Try operation promotion only if regular dag combine and target-specific ones failed...
[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 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NodesCombined   , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46
47 namespace {
48   static cl::opt<bool>
49     CombinerAA("combiner-alias-analysis", cl::Hidden,
50                cl::desc("Turn on alias analysis during testing"));
51
52   static cl::opt<bool>
53     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54                cl::desc("Include global information in alias analysis"));
55
56 //------------------------------ DAGCombiner ---------------------------------//
57
58   class DAGCombiner {
59     SelectionDAG &DAG;
60     const TargetLowering &TLI;
61     CombineLevel Level;
62     CodeGenOpt::Level OptLevel;
63     bool LegalOperations;
64     bool LegalTypes;
65
66     // Worklist of all of the nodes that need to be simplified.
67     std::vector<SDNode*> WorkList;
68
69     // AA - Used for DAG load/store alias analysis.
70     AliasAnalysis &AA;
71
72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
73     /// the instruction to the work lists because they might get more simplified
74     /// now.
75     ///
76     void AddUsersToWorkList(SDNode *N) {
77       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
78            UI != UE; ++UI)
79         AddToWorkList(*UI);
80     }
81
82     /// visit - call the node-specific routine that knows how to fold each
83     /// particular type of node.
84     SDValue visit(SDNode *N);
85
86   public:
87     /// AddToWorkList - Add to the work list making sure it's instance is at the
88     /// the back (next to be processed.)
89     void AddToWorkList(SDNode *N) {
90       removeFromWorkList(N);
91       WorkList.push_back(N);
92     }
93
94     /// removeFromWorkList - remove all instances of N from the worklist.
95     ///
96     void removeFromWorkList(SDNode *N) {
97       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
98                      WorkList.end());
99     }
100
101     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
102                       bool AddTo = true);
103
104     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105       return CombineTo(N, &Res, 1, AddTo);
106     }
107
108     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
109                       bool AddTo = true) {
110       SDValue To[] = { Res0, Res1 };
111       return CombineTo(N, To, 2, AddTo);
112     }
113
114     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
115
116   private:
117
118     /// SimplifyDemandedBits - Check the specified integer node value to see if
119     /// it can be simplified or if things it uses can be simplified by bit
120     /// propagation.  If so, return true.
121     bool SimplifyDemandedBits(SDValue Op) {
122       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123       APInt Demanded = APInt::getAllOnesValue(BitWidth);
124       return SimplifyDemandedBits(Op, Demanded);
125     }
126
127     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
128
129     bool CombineToPreIndexedLoadStore(SDNode *N);
130     bool CombineToPostIndexedLoadStore(SDNode *N);
131
132     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136     SDValue PromoteIntBinOp(SDValue Op);
137     SDValue PromoteIntShiftOp(SDValue Op);
138     SDValue PromoteExtend(SDValue Op);
139     bool PromoteLoad(SDValue Op);
140
141     /// combine - call the node-specific routine that knows how to fold each
142     /// particular type of node. If that doesn't do anything, try the
143     /// target-specific DAG combines.
144     SDValue combine(SDNode *N);
145
146     // Visitation implementation - Implement dag node combining for different
147     // node types.  The semantics are as follows:
148     // Return Value:
149     //   SDValue.getNode() == 0 - No change was made
150     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
151     //   otherwise              - N should be replaced by the returned Operand.
152     //
153     SDValue visitTokenFactor(SDNode *N);
154     SDValue visitMERGE_VALUES(SDNode *N);
155     SDValue visitADD(SDNode *N);
156     SDValue visitSUB(SDNode *N);
157     SDValue visitADDC(SDNode *N);
158     SDValue visitADDE(SDNode *N);
159     SDValue visitMUL(SDNode *N);
160     SDValue visitSDIV(SDNode *N);
161     SDValue visitUDIV(SDNode *N);
162     SDValue visitSREM(SDNode *N);
163     SDValue visitUREM(SDNode *N);
164     SDValue visitMULHU(SDNode *N);
165     SDValue visitMULHS(SDNode *N);
166     SDValue visitSMUL_LOHI(SDNode *N);
167     SDValue visitUMUL_LOHI(SDNode *N);
168     SDValue visitSDIVREM(SDNode *N);
169     SDValue visitUDIVREM(SDNode *N);
170     SDValue visitAND(SDNode *N);
171     SDValue visitOR(SDNode *N);
172     SDValue visitXOR(SDNode *N);
173     SDValue SimplifyVBinOp(SDNode *N);
174     SDValue visitSHL(SDNode *N);
175     SDValue visitSRA(SDNode *N);
176     SDValue visitSRL(SDNode *N);
177     SDValue visitCTLZ(SDNode *N);
178     SDValue visitCTTZ(SDNode *N);
179     SDValue visitCTPOP(SDNode *N);
180     SDValue visitSELECT(SDNode *N);
181     SDValue visitSELECT_CC(SDNode *N);
182     SDValue visitSETCC(SDNode *N);
183     SDValue visitSIGN_EXTEND(SDNode *N);
184     SDValue visitZERO_EXTEND(SDNode *N);
185     SDValue visitANY_EXTEND(SDNode *N);
186     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
187     SDValue visitTRUNCATE(SDNode *N);
188     SDValue visitBIT_CONVERT(SDNode *N);
189     SDValue visitBUILD_PAIR(SDNode *N);
190     SDValue visitFADD(SDNode *N);
191     SDValue visitFSUB(SDNode *N);
192     SDValue visitFMUL(SDNode *N);
193     SDValue visitFDIV(SDNode *N);
194     SDValue visitFREM(SDNode *N);
195     SDValue visitFCOPYSIGN(SDNode *N);
196     SDValue visitSINT_TO_FP(SDNode *N);
197     SDValue visitUINT_TO_FP(SDNode *N);
198     SDValue visitFP_TO_SINT(SDNode *N);
199     SDValue visitFP_TO_UINT(SDNode *N);
200     SDValue visitFP_ROUND(SDNode *N);
201     SDValue visitFP_ROUND_INREG(SDNode *N);
202     SDValue visitFP_EXTEND(SDNode *N);
203     SDValue visitFNEG(SDNode *N);
204     SDValue visitFABS(SDNode *N);
205     SDValue visitBRCOND(SDNode *N);
206     SDValue visitBR_CC(SDNode *N);
207     SDValue visitLOAD(SDNode *N);
208     SDValue visitSTORE(SDNode *N);
209     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
210     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
211     SDValue visitBUILD_VECTOR(SDNode *N);
212     SDValue visitCONCAT_VECTORS(SDNode *N);
213     SDValue visitVECTOR_SHUFFLE(SDNode *N);
214
215     SDValue XformToShuffleWithZero(SDNode *N);
216     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
217
218     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
219
220     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
221     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
222     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
223     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
224                              SDValue N3, ISD::CondCode CC,
225                              bool NotExtCompare = false);
226     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
227                           DebugLoc DL, bool foldBooleans = true);
228     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
229                                          unsigned HiOp);
230     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
231     SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
232     SDValue BuildSDIV(SDNode *N);
233     SDValue BuildUDIV(SDNode *N);
234     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
235     SDValue ReduceLoadWidth(SDNode *N);
236     SDValue ReduceLoadOpStoreWidth(SDNode *N);
237
238     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
239
240     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
241     /// looking for aliasing nodes and adding them to the Aliases vector.
242     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
243                           SmallVector<SDValue, 8> &Aliases);
244
245     /// isAlias - Return true if there is any possibility that the two addresses
246     /// overlap.
247     bool isAlias(SDValue Ptr1, int64_t Size1,
248                  const Value *SrcValue1, int SrcValueOffset1,
249                  unsigned SrcValueAlign1,
250                  SDValue Ptr2, int64_t Size2,
251                  const Value *SrcValue2, int SrcValueOffset2,
252                  unsigned SrcValueAlign2) const;
253
254     /// FindAliasInfo - Extracts the relevant alias information from the memory
255     /// node.  Returns true if the operand was a load.
256     bool FindAliasInfo(SDNode *N,
257                        SDValue &Ptr, int64_t &Size,
258                        const Value *&SrcValue, int &SrcValueOffset,
259                        unsigned &SrcValueAlignment) const;
260
261     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
262     /// looking for a better chain (aliasing node.)
263     SDValue FindBetterChain(SDNode *N, SDValue Chain);
264
265   public:
266     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
267       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
268         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
269
270     /// Run - runs the dag combiner on all nodes in the work list
271     void Run(CombineLevel AtLevel);
272     
273     SelectionDAG &getDAG() const { return DAG; }
274     
275     /// getShiftAmountTy - Returns a type large enough to hold any valid
276     /// shift amount - before type legalization these can be huge.
277     EVT getShiftAmountTy() {
278       return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
279     }
280     
281     /// isTypeLegal - This method returns true if we are running before type
282     /// legalization or if the specified VT is legal.
283     bool isTypeLegal(const EVT &VT) {
284       if (!LegalTypes) return true;
285       return TLI.isTypeLegal(VT);
286     }
287   };
288 }
289
290
291 namespace {
292 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
293 /// nodes from the worklist.
294 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
295   DAGCombiner &DC;
296 public:
297   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
298
299   virtual void NodeDeleted(SDNode *N, SDNode *E) {
300     DC.removeFromWorkList(N);
301   }
302
303   virtual void NodeUpdated(SDNode *N) {
304     // Ignore updates.
305   }
306 };
307 }
308
309 //===----------------------------------------------------------------------===//
310 //  TargetLowering::DAGCombinerInfo implementation
311 //===----------------------------------------------------------------------===//
312
313 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
314   ((DAGCombiner*)DC)->AddToWorkList(N);
315 }
316
317 SDValue TargetLowering::DAGCombinerInfo::
318 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
319   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
320 }
321
322 SDValue TargetLowering::DAGCombinerInfo::
323 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
324   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
325 }
326
327
328 SDValue TargetLowering::DAGCombinerInfo::
329 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
330   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
331 }
332
333 void TargetLowering::DAGCombinerInfo::
334 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
335   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
336 }
337
338 //===----------------------------------------------------------------------===//
339 // Helper Functions
340 //===----------------------------------------------------------------------===//
341
342 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
343 /// specified expression for the same cost as the expression itself, or 2 if we
344 /// can compute the negated form more cheaply than the expression itself.
345 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
346                                unsigned Depth = 0) {
347   // No compile time optimizations on this type.
348   if (Op.getValueType() == MVT::ppcf128)
349     return 0;
350
351   // fneg is removable even if it has multiple uses.
352   if (Op.getOpcode() == ISD::FNEG) return 2;
353
354   // Don't allow anything with multiple uses.
355   if (!Op.hasOneUse()) return 0;
356
357   // Don't recurse exponentially.
358   if (Depth > 6) return 0;
359
360   switch (Op.getOpcode()) {
361   default: return false;
362   case ISD::ConstantFP:
363     // Don't invert constant FP values after legalize.  The negated constant
364     // isn't necessarily legal.
365     return LegalOperations ? 0 : 1;
366   case ISD::FADD:
367     // FIXME: determine better conditions for this xform.
368     if (!UnsafeFPMath) return 0;
369
370     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
371     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
372       return V;
373     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
374     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
375   case ISD::FSUB:
376     // We can't turn -(A-B) into B-A when we honor signed zeros.
377     if (!UnsafeFPMath) return 0;
378
379     // fold (fneg (fsub A, B)) -> (fsub B, A)
380     return 1;
381
382   case ISD::FMUL:
383   case ISD::FDIV:
384     if (HonorSignDependentRoundingFPMath()) return 0;
385
386     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
387     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
388       return V;
389
390     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
391
392   case ISD::FP_EXTEND:
393   case ISD::FP_ROUND:
394   case ISD::FSIN:
395     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
396   }
397 }
398
399 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
400 /// returns the newly negated expression.
401 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
402                                     bool LegalOperations, unsigned Depth = 0) {
403   // fneg is removable even if it has multiple uses.
404   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
405
406   // Don't allow anything with multiple uses.
407   assert(Op.hasOneUse() && "Unknown reuse!");
408
409   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
410   switch (Op.getOpcode()) {
411   default: llvm_unreachable("Unknown code");
412   case ISD::ConstantFP: {
413     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
414     V.changeSign();
415     return DAG.getConstantFP(V, Op.getValueType());
416   }
417   case ISD::FADD:
418     // FIXME: determine better conditions for this xform.
419     assert(UnsafeFPMath);
420
421     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
422     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
423       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
424                          GetNegatedExpression(Op.getOperand(0), DAG,
425                                               LegalOperations, Depth+1),
426                          Op.getOperand(1));
427     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
428     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
429                        GetNegatedExpression(Op.getOperand(1), DAG,
430                                             LegalOperations, Depth+1),
431                        Op.getOperand(0));
432   case ISD::FSUB:
433     // We can't turn -(A-B) into B-A when we honor signed zeros.
434     assert(UnsafeFPMath);
435
436     // fold (fneg (fsub 0, B)) -> B
437     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
438       if (N0CFP->getValueAPF().isZero())
439         return Op.getOperand(1);
440
441     // fold (fneg (fsub A, B)) -> (fsub B, A)
442     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
443                        Op.getOperand(1), Op.getOperand(0));
444
445   case ISD::FMUL:
446   case ISD::FDIV:
447     assert(!HonorSignDependentRoundingFPMath());
448
449     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
450     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
451       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
452                          GetNegatedExpression(Op.getOperand(0), DAG,
453                                               LegalOperations, Depth+1),
454                          Op.getOperand(1));
455
456     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
457     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
458                        Op.getOperand(0),
459                        GetNegatedExpression(Op.getOperand(1), DAG,
460                                             LegalOperations, Depth+1));
461
462   case ISD::FP_EXTEND:
463   case ISD::FSIN:
464     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
465                        GetNegatedExpression(Op.getOperand(0), DAG,
466                                             LegalOperations, Depth+1));
467   case ISD::FP_ROUND:
468       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
469                          GetNegatedExpression(Op.getOperand(0), DAG,
470                                               LegalOperations, Depth+1),
471                          Op.getOperand(1));
472   }
473 }
474
475
476 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
477 // that selects between the values 1 and 0, making it equivalent to a setcc.
478 // Also, set the incoming LHS, RHS, and CC references to the appropriate
479 // nodes based on the type of node we are checking.  This simplifies life a
480 // bit for the callers.
481 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
482                               SDValue &CC) {
483   if (N.getOpcode() == ISD::SETCC) {
484     LHS = N.getOperand(0);
485     RHS = N.getOperand(1);
486     CC  = N.getOperand(2);
487     return true;
488   }
489   if (N.getOpcode() == ISD::SELECT_CC &&
490       N.getOperand(2).getOpcode() == ISD::Constant &&
491       N.getOperand(3).getOpcode() == ISD::Constant &&
492       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
493       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
494     LHS = N.getOperand(0);
495     RHS = N.getOperand(1);
496     CC  = N.getOperand(4);
497     return true;
498   }
499   return false;
500 }
501
502 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
503 // one use.  If this is true, it allows the users to invert the operation for
504 // free when it is profitable to do so.
505 static bool isOneUseSetCC(SDValue N) {
506   SDValue N0, N1, N2;
507   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
508     return true;
509   return false;
510 }
511
512 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
513                                     SDValue N0, SDValue N1) {
514   EVT VT = N0.getValueType();
515   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
516     if (isa<ConstantSDNode>(N1)) {
517       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
518       SDValue OpNode =
519         DAG.FoldConstantArithmetic(Opc, VT,
520                                    cast<ConstantSDNode>(N0.getOperand(1)),
521                                    cast<ConstantSDNode>(N1));
522       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
523     } else if (N0.hasOneUse()) {
524       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
525       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
526                                    N0.getOperand(0), N1);
527       AddToWorkList(OpNode.getNode());
528       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
529     }
530   }
531
532   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
533     if (isa<ConstantSDNode>(N0)) {
534       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
535       SDValue OpNode =
536         DAG.FoldConstantArithmetic(Opc, VT,
537                                    cast<ConstantSDNode>(N1.getOperand(1)),
538                                    cast<ConstantSDNode>(N0));
539       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
540     } else if (N1.hasOneUse()) {
541       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
542       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
543                                    N1.getOperand(0), N0);
544       AddToWorkList(OpNode.getNode());
545       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
546     }
547   }
548
549   return SDValue();
550 }
551
552 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
553                                bool AddTo) {
554   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
555   ++NodesCombined;
556   DEBUG(dbgs() << "\nReplacing.1 ";
557         N->dump(&DAG);
558         dbgs() << "\nWith: ";
559         To[0].getNode()->dump(&DAG);
560         dbgs() << " and " << NumTo-1 << " other values\n";
561         for (unsigned i = 0, e = NumTo; i != e; ++i)
562           assert((!To[i].getNode() ||
563                   N->getValueType(i) == To[i].getValueType()) &&
564                  "Cannot combine value to value of different type!"));
565   WorkListRemover DeadNodes(*this);
566   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
567
568   if (AddTo) {
569     // Push the new nodes and any users onto the worklist
570     for (unsigned i = 0, e = NumTo; i != e; ++i) {
571       if (To[i].getNode()) {
572         AddToWorkList(To[i].getNode());
573         AddUsersToWorkList(To[i].getNode());
574       }
575     }
576   }
577
578   // Finally, if the node is now dead, remove it from the graph.  The node
579   // may not be dead if the replacement process recursively simplified to
580   // something else needing this node.
581   if (N->use_empty()) {
582     // Nodes can be reintroduced into the worklist.  Make sure we do not
583     // process a node that has been replaced.
584     removeFromWorkList(N);
585
586     // Finally, since the node is now dead, remove it from the graph.
587     DAG.DeleteNode(N);
588   }
589   return SDValue(N, 0);
590 }
591
592 void DAGCombiner::
593 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
594   // Replace all uses.  If any nodes become isomorphic to other nodes and
595   // are deleted, make sure to remove them from our worklist.
596   WorkListRemover DeadNodes(*this);
597   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
598
599   // Push the new node and any (possibly new) users onto the worklist.
600   AddToWorkList(TLO.New.getNode());
601   AddUsersToWorkList(TLO.New.getNode());
602
603   // Finally, if the node is now dead, remove it from the graph.  The node
604   // may not be dead if the replacement process recursively simplified to
605   // something else needing this node.
606   if (TLO.Old.getNode()->use_empty()) {
607     removeFromWorkList(TLO.Old.getNode());
608
609     // If the operands of this node are only used by the node, they will now
610     // be dead.  Make sure to visit them first to delete dead nodes early.
611     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
612       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
613         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
614
615     DAG.DeleteNode(TLO.Old.getNode());
616   }
617 }
618
619 /// SimplifyDemandedBits - Check the specified integer node value to see if
620 /// it can be simplified or if things it uses can be simplified by bit
621 /// propagation.  If so, return true.
622 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
623   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
624   APInt KnownZero, KnownOne;
625   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
626     return false;
627
628   // Revisit the node.
629   AddToWorkList(Op.getNode());
630
631   // Replace the old value with the new one.
632   ++NodesCombined;
633   DEBUG(dbgs() << "\nReplacing.2 "; 
634         TLO.Old.getNode()->dump(&DAG);
635         dbgs() << "\nWith: ";
636         TLO.New.getNode()->dump(&DAG);
637         dbgs() << '\n');
638
639   CommitTargetLoweringOpt(TLO);
640   return true;
641 }
642
643 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
644   DebugLoc dl = Load->getDebugLoc();
645   EVT VT = Load->getValueType(0);
646   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
647
648   DEBUG(dbgs() << "\nReplacing.9 ";
649         Load->dump(&DAG);
650         dbgs() << "\nWith: ";
651         Trunc.getNode()->dump(&DAG);
652         dbgs() << '\n');
653   WorkListRemover DeadNodes(*this);
654   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
655   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
656                                 &DeadNodes);
657   removeFromWorkList(Load);
658   DAG.DeleteNode(Load);
659   AddToWorkList(Trunc.getNode());
660 }
661
662 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
663   Replace = false;
664   DebugLoc dl = Op.getDebugLoc();
665   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
666     EVT MemVT = LD->getMemoryVT();
667     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
668       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
669       : LD->getExtensionType();
670     Replace = true;
671     return DAG.getExtLoad(ExtType, dl, PVT,
672                           LD->getChain(), LD->getBasePtr(),
673                           LD->getSrcValue(), LD->getSrcValueOffset(),
674                           MemVT, LD->isVolatile(),
675                           LD->isNonTemporal(), LD->getAlignment());
676   }
677
678   unsigned Opc = Op.getOpcode();
679   switch (Opc) {
680   default: break;
681   case ISD::AssertSext:
682     return DAG.getNode(ISD::AssertSext, dl, PVT,
683                        SExtPromoteOperand(Op.getOperand(0), PVT),
684                        Op.getOperand(1));
685   case ISD::AssertZext:
686     return DAG.getNode(ISD::AssertZext, dl, PVT,
687                        ZExtPromoteOperand(Op.getOperand(0), PVT),
688                        Op.getOperand(1));
689   case ISD::Constant: {
690     unsigned ExtOpc =
691       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
692     return DAG.getNode(ExtOpc, dl, PVT, Op);
693   }    
694   }
695
696   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
697     return SDValue();
698   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
699 }
700
701 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
702   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
703     return SDValue();
704   EVT OldVT = Op.getValueType();
705   DebugLoc dl = Op.getDebugLoc();
706   bool Replace = false;
707   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
708   if (NewOp.getNode() == 0)
709     return SDValue();
710   AddToWorkList(NewOp.getNode());
711
712   if (Replace)
713     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
714   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
715                      DAG.getValueType(OldVT));
716 }
717
718 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
719   EVT OldVT = Op.getValueType();
720   DebugLoc dl = Op.getDebugLoc();
721   bool Replace = false;
722   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
723   if (NewOp.getNode() == 0)
724     return SDValue();
725   AddToWorkList(NewOp.getNode());
726
727   if (Replace)
728     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
729   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
730 }
731
732 /// PromoteIntBinOp - Promote the specified integer binary operation if the
733 /// target indicates it is beneficial. e.g. On x86, it's usually better to
734 /// promote i16 operations to i32 since i16 instructions are longer.
735 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
736   if (!LegalOperations)
737     return SDValue();
738
739   EVT VT = Op.getValueType();
740   if (VT.isVector() || !VT.isInteger())
741     return SDValue();
742
743   // If operation type is 'undesirable', e.g. i16 on x86, consider
744   // promoting it.
745   unsigned Opc = Op.getOpcode();
746   if (TLI.isTypeDesirableForOp(Opc, VT))
747     return SDValue();
748
749   EVT PVT = VT;
750   // Consult target whether it is a good idea to promote this operation and
751   // what's the right type to promote it to.
752   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
753     assert(PVT != VT && "Don't know what type to promote to!");
754
755     bool Replace0 = false;
756     SDValue N0 = Op.getOperand(0);
757     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
758     if (NN0.getNode() == 0)
759       return SDValue();
760
761     bool Replace1 = false;
762     SDValue N1 = Op.getOperand(1);
763     SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
764     if (NN1.getNode() == 0)
765       return SDValue();
766
767     AddToWorkList(NN0.getNode());
768     AddToWorkList(NN1.getNode());
769
770     if (Replace0)
771       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
772     if (Replace1)
773       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
774
775     DEBUG(dbgs() << "\nPromoting ";
776           Op.getNode()->dump(&DAG));
777     DebugLoc dl = Op.getDebugLoc();
778     return DAG.getNode(ISD::TRUNCATE, dl, VT,
779                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
780   }
781   return SDValue();
782 }
783
784 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
785 /// target indicates it is beneficial. e.g. On x86, it's usually better to
786 /// promote i16 operations to i32 since i16 instructions are longer.
787 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
788   if (!LegalOperations)
789     return SDValue();
790
791   EVT VT = Op.getValueType();
792   if (VT.isVector() || !VT.isInteger())
793     return SDValue();
794
795   // If operation type is 'undesirable', e.g. i16 on x86, consider
796   // promoting it.
797   unsigned Opc = Op.getOpcode();
798   if (TLI.isTypeDesirableForOp(Opc, VT))
799     return SDValue();
800
801   EVT PVT = VT;
802   // Consult target whether it is a good idea to promote this operation and
803   // what's the right type to promote it to.
804   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
805     assert(PVT != VT && "Don't know what type to promote to!");
806
807     bool Replace = false;
808     SDValue N0 = Op.getOperand(0);
809     if (Opc == ISD::SRA)
810       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
811     else if (Opc == ISD::SRL)
812       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
813     else
814       N0 = PromoteOperand(N0, PVT, Replace);
815     if (N0.getNode() == 0)
816       return SDValue();
817
818     AddToWorkList(N0.getNode());
819     if (Replace)
820       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
821
822     DEBUG(dbgs() << "\nPromoting ";
823           Op.getNode()->dump(&DAG));
824     DebugLoc dl = Op.getDebugLoc();
825     return DAG.getNode(ISD::TRUNCATE, dl, VT,
826                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
827   }
828   return SDValue();
829 }
830
831 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
832   if (!LegalOperations)
833     return SDValue();
834
835   EVT VT = Op.getValueType();
836   if (VT.isVector() || !VT.isInteger())
837     return SDValue();
838
839   // If operation type is 'undesirable', e.g. i16 on x86, consider
840   // promoting it.
841   unsigned Opc = Op.getOpcode();
842   if (TLI.isTypeDesirableForOp(Opc, VT))
843     return SDValue();
844
845   EVT PVT = VT;
846   // Consult target whether it is a good idea to promote this operation and
847   // what's the right type to promote it to.
848   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
849     assert(PVT != VT && "Don't know what type to promote to!");
850     // fold (aext (aext x)) -> (aext x)
851     // fold (aext (zext x)) -> (zext x)
852     // fold (aext (sext x)) -> (sext x)
853     DEBUG(dbgs() << "\nPromoting ";
854           Op.getNode()->dump(&DAG));
855     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
856   }
857   return SDValue();
858 }
859
860 bool DAGCombiner::PromoteLoad(SDValue Op) {
861   if (!LegalOperations)
862     return false;
863
864   EVT VT = Op.getValueType();
865   if (VT.isVector() || !VT.isInteger())
866     return false;
867
868   // If operation type is 'undesirable', e.g. i16 on x86, consider
869   // promoting it.
870   unsigned Opc = Op.getOpcode();
871   if (TLI.isTypeDesirableForOp(Opc, VT))
872     return false;
873
874   EVT PVT = VT;
875   // Consult target whether it is a good idea to promote this operation and
876   // what's the right type to promote it to.
877   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
878     assert(PVT != VT && "Don't know what type to promote to!");
879
880     DebugLoc dl = Op.getDebugLoc();
881     SDNode *N = Op.getNode();
882     LoadSDNode *LD = cast<LoadSDNode>(N);
883     EVT MemVT = LD->getMemoryVT();
884     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
885       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
886       : LD->getExtensionType();
887     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
888                                    LD->getChain(), LD->getBasePtr(),
889                                    LD->getSrcValue(), LD->getSrcValueOffset(),
890                                    MemVT, LD->isVolatile(),
891                                    LD->isNonTemporal(), LD->getAlignment());
892     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
893
894     DEBUG(dbgs() << "\nPromoting ";
895           N->dump(&DAG);
896           dbgs() << "\nTo: ";
897           Result.getNode()->dump(&DAG);
898           dbgs() << '\n');
899     WorkListRemover DeadNodes(*this);
900     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
901     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
902     removeFromWorkList(N);
903     DAG.DeleteNode(N);
904     AddToWorkList(Result.getNode());
905     return true;
906   }
907   return false;
908 }
909
910
911 //===----------------------------------------------------------------------===//
912 //  Main DAG Combiner implementation
913 //===----------------------------------------------------------------------===//
914
915 void DAGCombiner::Run(CombineLevel AtLevel) {
916   // set the instance variables, so that the various visit routines may use it.
917   Level = AtLevel;
918   LegalOperations = Level >= NoIllegalOperations;
919   LegalTypes = Level >= NoIllegalTypes;
920
921   // Add all the dag nodes to the worklist.
922   WorkList.reserve(DAG.allnodes_size());
923   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
924        E = DAG.allnodes_end(); I != E; ++I)
925     WorkList.push_back(I);
926
927   // Create a dummy node (which is not added to allnodes), that adds a reference
928   // to the root node, preventing it from being deleted, and tracking any
929   // changes of the root.
930   HandleSDNode Dummy(DAG.getRoot());
931
932   // The root of the dag may dangle to deleted nodes until the dag combiner is
933   // done.  Set it to null to avoid confusion.
934   DAG.setRoot(SDValue());
935
936   // while the worklist isn't empty, inspect the node on the end of it and
937   // try and combine it.
938   while (!WorkList.empty()) {
939     SDNode *N = WorkList.back();
940     WorkList.pop_back();
941
942     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
943     // N is deleted from the DAG, since they too may now be dead or may have a
944     // reduced number of uses, allowing other xforms.
945     if (N->use_empty() && N != &Dummy) {
946       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
947         AddToWorkList(N->getOperand(i).getNode());
948
949       DAG.DeleteNode(N);
950       continue;
951     }
952
953     SDValue RV = combine(N);
954
955     if (RV.getNode() == 0)
956       continue;
957
958     ++NodesCombined;
959
960     // If we get back the same node we passed in, rather than a new node or
961     // zero, we know that the node must have defined multiple values and
962     // CombineTo was used.  Since CombineTo takes care of the worklist
963     // mechanics for us, we have no work to do in this case.
964     if (RV.getNode() == N)
965       continue;
966
967     assert(N->getOpcode() != ISD::DELETED_NODE &&
968            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
969            "Node was deleted but visit returned new node!");
970
971     DEBUG(dbgs() << "\nReplacing.3 "; 
972           N->dump(&DAG);
973           dbgs() << "\nWith: ";
974           RV.getNode()->dump(&DAG);
975           dbgs() << '\n');
976     WorkListRemover DeadNodes(*this);
977     if (N->getNumValues() == RV.getNode()->getNumValues())
978       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
979     else {
980       assert(N->getValueType(0) == RV.getValueType() &&
981              N->getNumValues() == 1 && "Type mismatch");
982       SDValue OpV = RV;
983       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
984     }
985
986     // Push the new node and any users onto the worklist
987     AddToWorkList(RV.getNode());
988     AddUsersToWorkList(RV.getNode());
989
990     // Add any uses of the old node to the worklist in case this node is the
991     // last one that uses them.  They may become dead after this node is
992     // deleted.
993     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
994       AddToWorkList(N->getOperand(i).getNode());
995
996     // Finally, if the node is now dead, remove it from the graph.  The node
997     // may not be dead if the replacement process recursively simplified to
998     // something else needing this node.
999     if (N->use_empty()) {
1000       // Nodes can be reintroduced into the worklist.  Make sure we do not
1001       // process a node that has been replaced.
1002       removeFromWorkList(N);
1003
1004       // Finally, since the node is now dead, remove it from the graph.
1005       DAG.DeleteNode(N);
1006     }
1007   }
1008
1009   // If the root changed (e.g. it was a dead load, update the root).
1010   DAG.setRoot(Dummy.getValue());
1011 }
1012
1013 SDValue DAGCombiner::visit(SDNode *N) {
1014   switch (N->getOpcode()) {
1015   default: break;
1016   case ISD::TokenFactor:        return visitTokenFactor(N);
1017   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1018   case ISD::ADD:                return visitADD(N);
1019   case ISD::SUB:                return visitSUB(N);
1020   case ISD::ADDC:               return visitADDC(N);
1021   case ISD::ADDE:               return visitADDE(N);
1022   case ISD::MUL:                return visitMUL(N);
1023   case ISD::SDIV:               return visitSDIV(N);
1024   case ISD::UDIV:               return visitUDIV(N);
1025   case ISD::SREM:               return visitSREM(N);
1026   case ISD::UREM:               return visitUREM(N);
1027   case ISD::MULHU:              return visitMULHU(N);
1028   case ISD::MULHS:              return visitMULHS(N);
1029   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1030   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1031   case ISD::SDIVREM:            return visitSDIVREM(N);
1032   case ISD::UDIVREM:            return visitUDIVREM(N);
1033   case ISD::AND:                return visitAND(N);
1034   case ISD::OR:                 return visitOR(N);
1035   case ISD::XOR:                return visitXOR(N);
1036   case ISD::SHL:                return visitSHL(N);
1037   case ISD::SRA:                return visitSRA(N);
1038   case ISD::SRL:                return visitSRL(N);
1039   case ISD::CTLZ:               return visitCTLZ(N);
1040   case ISD::CTTZ:               return visitCTTZ(N);
1041   case ISD::CTPOP:              return visitCTPOP(N);
1042   case ISD::SELECT:             return visitSELECT(N);
1043   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1044   case ISD::SETCC:              return visitSETCC(N);
1045   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1046   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1047   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1048   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1049   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1050   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
1051   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1052   case ISD::FADD:               return visitFADD(N);
1053   case ISD::FSUB:               return visitFSUB(N);
1054   case ISD::FMUL:               return visitFMUL(N);
1055   case ISD::FDIV:               return visitFDIV(N);
1056   case ISD::FREM:               return visitFREM(N);
1057   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1058   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1059   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1060   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1061   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1062   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1063   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1064   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1065   case ISD::FNEG:               return visitFNEG(N);
1066   case ISD::FABS:               return visitFABS(N);
1067   case ISD::BRCOND:             return visitBRCOND(N);
1068   case ISD::BR_CC:              return visitBR_CC(N);
1069   case ISD::LOAD:               return visitLOAD(N);
1070   case ISD::STORE:              return visitSTORE(N);
1071   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1072   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1073   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1074   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1075   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1076   }
1077   return SDValue();
1078 }
1079
1080 SDValue DAGCombiner::combine(SDNode *N) {
1081   SDValue RV = visit(N);
1082
1083   // If nothing happened, try a target-specific DAG combine.
1084   if (RV.getNode() == 0) {
1085     assert(N->getOpcode() != ISD::DELETED_NODE &&
1086            "Node was deleted but visit returned NULL!");
1087
1088     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1089         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1090
1091       // Expose the DAG combiner to the target combiner impls.
1092       TargetLowering::DAGCombinerInfo
1093         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1094
1095       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1096     }
1097   }
1098
1099   // If nothing happened still, try promoting the operation.
1100   if (RV.getNode() == 0) {
1101     switch (N->getOpcode()) {
1102     default: break;
1103     case ISD::ADD:
1104     case ISD::SUB:
1105     case ISD::MUL:
1106     case ISD::AND:
1107     case ISD::OR:
1108     case ISD::XOR:
1109       RV = PromoteIntBinOp(SDValue(N, 0));
1110       break;
1111     case ISD::SHL:
1112     case ISD::SRA:
1113     case ISD::SRL:
1114       RV = PromoteIntShiftOp(SDValue(N, 0));
1115       break;
1116     case ISD::SIGN_EXTEND:
1117     case ISD::ZERO_EXTEND:
1118     case ISD::ANY_EXTEND:
1119       RV = PromoteExtend(SDValue(N, 0));
1120       break;
1121     case ISD::LOAD:
1122       if (PromoteLoad(SDValue(N, 0)))
1123         RV = SDValue(N, 0);
1124       break;
1125     }
1126   }
1127
1128   // If N is a commutative binary node, try commuting it to enable more
1129   // sdisel CSE.
1130   if (RV.getNode() == 0 &&
1131       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1132       N->getNumValues() == 1) {
1133     SDValue N0 = N->getOperand(0);
1134     SDValue N1 = N->getOperand(1);
1135
1136     // Constant operands are canonicalized to RHS.
1137     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1138       SDValue Ops[] = { N1, N0 };
1139       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1140                                             Ops, 2);
1141       if (CSENode)
1142         return SDValue(CSENode, 0);
1143     }
1144   }
1145
1146   return RV;
1147 }
1148
1149 /// getInputChainForNode - Given a node, return its input chain if it has one,
1150 /// otherwise return a null sd operand.
1151 static SDValue getInputChainForNode(SDNode *N) {
1152   if (unsigned NumOps = N->getNumOperands()) {
1153     if (N->getOperand(0).getValueType() == MVT::Other)
1154       return N->getOperand(0);
1155     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1156       return N->getOperand(NumOps-1);
1157     for (unsigned i = 1; i < NumOps-1; ++i)
1158       if (N->getOperand(i).getValueType() == MVT::Other)
1159         return N->getOperand(i);
1160   }
1161   return SDValue();
1162 }
1163
1164 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1165   // If N has two operands, where one has an input chain equal to the other,
1166   // the 'other' chain is redundant.
1167   if (N->getNumOperands() == 2) {
1168     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1169       return N->getOperand(0);
1170     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1171       return N->getOperand(1);
1172   }
1173
1174   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1175   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1176   SmallPtrSet<SDNode*, 16> SeenOps;
1177   bool Changed = false;             // If we should replace this token factor.
1178
1179   // Start out with this token factor.
1180   TFs.push_back(N);
1181
1182   // Iterate through token factors.  The TFs grows when new token factors are
1183   // encountered.
1184   for (unsigned i = 0; i < TFs.size(); ++i) {
1185     SDNode *TF = TFs[i];
1186
1187     // Check each of the operands.
1188     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1189       SDValue Op = TF->getOperand(i);
1190
1191       switch (Op.getOpcode()) {
1192       case ISD::EntryToken:
1193         // Entry tokens don't need to be added to the list. They are
1194         // rededundant.
1195         Changed = true;
1196         break;
1197
1198       case ISD::TokenFactor:
1199         if (Op.hasOneUse() &&
1200             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1201           // Queue up for processing.
1202           TFs.push_back(Op.getNode());
1203           // Clean up in case the token factor is removed.
1204           AddToWorkList(Op.getNode());
1205           Changed = true;
1206           break;
1207         }
1208         // Fall thru
1209
1210       default:
1211         // Only add if it isn't already in the list.
1212         if (SeenOps.insert(Op.getNode()))
1213           Ops.push_back(Op);
1214         else
1215           Changed = true;
1216         break;
1217       }
1218     }
1219   }
1220   
1221   SDValue Result;
1222
1223   // If we've change things around then replace token factor.
1224   if (Changed) {
1225     if (Ops.empty()) {
1226       // The entry token is the only possible outcome.
1227       Result = DAG.getEntryNode();
1228     } else {
1229       // New and improved token factor.
1230       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1231                            MVT::Other, &Ops[0], Ops.size());
1232     }
1233
1234     // Don't add users to work list.
1235     return CombineTo(N, Result, false);
1236   }
1237
1238   return Result;
1239 }
1240
1241 /// MERGE_VALUES can always be eliminated.
1242 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1243   WorkListRemover DeadNodes(*this);
1244   // Replacing results may cause a different MERGE_VALUES to suddenly
1245   // be CSE'd with N, and carry its uses with it. Iterate until no
1246   // uses remain, to ensure that the node can be safely deleted.
1247   do {
1248     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1249       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1250                                     &DeadNodes);
1251   } while (!N->use_empty());
1252   removeFromWorkList(N);
1253   DAG.DeleteNode(N);
1254   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1255 }
1256
1257 static
1258 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1259                               SelectionDAG &DAG) {
1260   EVT VT = N0.getValueType();
1261   SDValue N00 = N0.getOperand(0);
1262   SDValue N01 = N0.getOperand(1);
1263   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1264
1265   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1266       isa<ConstantSDNode>(N00.getOperand(1))) {
1267     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1268     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1269                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1270                                  N00.getOperand(0), N01),
1271                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1272                                  N00.getOperand(1), N01));
1273     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1274   }
1275
1276   return SDValue();
1277 }
1278
1279 SDValue DAGCombiner::visitADD(SDNode *N) {
1280   SDValue N0 = N->getOperand(0);
1281   SDValue N1 = N->getOperand(1);
1282   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1283   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1284   EVT VT = N0.getValueType();
1285
1286   // fold vector ops
1287   if (VT.isVector()) {
1288     SDValue FoldedVOp = SimplifyVBinOp(N);
1289     if (FoldedVOp.getNode()) return FoldedVOp;
1290   }
1291
1292   // fold (add x, undef) -> undef
1293   if (N0.getOpcode() == ISD::UNDEF)
1294     return N0;
1295   if (N1.getOpcode() == ISD::UNDEF)
1296     return N1;
1297   // fold (add c1, c2) -> c1+c2
1298   if (N0C && N1C)
1299     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1300   // canonicalize constant to RHS
1301   if (N0C && !N1C)
1302     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1303   // fold (add x, 0) -> x
1304   if (N1C && N1C->isNullValue())
1305     return N0;
1306   // fold (add Sym, c) -> Sym+c
1307   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1308     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1309         GA->getOpcode() == ISD::GlobalAddress)
1310       return DAG.getGlobalAddress(GA->getGlobal(), VT,
1311                                   GA->getOffset() +
1312                                     (uint64_t)N1C->getSExtValue());
1313   // fold ((c1-A)+c2) -> (c1+c2)-A
1314   if (N1C && N0.getOpcode() == ISD::SUB)
1315     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1316       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1317                          DAG.getConstant(N1C->getAPIntValue()+
1318                                          N0C->getAPIntValue(), VT),
1319                          N0.getOperand(1));
1320   // reassociate add
1321   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1322   if (RADD.getNode() != 0)
1323     return RADD;
1324   // fold ((0-A) + B) -> B-A
1325   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1326       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1327     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1328   // fold (A + (0-B)) -> A-B
1329   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1330       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1331     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1332   // fold (A+(B-A)) -> B
1333   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1334     return N1.getOperand(0);
1335   // fold ((B-A)+A) -> B
1336   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1337     return N0.getOperand(0);
1338   // fold (A+(B-(A+C))) to (B-C)
1339   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1340       N0 == N1.getOperand(1).getOperand(0))
1341     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1342                        N1.getOperand(1).getOperand(1));
1343   // fold (A+(B-(C+A))) to (B-C)
1344   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1345       N0 == N1.getOperand(1).getOperand(1))
1346     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1347                        N1.getOperand(1).getOperand(0));
1348   // fold (A+((B-A)+or-C)) to (B+or-C)
1349   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1350       N1.getOperand(0).getOpcode() == ISD::SUB &&
1351       N0 == N1.getOperand(0).getOperand(1))
1352     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1353                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1354
1355   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1356   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1357     SDValue N00 = N0.getOperand(0);
1358     SDValue N01 = N0.getOperand(1);
1359     SDValue N10 = N1.getOperand(0);
1360     SDValue N11 = N1.getOperand(1);
1361
1362     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1363       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1364                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1365                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1366   }
1367
1368   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1369     return SDValue(N, 0);
1370
1371   // fold (a+b) -> (a|b) iff a and b share no bits.
1372   if (VT.isInteger() && !VT.isVector()) {
1373     APInt LHSZero, LHSOne;
1374     APInt RHSZero, RHSOne;
1375     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1376     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1377
1378     if (LHSZero.getBoolValue()) {
1379       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1380
1381       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1382       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1383       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1384           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1385         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1386     }
1387   }
1388
1389   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1390   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1391     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1392     if (Result.getNode()) return Result;
1393   }
1394   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1395     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1396     if (Result.getNode()) return Result;
1397   }
1398
1399   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1400   if (N1.getOpcode() == ISD::SHL &&
1401       N1.getOperand(0).getOpcode() == ISD::SUB)
1402     if (ConstantSDNode *C =
1403           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1404       if (C->getAPIntValue() == 0)
1405         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1406                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1407                                        N1.getOperand(0).getOperand(1),
1408                                        N1.getOperand(1)));
1409   if (N0.getOpcode() == ISD::SHL &&
1410       N0.getOperand(0).getOpcode() == ISD::SUB)
1411     if (ConstantSDNode *C =
1412           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1413       if (C->getAPIntValue() == 0)
1414         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1415                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1416                                        N0.getOperand(0).getOperand(1),
1417                                        N0.getOperand(1)));
1418
1419   return SDValue();
1420 }
1421
1422 SDValue DAGCombiner::visitADDC(SDNode *N) {
1423   SDValue N0 = N->getOperand(0);
1424   SDValue N1 = N->getOperand(1);
1425   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1426   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1427   EVT VT = N0.getValueType();
1428
1429   // If the flag result is dead, turn this into an ADD.
1430   if (N->hasNUsesOfValue(0, 1))
1431     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1432                      DAG.getNode(ISD::CARRY_FALSE,
1433                                  N->getDebugLoc(), MVT::Flag));
1434
1435   // canonicalize constant to RHS.
1436   if (N0C && !N1C)
1437     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1438
1439   // fold (addc x, 0) -> x + no carry out
1440   if (N1C && N1C->isNullValue())
1441     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1442                                         N->getDebugLoc(), MVT::Flag));
1443
1444   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1445   APInt LHSZero, LHSOne;
1446   APInt RHSZero, RHSOne;
1447   APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1448   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1449
1450   if (LHSZero.getBoolValue()) {
1451     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1452
1453     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1454     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1455     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1456         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1457       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1458                        DAG.getNode(ISD::CARRY_FALSE,
1459                                    N->getDebugLoc(), MVT::Flag));
1460   }
1461
1462   return SDValue();
1463 }
1464
1465 SDValue DAGCombiner::visitADDE(SDNode *N) {
1466   SDValue N0 = N->getOperand(0);
1467   SDValue N1 = N->getOperand(1);
1468   SDValue CarryIn = N->getOperand(2);
1469   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1470   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1471
1472   // canonicalize constant to RHS
1473   if (N0C && !N1C)
1474     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1475                        N1, N0, CarryIn);
1476
1477   // fold (adde x, y, false) -> (addc x, y)
1478   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1479     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1480
1481   return SDValue();
1482 }
1483
1484 SDValue DAGCombiner::visitSUB(SDNode *N) {
1485   SDValue N0 = N->getOperand(0);
1486   SDValue N1 = N->getOperand(1);
1487   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1488   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1489   EVT VT = N0.getValueType();
1490
1491   // fold vector ops
1492   if (VT.isVector()) {
1493     SDValue FoldedVOp = SimplifyVBinOp(N);
1494     if (FoldedVOp.getNode()) return FoldedVOp;
1495   }
1496
1497   // fold (sub x, x) -> 0
1498   if (N0 == N1)
1499     return DAG.getConstant(0, N->getValueType(0));
1500   // fold (sub c1, c2) -> c1-c2
1501   if (N0C && N1C)
1502     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1503   // fold (sub x, c) -> (add x, -c)
1504   if (N1C)
1505     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1506                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1507   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1508   if (N0C && N0C->isAllOnesValue())
1509     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1510   // fold (A+B)-A -> B
1511   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1512     return N0.getOperand(1);
1513   // fold (A+B)-B -> A
1514   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1515     return N0.getOperand(0);
1516   // fold ((A+(B+or-C))-B) -> A+or-C
1517   if (N0.getOpcode() == ISD::ADD &&
1518       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1519        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1520       N0.getOperand(1).getOperand(0) == N1)
1521     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1522                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1523   // fold ((A+(C+B))-B) -> A+C
1524   if (N0.getOpcode() == ISD::ADD &&
1525       N0.getOperand(1).getOpcode() == ISD::ADD &&
1526       N0.getOperand(1).getOperand(1) == N1)
1527     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1528                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1529   // fold ((A-(B-C))-C) -> A-B
1530   if (N0.getOpcode() == ISD::SUB &&
1531       N0.getOperand(1).getOpcode() == ISD::SUB &&
1532       N0.getOperand(1).getOperand(1) == N1)
1533     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1534                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1535
1536   // If either operand of a sub is undef, the result is undef
1537   if (N0.getOpcode() == ISD::UNDEF)
1538     return N0;
1539   if (N1.getOpcode() == ISD::UNDEF)
1540     return N1;
1541
1542   // If the relocation model supports it, consider symbol offsets.
1543   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1544     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1545       // fold (sub Sym, c) -> Sym-c
1546       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1547         return DAG.getGlobalAddress(GA->getGlobal(), VT,
1548                                     GA->getOffset() -
1549                                       (uint64_t)N1C->getSExtValue());
1550       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1551       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1552         if (GA->getGlobal() == GB->getGlobal())
1553           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1554                                  VT);
1555     }
1556
1557   return SDValue();
1558 }
1559
1560 SDValue DAGCombiner::visitMUL(SDNode *N) {
1561   SDValue N0 = N->getOperand(0);
1562   SDValue N1 = N->getOperand(1);
1563   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1565   EVT VT = N0.getValueType();
1566
1567   // fold vector ops
1568   if (VT.isVector()) {
1569     SDValue FoldedVOp = SimplifyVBinOp(N);
1570     if (FoldedVOp.getNode()) return FoldedVOp;
1571   }
1572
1573   // fold (mul x, undef) -> 0
1574   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1575     return DAG.getConstant(0, VT);
1576   // fold (mul c1, c2) -> c1*c2
1577   if (N0C && N1C)
1578     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1579   // canonicalize constant to RHS
1580   if (N0C && !N1C)
1581     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1582   // fold (mul x, 0) -> 0
1583   if (N1C && N1C->isNullValue())
1584     return N1;
1585   // fold (mul x, -1) -> 0-x
1586   if (N1C && N1C->isAllOnesValue())
1587     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1588                        DAG.getConstant(0, VT), N0);
1589   // fold (mul x, (1 << c)) -> x << c
1590   if (N1C && N1C->getAPIntValue().isPowerOf2())
1591     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1592                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1593                                        getShiftAmountTy()));
1594   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1595   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1596     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1597     // FIXME: If the input is something that is easily negated (e.g. a
1598     // single-use add), we should put the negate there.
1599     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1600                        DAG.getConstant(0, VT),
1601                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1602                             DAG.getConstant(Log2Val, getShiftAmountTy())));
1603   }
1604   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1605   if (N1C && N0.getOpcode() == ISD::SHL &&
1606       isa<ConstantSDNode>(N0.getOperand(1))) {
1607     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1608                              N1, N0.getOperand(1));
1609     AddToWorkList(C3.getNode());
1610     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1611                        N0.getOperand(0), C3);
1612   }
1613
1614   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1615   // use.
1616   {
1617     SDValue Sh(0,0), Y(0,0);
1618     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1619     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1620         N0.getNode()->hasOneUse()) {
1621       Sh = N0; Y = N1;
1622     } else if (N1.getOpcode() == ISD::SHL &&
1623                isa<ConstantSDNode>(N1.getOperand(1)) &&
1624                N1.getNode()->hasOneUse()) {
1625       Sh = N1; Y = N0;
1626     }
1627
1628     if (Sh.getNode()) {
1629       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1630                                 Sh.getOperand(0), Y);
1631       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1632                          Mul, Sh.getOperand(1));
1633     }
1634   }
1635
1636   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1637   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1638       isa<ConstantSDNode>(N0.getOperand(1)))
1639     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1640                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1641                                    N0.getOperand(0), N1),
1642                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1643                                    N0.getOperand(1), N1));
1644
1645   // reassociate mul
1646   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1647   if (RMUL.getNode() != 0)
1648     return RMUL;
1649
1650   return SDValue();
1651 }
1652
1653 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1654   SDValue N0 = N->getOperand(0);
1655   SDValue N1 = N->getOperand(1);
1656   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1657   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1658   EVT VT = N->getValueType(0);
1659
1660   // fold vector ops
1661   if (VT.isVector()) {
1662     SDValue FoldedVOp = SimplifyVBinOp(N);
1663     if (FoldedVOp.getNode()) return FoldedVOp;
1664   }
1665
1666   // fold (sdiv c1, c2) -> c1/c2
1667   if (N0C && N1C && !N1C->isNullValue())
1668     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1669   // fold (sdiv X, 1) -> X
1670   if (N1C && N1C->getSExtValue() == 1LL)
1671     return N0;
1672   // fold (sdiv X, -1) -> 0-X
1673   if (N1C && N1C->isAllOnesValue())
1674     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1675                        DAG.getConstant(0, VT), N0);
1676   // If we know the sign bits of both operands are zero, strength reduce to a
1677   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1678   if (!VT.isVector()) {
1679     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1680       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1681                          N0, N1);
1682   }
1683   // fold (sdiv X, pow2) -> simple ops after legalize
1684   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1685       (isPowerOf2_64(N1C->getSExtValue()) ||
1686        isPowerOf2_64(-N1C->getSExtValue()))) {
1687     // If dividing by powers of two is cheap, then don't perform the following
1688     // fold.
1689     if (TLI.isPow2DivCheap())
1690       return SDValue();
1691
1692     int64_t pow2 = N1C->getSExtValue();
1693     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1694     unsigned lg2 = Log2_64(abs2);
1695
1696     // Splat the sign bit into the register
1697     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1698                               DAG.getConstant(VT.getSizeInBits()-1,
1699                                               getShiftAmountTy()));
1700     AddToWorkList(SGN.getNode());
1701
1702     // Add (N0 < 0) ? abs2 - 1 : 0;
1703     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1704                               DAG.getConstant(VT.getSizeInBits() - lg2,
1705                                               getShiftAmountTy()));
1706     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1707     AddToWorkList(SRL.getNode());
1708     AddToWorkList(ADD.getNode());    // Divide by pow2
1709     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1710                               DAG.getConstant(lg2, getShiftAmountTy()));
1711
1712     // If we're dividing by a positive value, we're done.  Otherwise, we must
1713     // negate the result.
1714     if (pow2 > 0)
1715       return SRA;
1716
1717     AddToWorkList(SRA.getNode());
1718     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1719                        DAG.getConstant(0, VT), SRA);
1720   }
1721
1722   // if integer divide is expensive and we satisfy the requirements, emit an
1723   // alternate sequence.
1724   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1725       !TLI.isIntDivCheap()) {
1726     SDValue Op = BuildSDIV(N);
1727     if (Op.getNode()) return Op;
1728   }
1729
1730   // undef / X -> 0
1731   if (N0.getOpcode() == ISD::UNDEF)
1732     return DAG.getConstant(0, VT);
1733   // X / undef -> undef
1734   if (N1.getOpcode() == ISD::UNDEF)
1735     return N1;
1736
1737   return SDValue();
1738 }
1739
1740 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1741   SDValue N0 = N->getOperand(0);
1742   SDValue N1 = N->getOperand(1);
1743   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1744   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1745   EVT VT = N->getValueType(0);
1746
1747   // fold vector ops
1748   if (VT.isVector()) {
1749     SDValue FoldedVOp = SimplifyVBinOp(N);
1750     if (FoldedVOp.getNode()) return FoldedVOp;
1751   }
1752
1753   // fold (udiv c1, c2) -> c1/c2
1754   if (N0C && N1C && !N1C->isNullValue())
1755     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1756   // fold (udiv x, (1 << c)) -> x >>u c
1757   if (N1C && N1C->getAPIntValue().isPowerOf2())
1758     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1759                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1760                                        getShiftAmountTy()));
1761   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1762   if (N1.getOpcode() == ISD::SHL) {
1763     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1764       if (SHC->getAPIntValue().isPowerOf2()) {
1765         EVT ADDVT = N1.getOperand(1).getValueType();
1766         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1767                                   N1.getOperand(1),
1768                                   DAG.getConstant(SHC->getAPIntValue()
1769                                                                   .logBase2(),
1770                                                   ADDVT));
1771         AddToWorkList(Add.getNode());
1772         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1773       }
1774     }
1775   }
1776   // fold (udiv x, c) -> alternate
1777   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1778     SDValue Op = BuildUDIV(N);
1779     if (Op.getNode()) return Op;
1780   }
1781
1782   // undef / X -> 0
1783   if (N0.getOpcode() == ISD::UNDEF)
1784     return DAG.getConstant(0, VT);
1785   // X / undef -> undef
1786   if (N1.getOpcode() == ISD::UNDEF)
1787     return N1;
1788
1789   return SDValue();
1790 }
1791
1792 SDValue DAGCombiner::visitSREM(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797   EVT VT = N->getValueType(0);
1798
1799   // fold (srem c1, c2) -> c1%c2
1800   if (N0C && N1C && !N1C->isNullValue())
1801     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1802   // If we know the sign bits of both operands are zero, strength reduce to a
1803   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1804   if (!VT.isVector()) {
1805     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1806       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1807   }
1808
1809   // If X/C can be simplified by the division-by-constant logic, lower
1810   // X%C to the equivalent of X-X/C*C.
1811   if (N1C && !N1C->isNullValue()) {
1812     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1813     AddToWorkList(Div.getNode());
1814     SDValue OptimizedDiv = combine(Div.getNode());
1815     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1816       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1817                                 OptimizedDiv, N1);
1818       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1819       AddToWorkList(Mul.getNode());
1820       return Sub;
1821     }
1822   }
1823
1824   // undef % X -> 0
1825   if (N0.getOpcode() == ISD::UNDEF)
1826     return DAG.getConstant(0, VT);
1827   // X % undef -> undef
1828   if (N1.getOpcode() == ISD::UNDEF)
1829     return N1;
1830
1831   return SDValue();
1832 }
1833
1834 SDValue DAGCombiner::visitUREM(SDNode *N) {
1835   SDValue N0 = N->getOperand(0);
1836   SDValue N1 = N->getOperand(1);
1837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839   EVT VT = N->getValueType(0);
1840
1841   // fold (urem c1, c2) -> c1%c2
1842   if (N0C && N1C && !N1C->isNullValue())
1843     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1844   // fold (urem x, pow2) -> (and x, pow2-1)
1845   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1846     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1847                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
1848   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1849   if (N1.getOpcode() == ISD::SHL) {
1850     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1851       if (SHC->getAPIntValue().isPowerOf2()) {
1852         SDValue Add =
1853           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1854                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1855                                  VT));
1856         AddToWorkList(Add.getNode());
1857         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1858       }
1859     }
1860   }
1861
1862   // If X/C can be simplified by the division-by-constant logic, lower
1863   // X%C to the equivalent of X-X/C*C.
1864   if (N1C && !N1C->isNullValue()) {
1865     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1866     AddToWorkList(Div.getNode());
1867     SDValue OptimizedDiv = combine(Div.getNode());
1868     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1869       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1870                                 OptimizedDiv, N1);
1871       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1872       AddToWorkList(Mul.getNode());
1873       return Sub;
1874     }
1875   }
1876
1877   // undef % X -> 0
1878   if (N0.getOpcode() == ISD::UNDEF)
1879     return DAG.getConstant(0, VT);
1880   // X % undef -> undef
1881   if (N1.getOpcode() == ISD::UNDEF)
1882     return N1;
1883
1884   return SDValue();
1885 }
1886
1887 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1888   SDValue N0 = N->getOperand(0);
1889   SDValue N1 = N->getOperand(1);
1890   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891   EVT VT = N->getValueType(0);
1892
1893   // fold (mulhs x, 0) -> 0
1894   if (N1C && N1C->isNullValue())
1895     return N1;
1896   // fold (mulhs x, 1) -> (sra x, size(x)-1)
1897   if (N1C && N1C->getAPIntValue() == 1)
1898     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1899                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1900                                        getShiftAmountTy()));
1901   // fold (mulhs x, undef) -> 0
1902   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1903     return DAG.getConstant(0, VT);
1904
1905   return SDValue();
1906 }
1907
1908 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1909   SDValue N0 = N->getOperand(0);
1910   SDValue N1 = N->getOperand(1);
1911   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1912   EVT VT = N->getValueType(0);
1913
1914   // fold (mulhu x, 0) -> 0
1915   if (N1C && N1C->isNullValue())
1916     return N1;
1917   // fold (mulhu x, 1) -> 0
1918   if (N1C && N1C->getAPIntValue() == 1)
1919     return DAG.getConstant(0, N0.getValueType());
1920   // fold (mulhu x, undef) -> 0
1921   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1922     return DAG.getConstant(0, VT);
1923
1924   return SDValue();
1925 }
1926
1927 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1928 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1929 /// that are being performed. Return true if a simplification was made.
1930 ///
1931 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1932                                                 unsigned HiOp) {
1933   // If the high half is not needed, just compute the low half.
1934   bool HiExists = N->hasAnyUseOfValue(1);
1935   if (!HiExists &&
1936       (!LegalOperations ||
1937        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1938     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1939                               N->op_begin(), N->getNumOperands());
1940     return CombineTo(N, Res, Res);
1941   }
1942
1943   // If the low half is not needed, just compute the high half.
1944   bool LoExists = N->hasAnyUseOfValue(0);
1945   if (!LoExists &&
1946       (!LegalOperations ||
1947        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1948     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1949                               N->op_begin(), N->getNumOperands());
1950     return CombineTo(N, Res, Res);
1951   }
1952
1953   // If both halves are used, return as it is.
1954   if (LoExists && HiExists)
1955     return SDValue();
1956
1957   // If the two computed results can be simplified separately, separate them.
1958   if (LoExists) {
1959     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1960                              N->op_begin(), N->getNumOperands());
1961     AddToWorkList(Lo.getNode());
1962     SDValue LoOpt = combine(Lo.getNode());
1963     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1964         (!LegalOperations ||
1965          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1966       return CombineTo(N, LoOpt, LoOpt);
1967   }
1968
1969   if (HiExists) {
1970     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1971                              N->op_begin(), N->getNumOperands());
1972     AddToWorkList(Hi.getNode());
1973     SDValue HiOpt = combine(Hi.getNode());
1974     if (HiOpt.getNode() && HiOpt != Hi &&
1975         (!LegalOperations ||
1976          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1977       return CombineTo(N, HiOpt, HiOpt);
1978   }
1979
1980   return SDValue();
1981 }
1982
1983 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1984   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1985   if (Res.getNode()) return Res;
1986
1987   return SDValue();
1988 }
1989
1990 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1991   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1992   if (Res.getNode()) return Res;
1993
1994   return SDValue();
1995 }
1996
1997 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1998   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1999   if (Res.getNode()) return Res;
2000
2001   return SDValue();
2002 }
2003
2004 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2005   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2006   if (Res.getNode()) return Res;
2007
2008   return SDValue();
2009 }
2010
2011 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2012 /// two operands of the same opcode, try to simplify it.
2013 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2014   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2015   EVT VT = N0.getValueType();
2016   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2017
2018   // Bail early if none of these transforms apply.
2019   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2020
2021   // For each of OP in AND/OR/XOR:
2022   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2023   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2024   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2025   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
2026   //
2027   // do not sink logical op inside of a vector extend, since it may combine
2028   // into a vsetcc.
2029   EVT Op0VT = N0.getOperand(0).getValueType();
2030   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2031        N0.getOpcode() == ISD::SIGN_EXTEND ||
2032        // Avoid infinite looping with PromoteIntBinOp.
2033        (N0.getOpcode() == ISD::ANY_EXTEND &&
2034         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2035        (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
2036       !VT.isVector() &&
2037       Op0VT == N1.getOperand(0).getValueType() &&
2038       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2039     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2040                                  N0.getOperand(0).getValueType(),
2041                                  N0.getOperand(0), N1.getOperand(0));
2042     AddToWorkList(ORNode.getNode());
2043     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2044   }
2045
2046   // For each of OP in SHL/SRL/SRA/AND...
2047   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2048   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2049   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2050   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2051        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2052       N0.getOperand(1) == N1.getOperand(1)) {
2053     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2054                                  N0.getOperand(0).getValueType(),
2055                                  N0.getOperand(0), N1.getOperand(0));
2056     AddToWorkList(ORNode.getNode());
2057     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2058                        ORNode, N0.getOperand(1));
2059   }
2060
2061   return SDValue();
2062 }
2063
2064 SDValue DAGCombiner::visitAND(SDNode *N) {
2065   SDValue N0 = N->getOperand(0);
2066   SDValue N1 = N->getOperand(1);
2067   SDValue LL, LR, RL, RR, CC0, CC1;
2068   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2069   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2070   EVT VT = N1.getValueType();
2071   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2072
2073   // fold vector ops
2074   if (VT.isVector()) {
2075     SDValue FoldedVOp = SimplifyVBinOp(N);
2076     if (FoldedVOp.getNode()) return FoldedVOp;
2077   }
2078
2079   // fold (and x, undef) -> 0
2080   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2081     return DAG.getConstant(0, VT);
2082   // fold (and c1, c2) -> c1&c2
2083   if (N0C && N1C)
2084     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2085   // canonicalize constant to RHS
2086   if (N0C && !N1C)
2087     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2088   // fold (and x, -1) -> x
2089   if (N1C && N1C->isAllOnesValue())
2090     return N0;
2091   // if (and x, c) is known to be zero, return 0
2092   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2093                                    APInt::getAllOnesValue(BitWidth)))
2094     return DAG.getConstant(0, VT);
2095   // reassociate and
2096   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2097   if (RAND.getNode() != 0)
2098     return RAND;
2099   // fold (and (or x, C), D) -> D if (C & D) == D
2100   if (N1C && N0.getOpcode() == ISD::OR)
2101     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2102       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2103         return N1;
2104   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2105   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2106     SDValue N0Op0 = N0.getOperand(0);
2107     APInt Mask = ~N1C->getAPIntValue();
2108     Mask.trunc(N0Op0.getValueSizeInBits());
2109     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2110       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2111                                  N0.getValueType(), N0Op0);
2112
2113       // Replace uses of the AND with uses of the Zero extend node.
2114       CombineTo(N, Zext);
2115
2116       // We actually want to replace all uses of the any_extend with the
2117       // zero_extend, to avoid duplicating things.  This will later cause this
2118       // AND to be folded.
2119       CombineTo(N0.getNode(), Zext);
2120       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2121     }
2122   }
2123   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2124   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2125     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2126     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2127
2128     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2129         LL.getValueType().isInteger()) {
2130       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2131       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2132         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2133                                      LR.getValueType(), LL, RL);
2134         AddToWorkList(ORNode.getNode());
2135         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2136       }
2137       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2138       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2139         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2140                                       LR.getValueType(), LL, RL);
2141         AddToWorkList(ANDNode.getNode());
2142         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2143       }
2144       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2145       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2146         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2147                                      LR.getValueType(), LL, RL);
2148         AddToWorkList(ORNode.getNode());
2149         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2150       }
2151     }
2152     // canonicalize equivalent to ll == rl
2153     if (LL == RR && LR == RL) {
2154       Op1 = ISD::getSetCCSwappedOperands(Op1);
2155       std::swap(RL, RR);
2156     }
2157     if (LL == RL && LR == RR) {
2158       bool isInteger = LL.getValueType().isInteger();
2159       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2160       if (Result != ISD::SETCC_INVALID &&
2161           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2162         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2163                             LL, LR, Result);
2164     }
2165   }
2166
2167   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2168   if (N0.getOpcode() == N1.getOpcode()) {
2169     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2170     if (Tmp.getNode()) return Tmp;
2171   }
2172
2173   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2174   // fold (and (sra)) -> (and (srl)) when possible.
2175   if (!VT.isVector() &&
2176       SimplifyDemandedBits(SDValue(N, 0)))
2177     return SDValue(N, 0);
2178
2179   // fold (zext_inreg (extload x)) -> (zextload x)
2180   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2181     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2182     EVT MemVT = LN0->getMemoryVT();
2183     // If we zero all the possible extended bits, then we can turn this into
2184     // a zextload if we are running before legalize or the operation is legal.
2185     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2186     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2187                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2188         ((!LegalOperations && !LN0->isVolatile()) ||
2189          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2190       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2191                                        LN0->getChain(), LN0->getBasePtr(),
2192                                        LN0->getSrcValue(),
2193                                        LN0->getSrcValueOffset(), MemVT,
2194                                        LN0->isVolatile(), LN0->isNonTemporal(),
2195                                        LN0->getAlignment());
2196       AddToWorkList(N);
2197       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2198       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2199     }
2200   }
2201   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2202   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2203       N0.hasOneUse()) {
2204     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2205     EVT MemVT = LN0->getMemoryVT();
2206     // If we zero all the possible extended bits, then we can turn this into
2207     // a zextload if we are running before legalize or the operation is legal.
2208     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2209     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2210                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2211         ((!LegalOperations && !LN0->isVolatile()) ||
2212          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2213       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2214                                        LN0->getChain(),
2215                                        LN0->getBasePtr(), LN0->getSrcValue(),
2216                                        LN0->getSrcValueOffset(), MemVT,
2217                                        LN0->isVolatile(), LN0->isNonTemporal(),
2218                                        LN0->getAlignment());
2219       AddToWorkList(N);
2220       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2221       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2222     }
2223   }
2224
2225   // fold (and (load x), 255) -> (zextload x, i8)
2226   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2227   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2228   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2229               (N0.getOpcode() == ISD::ANY_EXTEND &&
2230                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2231     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2232     LoadSDNode *LN0 = HasAnyExt
2233       ? cast<LoadSDNode>(N0.getOperand(0))
2234       : cast<LoadSDNode>(N0);
2235     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2236         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2237       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2238       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2239         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2240         EVT LoadedVT = LN0->getMemoryVT();
2241
2242         if (ExtVT == LoadedVT &&
2243             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2244           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2245           
2246           SDValue NewLoad = 
2247             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2248                            LN0->getChain(), LN0->getBasePtr(),
2249                            LN0->getSrcValue(), LN0->getSrcValueOffset(),
2250                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2251                            LN0->getAlignment());
2252           AddToWorkList(N);
2253           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2254           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2255         }
2256         
2257         // Do not change the width of a volatile load.
2258         // Do not generate loads of non-round integer types since these can
2259         // be expensive (and would be wrong if the type is not byte sized).
2260         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2261             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2262           EVT PtrType = LN0->getOperand(1).getValueType();
2263
2264           unsigned Alignment = LN0->getAlignment();
2265           SDValue NewPtr = LN0->getBasePtr();
2266
2267           // For big endian targets, we need to add an offset to the pointer
2268           // to load the correct bytes.  For little endian systems, we merely
2269           // need to read fewer bytes from the same pointer.
2270           if (TLI.isBigEndian()) {
2271             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2272             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2273             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2274             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2275                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2276             Alignment = MinAlign(Alignment, PtrOff);
2277           }
2278
2279           AddToWorkList(NewPtr.getNode());
2280           
2281           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2282           SDValue Load =
2283             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2284                            LN0->getChain(), NewPtr,
2285                            LN0->getSrcValue(), LN0->getSrcValueOffset(),
2286                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2287                            Alignment);
2288           AddToWorkList(N);
2289           CombineTo(LN0, Load, Load.getValue(1));
2290           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2291         }
2292       }
2293     }
2294   }
2295
2296   return SDValue();
2297 }
2298
2299 SDValue DAGCombiner::visitOR(SDNode *N) {
2300   SDValue N0 = N->getOperand(0);
2301   SDValue N1 = N->getOperand(1);
2302   SDValue LL, LR, RL, RR, CC0, CC1;
2303   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2304   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2305   EVT VT = N1.getValueType();
2306
2307   // fold vector ops
2308   if (VT.isVector()) {
2309     SDValue FoldedVOp = SimplifyVBinOp(N);
2310     if (FoldedVOp.getNode()) return FoldedVOp;
2311   }
2312
2313   // fold (or x, undef) -> -1
2314   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2315     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2316     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2317   }
2318   // fold (or c1, c2) -> c1|c2
2319   if (N0C && N1C)
2320     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2321   // canonicalize constant to RHS
2322   if (N0C && !N1C)
2323     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2324   // fold (or x, 0) -> x
2325   if (N1C && N1C->isNullValue())
2326     return N0;
2327   // fold (or x, -1) -> -1
2328   if (N1C && N1C->isAllOnesValue())
2329     return N1;
2330   // fold (or x, c) -> c iff (x & ~c) == 0
2331   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2332     return N1;
2333   // reassociate or
2334   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2335   if (ROR.getNode() != 0)
2336     return ROR;
2337   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2338   // iff (c1 & c2) == 0.
2339   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2340              isa<ConstantSDNode>(N0.getOperand(1))) {
2341     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2342     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2343       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2344                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2345                                      N0.getOperand(0), N1),
2346                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2347   }
2348   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2349   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2350     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2351     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2352
2353     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2354         LL.getValueType().isInteger()) {
2355       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2356       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2357       if (cast<ConstantSDNode>(LR)->isNullValue() &&
2358           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2359         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2360                                      LR.getValueType(), LL, RL);
2361         AddToWorkList(ORNode.getNode());
2362         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2363       }
2364       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2365       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
2366       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2367           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2368         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2369                                       LR.getValueType(), LL, RL);
2370         AddToWorkList(ANDNode.getNode());
2371         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2372       }
2373     }
2374     // canonicalize equivalent to ll == rl
2375     if (LL == RR && LR == RL) {
2376       Op1 = ISD::getSetCCSwappedOperands(Op1);
2377       std::swap(RL, RR);
2378     }
2379     if (LL == RL && LR == RR) {
2380       bool isInteger = LL.getValueType().isInteger();
2381       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2382       if (Result != ISD::SETCC_INVALID &&
2383           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2384         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2385                             LL, LR, Result);
2386     }
2387   }
2388
2389   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
2390   if (N0.getOpcode() == N1.getOpcode()) {
2391     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2392     if (Tmp.getNode()) return Tmp;
2393   }
2394
2395   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
2396   if (N0.getOpcode() == ISD::AND &&
2397       N1.getOpcode() == ISD::AND &&
2398       N0.getOperand(1).getOpcode() == ISD::Constant &&
2399       N1.getOperand(1).getOpcode() == ISD::Constant &&
2400       // Don't increase # computations.
2401       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2402     // We can only do this xform if we know that bits from X that are set in C2
2403     // but not in C1 are already zero.  Likewise for Y.
2404     const APInt &LHSMask =
2405       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2406     const APInt &RHSMask =
2407       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2408
2409     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2410         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2411       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2412                               N0.getOperand(0), N1.getOperand(0));
2413       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2414                          DAG.getConstant(LHSMask | RHSMask, VT));
2415     }
2416   }
2417
2418   // See if this is some rotate idiom.
2419   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2420     return SDValue(Rot, 0);
2421
2422   return SDValue();
2423 }
2424
2425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2427   if (Op.getOpcode() == ISD::AND) {
2428     if (isa<ConstantSDNode>(Op.getOperand(1))) {
2429       Mask = Op.getOperand(1);
2430       Op = Op.getOperand(0);
2431     } else {
2432       return false;
2433     }
2434   }
2435
2436   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2437     Shift = Op;
2438     return true;
2439   }
2440
2441   return false;
2442 }
2443
2444 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
2445 // idioms for rotate, and if the target supports rotation instructions, generate
2446 // a rot[lr].
2447 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2448   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
2449   EVT VT = LHS.getValueType();
2450   if (!TLI.isTypeLegal(VT)) return 0;
2451
2452   // The target must have at least one rotate flavor.
2453   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2454   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2455   if (!HasROTL && !HasROTR) return 0;
2456
2457   // Match "(X shl/srl V1) & V2" where V2 may not be present.
2458   SDValue LHSShift;   // The shift.
2459   SDValue LHSMask;    // AND value if any.
2460   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2461     return 0; // Not part of a rotate.
2462
2463   SDValue RHSShift;   // The shift.
2464   SDValue RHSMask;    // AND value if any.
2465   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2466     return 0; // Not part of a rotate.
2467
2468   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2469     return 0;   // Not shifting the same value.
2470
2471   if (LHSShift.getOpcode() == RHSShift.getOpcode())
2472     return 0;   // Shifts must disagree.
2473
2474   // Canonicalize shl to left side in a shl/srl pair.
2475   if (RHSShift.getOpcode() == ISD::SHL) {
2476     std::swap(LHS, RHS);
2477     std::swap(LHSShift, RHSShift);
2478     std::swap(LHSMask , RHSMask );
2479   }
2480
2481   unsigned OpSizeInBits = VT.getSizeInBits();
2482   SDValue LHSShiftArg = LHSShift.getOperand(0);
2483   SDValue LHSShiftAmt = LHSShift.getOperand(1);
2484   SDValue RHSShiftAmt = RHSShift.getOperand(1);
2485
2486   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2487   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2488   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2489       RHSShiftAmt.getOpcode() == ISD::Constant) {
2490     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2491     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2492     if ((LShVal + RShVal) != OpSizeInBits)
2493       return 0;
2494
2495     SDValue Rot;
2496     if (HasROTL)
2497       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2498     else
2499       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2500
2501     // If there is an AND of either shifted operand, apply it to the result.
2502     if (LHSMask.getNode() || RHSMask.getNode()) {
2503       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2504
2505       if (LHSMask.getNode()) {
2506         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2507         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2508       }
2509       if (RHSMask.getNode()) {
2510         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2511         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2512       }
2513
2514       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2515     }
2516
2517     return Rot.getNode();
2518   }
2519
2520   // If there is a mask here, and we have a variable shift, we can't be sure
2521   // that we're masking out the right stuff.
2522   if (LHSMask.getNode() || RHSMask.getNode())
2523     return 0;
2524
2525   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2526   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2527   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2528       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2529     if (ConstantSDNode *SUBC =
2530           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2531       if (SUBC->getAPIntValue() == OpSizeInBits) {
2532         if (HasROTL)
2533           return DAG.getNode(ISD::ROTL, DL, VT,
2534                              LHSShiftArg, LHSShiftAmt).getNode();
2535         else
2536           return DAG.getNode(ISD::ROTR, DL, VT,
2537                              LHSShiftArg, RHSShiftAmt).getNode();
2538       }
2539     }
2540   }
2541
2542   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2543   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2544   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2545       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2546     if (ConstantSDNode *SUBC =
2547           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2548       if (SUBC->getAPIntValue() == OpSizeInBits) {
2549         if (HasROTR)
2550           return DAG.getNode(ISD::ROTR, DL, VT,
2551                              LHSShiftArg, RHSShiftAmt).getNode();
2552         else
2553           return DAG.getNode(ISD::ROTL, DL, VT,
2554                              LHSShiftArg, LHSShiftAmt).getNode();
2555       }
2556     }
2557   }
2558
2559   // Look for sign/zext/any-extended or truncate cases:
2560   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2561        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2562        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2563        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2564       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2565        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2566        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2567        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2568     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2569     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2570     if (RExtOp0.getOpcode() == ISD::SUB &&
2571         RExtOp0.getOperand(1) == LExtOp0) {
2572       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2573       //   (rotl x, y)
2574       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2575       //   (rotr x, (sub 32, y))
2576       if (ConstantSDNode *SUBC =
2577             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2578         if (SUBC->getAPIntValue() == OpSizeInBits) {
2579           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2580                              LHSShiftArg,
2581                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2582         }
2583       }
2584     } else if (LExtOp0.getOpcode() == ISD::SUB &&
2585                RExtOp0 == LExtOp0.getOperand(1)) {
2586       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2587       //   (rotr x, y)
2588       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2589       //   (rotl x, (sub 32, y))
2590       if (ConstantSDNode *SUBC =
2591             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2592         if (SUBC->getAPIntValue() == OpSizeInBits) {
2593           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2594                              LHSShiftArg,
2595                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2596         }
2597       }
2598     }
2599   }
2600
2601   return 0;
2602 }
2603
2604 SDValue DAGCombiner::visitXOR(SDNode *N) {
2605   SDValue N0 = N->getOperand(0);
2606   SDValue N1 = N->getOperand(1);
2607   SDValue LHS, RHS, CC;
2608   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2609   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2610   EVT VT = N0.getValueType();
2611
2612   // fold vector ops
2613   if (VT.isVector()) {
2614     SDValue FoldedVOp = SimplifyVBinOp(N);
2615     if (FoldedVOp.getNode()) return FoldedVOp;
2616   }
2617
2618   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2619   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2620     return DAG.getConstant(0, VT);
2621   // fold (xor x, undef) -> undef
2622   if (N0.getOpcode() == ISD::UNDEF)
2623     return N0;
2624   if (N1.getOpcode() == ISD::UNDEF)
2625     return N1;
2626   // fold (xor c1, c2) -> c1^c2
2627   if (N0C && N1C)
2628     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2629   // canonicalize constant to RHS
2630   if (N0C && !N1C)
2631     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2632   // fold (xor x, 0) -> x
2633   if (N1C && N1C->isNullValue())
2634     return N0;
2635   // reassociate xor
2636   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2637   if (RXOR.getNode() != 0)
2638     return RXOR;
2639
2640   // fold !(x cc y) -> (x !cc y)
2641   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2642     bool isInt = LHS.getValueType().isInteger();
2643     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2644                                                isInt);
2645
2646     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2647       switch (N0.getOpcode()) {
2648       default:
2649         llvm_unreachable("Unhandled SetCC Equivalent!");
2650       case ISD::SETCC:
2651         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2652       case ISD::SELECT_CC:
2653         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2654                                N0.getOperand(3), NotCC);
2655       }
2656     }
2657   }
2658
2659   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2660   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2661       N0.getNode()->hasOneUse() &&
2662       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2663     SDValue V = N0.getOperand(0);
2664     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2665                     DAG.getConstant(1, V.getValueType()));
2666     AddToWorkList(V.getNode());
2667     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2668   }
2669
2670   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2671   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2672       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2673     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2674     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2675       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2676       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2677       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2678       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2679       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2680     }
2681   }
2682   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2683   if (N1C && N1C->isAllOnesValue() &&
2684       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2685     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2686     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2687       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2688       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2689       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2690       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2691       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2692     }
2693   }
2694   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2695   if (N1C && N0.getOpcode() == ISD::XOR) {
2696     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2697     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2698     if (N00C)
2699       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2700                          DAG.getConstant(N1C->getAPIntValue() ^
2701                                          N00C->getAPIntValue(), VT));
2702     if (N01C)
2703       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2704                          DAG.getConstant(N1C->getAPIntValue() ^
2705                                          N01C->getAPIntValue(), VT));
2706   }
2707   // fold (xor x, x) -> 0
2708   if (N0 == N1) {
2709     if (!VT.isVector()) {
2710       return DAG.getConstant(0, VT);
2711     } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2712       // Produce a vector of zeros.
2713       SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2714       std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2715       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2716                          &Ops[0], Ops.size());
2717     }
2718   }
2719
2720   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
2721   if (N0.getOpcode() == N1.getOpcode()) {
2722     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2723     if (Tmp.getNode()) return Tmp;
2724   }
2725
2726   // Simplify the expression using non-local knowledge.
2727   if (!VT.isVector() &&
2728       SimplifyDemandedBits(SDValue(N, 0)))
2729     return SDValue(N, 0);
2730
2731   return SDValue();
2732 }
2733
2734 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2735 /// the shift amount is a constant.
2736 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2737   SDNode *LHS = N->getOperand(0).getNode();
2738   if (!LHS->hasOneUse()) return SDValue();
2739
2740   // We want to pull some binops through shifts, so that we have (and (shift))
2741   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
2742   // thing happens with address calculations, so it's important to canonicalize
2743   // it.
2744   bool HighBitSet = false;  // Can we transform this if the high bit is set?
2745
2746   switch (LHS->getOpcode()) {
2747   default: return SDValue();
2748   case ISD::OR:
2749   case ISD::XOR:
2750     HighBitSet = false; // We can only transform sra if the high bit is clear.
2751     break;
2752   case ISD::AND:
2753     HighBitSet = true;  // We can only transform sra if the high bit is set.
2754     break;
2755   case ISD::ADD:
2756     if (N->getOpcode() != ISD::SHL)
2757       return SDValue(); // only shl(add) not sr[al](add).
2758     HighBitSet = false; // We can only transform sra if the high bit is clear.
2759     break;
2760   }
2761
2762   // We require the RHS of the binop to be a constant as well.
2763   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2764   if (!BinOpCst) return SDValue();
2765
2766   // FIXME: disable this unless the input to the binop is a shift by a constant.
2767   // If it is not a shift, it pessimizes some common cases like:
2768   //
2769   //    void foo(int *X, int i) { X[i & 1235] = 1; }
2770   //    int bar(int *X, int i) { return X[i & 255]; }
2771   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2772   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2773        BinOpLHSVal->getOpcode() != ISD::SRA &&
2774        BinOpLHSVal->getOpcode() != ISD::SRL) ||
2775       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2776     return SDValue();
2777
2778   EVT VT = N->getValueType(0);
2779
2780   // If this is a signed shift right, and the high bit is modified by the
2781   // logical operation, do not perform the transformation. The highBitSet
2782   // boolean indicates the value of the high bit of the constant which would
2783   // cause it to be modified for this operation.
2784   if (N->getOpcode() == ISD::SRA) {
2785     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2786     if (BinOpRHSSignSet != HighBitSet)
2787       return SDValue();
2788   }
2789
2790   // Fold the constants, shifting the binop RHS by the shift amount.
2791   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2792                                N->getValueType(0),
2793                                LHS->getOperand(1), N->getOperand(1));
2794
2795   // Create the new shift.
2796   SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2797                                  VT, LHS->getOperand(0), N->getOperand(1));
2798
2799   // Create the new binop.
2800   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2801 }
2802
2803 SDValue DAGCombiner::visitSHL(SDNode *N) {
2804   SDValue N0 = N->getOperand(0);
2805   SDValue N1 = N->getOperand(1);
2806   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2807   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2808   EVT VT = N0.getValueType();
2809   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2810
2811   // fold (shl c1, c2) -> c1<<c2
2812   if (N0C && N1C)
2813     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2814   // fold (shl 0, x) -> 0
2815   if (N0C && N0C->isNullValue())
2816     return N0;
2817   // fold (shl x, c >= size(x)) -> undef
2818   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2819     return DAG.getUNDEF(VT);
2820   // fold (shl x, 0) -> x
2821   if (N1C && N1C->isNullValue())
2822     return N0;
2823   // if (shl x, c) is known to be zero, return 0
2824   if (DAG.MaskedValueIsZero(SDValue(N, 0),
2825                             APInt::getAllOnesValue(OpSizeInBits)))
2826     return DAG.getConstant(0, VT);
2827   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2828   if (N1.getOpcode() == ISD::TRUNCATE &&
2829       N1.getOperand(0).getOpcode() == ISD::AND &&
2830       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2831     SDValue N101 = N1.getOperand(0).getOperand(1);
2832     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2833       EVT TruncVT = N1.getValueType();
2834       SDValue N100 = N1.getOperand(0).getOperand(0);
2835       APInt TruncC = N101C->getAPIntValue();
2836       TruncC.trunc(TruncVT.getSizeInBits());
2837       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2838                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2839                                      DAG.getNode(ISD::TRUNCATE,
2840                                                  N->getDebugLoc(),
2841                                                  TruncVT, N100),
2842                                      DAG.getConstant(TruncC, TruncVT)));
2843     }
2844   }
2845
2846   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2847     return SDValue(N, 0);
2848
2849   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2850   if (N1C && N0.getOpcode() == ISD::SHL &&
2851       N0.getOperand(1).getOpcode() == ISD::Constant) {
2852     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2853     uint64_t c2 = N1C->getZExtValue();
2854     if (c1 + c2 > OpSizeInBits)
2855       return DAG.getConstant(0, VT);
2856     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2857                        DAG.getConstant(c1 + c2, N1.getValueType()));
2858   }
2859   // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2860   //                               (srl (and x, (shl -1, c1)), (sub c1, c2))
2861   if (N1C && N0.getOpcode() == ISD::SRL &&
2862       N0.getOperand(1).getOpcode() == ISD::Constant) {
2863     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2864     if (c1 < VT.getSizeInBits()) {
2865       uint64_t c2 = N1C->getZExtValue();
2866       SDValue HiBitsMask =
2867         DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2868                                               VT.getSizeInBits() - c1),
2869                         VT);
2870       SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2871                                  N0.getOperand(0),
2872                                  HiBitsMask);
2873       if (c2 > c1)
2874         return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2875                            DAG.getConstant(c2-c1, N1.getValueType()));
2876       else
2877         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2878                            DAG.getConstant(c1-c2, N1.getValueType()));
2879     }
2880   }
2881   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2882   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2883     SDValue HiBitsMask =
2884       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2885                                             VT.getSizeInBits() -
2886                                               N1C->getZExtValue()),
2887                       VT);
2888     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2889                        HiBitsMask);
2890   }
2891
2892   if (N1C) {
2893     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
2894     if (NewSHL.getNode())
2895       return NewSHL;
2896   }
2897
2898   return SDValue();
2899 }
2900
2901 SDValue DAGCombiner::visitSRA(SDNode *N) {
2902   SDValue N0 = N->getOperand(0);
2903   SDValue N1 = N->getOperand(1);
2904   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2905   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2906   EVT VT = N0.getValueType();
2907   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2908
2909   // fold (sra c1, c2) -> (sra c1, c2)
2910   if (N0C && N1C)
2911     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2912   // fold (sra 0, x) -> 0
2913   if (N0C && N0C->isNullValue())
2914     return N0;
2915   // fold (sra -1, x) -> -1
2916   if (N0C && N0C->isAllOnesValue())
2917     return N0;
2918   // fold (sra x, (setge c, size(x))) -> undef
2919   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2920     return DAG.getUNDEF(VT);
2921   // fold (sra x, 0) -> x
2922   if (N1C && N1C->isNullValue())
2923     return N0;
2924   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2925   // sext_inreg.
2926   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2927     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2928     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2929     if (VT.isVector())
2930       ExtVT = EVT::getVectorVT(*DAG.getContext(),
2931                                ExtVT, VT.getVectorNumElements());
2932     if ((!LegalOperations ||
2933          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2934       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2935                          N0.getOperand(0), DAG.getValueType(ExtVT));
2936   }
2937
2938   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2939   if (N1C && N0.getOpcode() == ISD::SRA) {
2940     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2941       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2942       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2943       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2944                          DAG.getConstant(Sum, N1C->getValueType(0)));
2945     }
2946   }
2947
2948   // fold (sra (shl X, m), (sub result_size, n))
2949   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2950   // result_size - n != m.
2951   // If truncate is free for the target sext(shl) is likely to result in better
2952   // code.
2953   if (N0.getOpcode() == ISD::SHL) {
2954     // Get the two constanst of the shifts, CN0 = m, CN = n.
2955     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2956     if (N01C && N1C) {
2957       // Determine what the truncate's result bitsize and type would be.
2958       EVT TruncVT =
2959         EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2960       // Determine the residual right-shift amount.
2961       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2962
2963       // If the shift is not a no-op (in which case this should be just a sign
2964       // extend already), the truncated to type is legal, sign_extend is legal
2965       // on that type, and the truncate to that type is both legal and free,
2966       // perform the transform.
2967       if ((ShiftAmt > 0) &&
2968           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2969           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2970           TLI.isTruncateFree(VT, TruncVT)) {
2971
2972           SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2973           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2974                                       N0.getOperand(0), Amt);
2975           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2976                                       Shift);
2977           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2978                              N->getValueType(0), Trunc);
2979       }
2980     }
2981   }
2982
2983   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2984   if (N1.getOpcode() == ISD::TRUNCATE &&
2985       N1.getOperand(0).getOpcode() == ISD::AND &&
2986       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2987     SDValue N101 = N1.getOperand(0).getOperand(1);
2988     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2989       EVT TruncVT = N1.getValueType();
2990       SDValue N100 = N1.getOperand(0).getOperand(0);
2991       APInt TruncC = N101C->getAPIntValue();
2992       TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2993       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2994                          DAG.getNode(ISD::AND, N->getDebugLoc(),
2995                                      TruncVT,
2996                                      DAG.getNode(ISD::TRUNCATE,
2997                                                  N->getDebugLoc(),
2998                                                  TruncVT, N100),
2999                                      DAG.getConstant(TruncC, TruncVT)));
3000     }
3001   }
3002
3003   // Simplify, based on bits shifted out of the LHS.
3004   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3005     return SDValue(N, 0);
3006
3007
3008   // If the sign bit is known to be zero, switch this to a SRL.
3009   if (DAG.SignBitIsZero(N0))
3010     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3011
3012   if (N1C) {
3013     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3014     if (NewSRA.getNode())
3015       return NewSRA;
3016   }
3017
3018   return SDValue();
3019 }
3020
3021 SDValue DAGCombiner::visitSRL(SDNode *N) {
3022   SDValue N0 = N->getOperand(0);
3023   SDValue N1 = N->getOperand(1);
3024   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3025   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3026   EVT VT = N0.getValueType();
3027   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3028
3029   // fold (srl c1, c2) -> c1 >>u c2
3030   if (N0C && N1C)
3031     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3032   // fold (srl 0, x) -> 0
3033   if (N0C && N0C->isNullValue())
3034     return N0;
3035   // fold (srl x, c >= size(x)) -> undef
3036   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3037     return DAG.getUNDEF(VT);
3038   // fold (srl x, 0) -> x
3039   if (N1C && N1C->isNullValue())
3040     return N0;
3041   // if (srl x, c) is known to be zero, return 0
3042   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3043                                    APInt::getAllOnesValue(OpSizeInBits)))
3044     return DAG.getConstant(0, VT);
3045
3046   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3047   if (N1C && N0.getOpcode() == ISD::SRL &&
3048       N0.getOperand(1).getOpcode() == ISD::Constant) {
3049     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3050     uint64_t c2 = N1C->getZExtValue();
3051     if (c1 + c2 > OpSizeInBits)
3052       return DAG.getConstant(0, VT);
3053     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3054                        DAG.getConstant(c1 + c2, N1.getValueType()));
3055   }
3056   
3057   // fold (srl (shl x, c), c) -> (and x, cst2)
3058   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3059       N0.getValueSizeInBits() <= 64) {
3060     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3061     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3062                        DAG.getConstant(~0ULL >> ShAmt, VT));
3063   }
3064   
3065
3066   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3067   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3068     // Shifting in all undef bits?
3069     EVT SmallVT = N0.getOperand(0).getValueType();
3070     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3071       return DAG.getUNDEF(VT);
3072
3073     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3074       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3075                                        N0.getOperand(0), N1);
3076       AddToWorkList(SmallShift.getNode());
3077       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3078     }
3079   }
3080
3081   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3082   // bit, which is unmodified by sra.
3083   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3084     if (N0.getOpcode() == ISD::SRA)
3085       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3086   }
3087
3088   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3089   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3090       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3091     APInt KnownZero, KnownOne;
3092     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3093     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3094
3095     // If any of the input bits are KnownOne, then the input couldn't be all
3096     // zeros, thus the result of the srl will always be zero.
3097     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3098
3099     // If all of the bits input the to ctlz node are known to be zero, then
3100     // the result of the ctlz is "32" and the result of the shift is one.
3101     APInt UnknownBits = ~KnownZero & Mask;
3102     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3103
3104     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3105     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3106       // Okay, we know that only that the single bit specified by UnknownBits
3107       // could be set on input to the CTLZ node. If this bit is set, the SRL
3108       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3109       // to an SRL/XOR pair, which is likely to simplify more.
3110       unsigned ShAmt = UnknownBits.countTrailingZeros();
3111       SDValue Op = N0.getOperand(0);
3112
3113       if (ShAmt) {
3114         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3115                          DAG.getConstant(ShAmt, getShiftAmountTy()));
3116         AddToWorkList(Op.getNode());
3117       }
3118
3119       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3120                          Op, DAG.getConstant(1, VT));
3121     }
3122   }
3123
3124   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3125   if (N1.getOpcode() == ISD::TRUNCATE &&
3126       N1.getOperand(0).getOpcode() == ISD::AND &&
3127       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3128     SDValue N101 = N1.getOperand(0).getOperand(1);
3129     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3130       EVT TruncVT = N1.getValueType();
3131       SDValue N100 = N1.getOperand(0).getOperand(0);
3132       APInt TruncC = N101C->getAPIntValue();
3133       TruncC.trunc(TruncVT.getSizeInBits());
3134       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3135                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3136                                      TruncVT,
3137                                      DAG.getNode(ISD::TRUNCATE,
3138                                                  N->getDebugLoc(),
3139                                                  TruncVT, N100),
3140                                      DAG.getConstant(TruncC, TruncVT)));
3141     }
3142   }
3143
3144   // fold operands of srl based on knowledge that the low bits are not
3145   // demanded.
3146   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3147     return SDValue(N, 0);
3148
3149   if (N1C) {
3150     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3151     if (NewSRL.getNode())
3152       return NewSRL;
3153   }
3154
3155   // Here is a common situation. We want to optimize:
3156   //
3157   //   %a = ...
3158   //   %b = and i32 %a, 2
3159   //   %c = srl i32 %b, 1
3160   //   brcond i32 %c ...
3161   //
3162   // into
3163   // 
3164   //   %a = ...
3165   //   %b = and %a, 2
3166   //   %c = setcc eq %b, 0
3167   //   brcond %c ...
3168   //
3169   // However when after the source operand of SRL is optimized into AND, the SRL
3170   // itself may not be optimized further. Look for it and add the BRCOND into
3171   // the worklist.
3172   if (N->hasOneUse()) {
3173     SDNode *Use = *N->use_begin();
3174     if (Use->getOpcode() == ISD::BRCOND)
3175       AddToWorkList(Use);
3176     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3177       // Also look pass the truncate.
3178       Use = *Use->use_begin();
3179       if (Use->getOpcode() == ISD::BRCOND)
3180         AddToWorkList(Use);
3181     }
3182   }
3183
3184   return SDValue();
3185 }
3186
3187 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3188   SDValue N0 = N->getOperand(0);
3189   EVT VT = N->getValueType(0);
3190
3191   // fold (ctlz c1) -> c2
3192   if (isa<ConstantSDNode>(N0))
3193     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3194   return SDValue();
3195 }
3196
3197 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3198   SDValue N0 = N->getOperand(0);
3199   EVT VT = N->getValueType(0);
3200
3201   // fold (cttz c1) -> c2
3202   if (isa<ConstantSDNode>(N0))
3203     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3204   return SDValue();
3205 }
3206
3207 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3208   SDValue N0 = N->getOperand(0);
3209   EVT VT = N->getValueType(0);
3210
3211   // fold (ctpop c1) -> c2
3212   if (isa<ConstantSDNode>(N0))
3213     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3214   return SDValue();
3215 }
3216
3217 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3218   SDValue N0 = N->getOperand(0);
3219   SDValue N1 = N->getOperand(1);
3220   SDValue N2 = N->getOperand(2);
3221   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3222   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3223   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3224   EVT VT = N->getValueType(0);
3225   EVT VT0 = N0.getValueType();
3226
3227   // fold (select C, X, X) -> X
3228   if (N1 == N2)
3229     return N1;
3230   // fold (select true, X, Y) -> X
3231   if (N0C && !N0C->isNullValue())
3232     return N1;
3233   // fold (select false, X, Y) -> Y
3234   if (N0C && N0C->isNullValue())
3235     return N2;
3236   // fold (select C, 1, X) -> (or C, X)
3237   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3238     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3239   // fold (select C, 0, 1) -> (xor C, 1)
3240   if (VT.isInteger() &&
3241       (VT0 == MVT::i1 ||
3242        (VT0.isInteger() &&
3243         TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3244       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3245     SDValue XORNode;
3246     if (VT == VT0)
3247       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3248                          N0, DAG.getConstant(1, VT0));
3249     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3250                           N0, DAG.getConstant(1, VT0));
3251     AddToWorkList(XORNode.getNode());
3252     if (VT.bitsGT(VT0))
3253       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3254     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3255   }
3256   // fold (select C, 0, X) -> (and (not C), X)
3257   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3258     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3259     AddToWorkList(NOTNode.getNode());
3260     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3261   }
3262   // fold (select C, X, 1) -> (or (not C), X)
3263   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3264     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3265     AddToWorkList(NOTNode.getNode());
3266     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3267   }
3268   // fold (select C, X, 0) -> (and C, X)
3269   if (VT == MVT::i1 && N2C && N2C->isNullValue())
3270     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3271   // fold (select X, X, Y) -> (or X, Y)
3272   // fold (select X, 1, Y) -> (or X, Y)
3273   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3274     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3275   // fold (select X, Y, X) -> (and X, Y)
3276   // fold (select X, Y, 0) -> (and X, Y)
3277   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3278     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3279
3280   // If we can fold this based on the true/false value, do so.
3281   if (SimplifySelectOps(N, N1, N2))
3282     return SDValue(N, 0);  // Don't revisit N.
3283
3284   // fold selects based on a setcc into other things, such as min/max/abs
3285   if (N0.getOpcode() == ISD::SETCC) {
3286     // FIXME:
3287     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3288     // having to say they don't support SELECT_CC on every type the DAG knows
3289     // about, since there is no way to mark an opcode illegal at all value types
3290     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3291         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3292       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3293                          N0.getOperand(0), N0.getOperand(1),
3294                          N1, N2, N0.getOperand(2));
3295     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3296   }
3297
3298   return SDValue();
3299 }
3300
3301 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3302   SDValue N0 = N->getOperand(0);
3303   SDValue N1 = N->getOperand(1);
3304   SDValue N2 = N->getOperand(2);
3305   SDValue N3 = N->getOperand(3);
3306   SDValue N4 = N->getOperand(4);
3307   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3308
3309   // fold select_cc lhs, rhs, x, x, cc -> x
3310   if (N2 == N3)
3311     return N2;
3312
3313   // Determine if the condition we're dealing with is constant
3314   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3315                               N0, N1, CC, N->getDebugLoc(), false);
3316   if (SCC.getNode()) AddToWorkList(SCC.getNode());
3317
3318   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3319     if (!SCCC->isNullValue())
3320       return N2;    // cond always true -> true val
3321     else
3322       return N3;    // cond always false -> false val
3323   }
3324
3325   // Fold to a simpler select_cc
3326   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3327     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3328                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3329                        SCC.getOperand(2));
3330
3331   // If we can fold this based on the true/false value, do so.
3332   if (SimplifySelectOps(N, N2, N3))
3333     return SDValue(N, 0);  // Don't revisit N.
3334
3335   // fold select_cc into other things, such as min/max/abs
3336   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3337 }
3338
3339 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3340   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3341                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
3342                        N->getDebugLoc());
3343 }
3344
3345 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3346 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3347 // transformation. Returns true if extension are possible and the above
3348 // mentioned transformation is profitable.
3349 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3350                                     unsigned ExtOpc,
3351                                     SmallVector<SDNode*, 4> &ExtendNodes,
3352                                     const TargetLowering &TLI) {
3353   bool HasCopyToRegUses = false;
3354   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3355   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3356                             UE = N0.getNode()->use_end();
3357        UI != UE; ++UI) {
3358     SDNode *User = *UI;
3359     if (User == N)
3360       continue;
3361     if (UI.getUse().getResNo() != N0.getResNo())
3362       continue;
3363     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3364     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3365       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3366       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3367         // Sign bits will be lost after a zext.
3368         return false;
3369       bool Add = false;
3370       for (unsigned i = 0; i != 2; ++i) {
3371         SDValue UseOp = User->getOperand(i);
3372         if (UseOp == N0)
3373           continue;
3374         if (!isa<ConstantSDNode>(UseOp))
3375           return false;
3376         Add = true;
3377       }
3378       if (Add)
3379         ExtendNodes.push_back(User);
3380       continue;
3381     }
3382     // If truncates aren't free and there are users we can't
3383     // extend, it isn't worthwhile.
3384     if (!isTruncFree)
3385       return false;
3386     // Remember if this value is live-out.
3387     if (User->getOpcode() == ISD::CopyToReg)
3388       HasCopyToRegUses = true;
3389   }
3390
3391   if (HasCopyToRegUses) {
3392     bool BothLiveOut = false;
3393     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3394          UI != UE; ++UI) {
3395       SDUse &Use = UI.getUse();
3396       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3397         BothLiveOut = true;
3398         break;
3399       }
3400     }
3401     if (BothLiveOut)
3402       // Both unextended and extended values are live out. There had better be
3403       // good a reason for the transformation.
3404       return ExtendNodes.size();
3405   }
3406   return true;
3407 }
3408
3409 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3410   SDValue N0 = N->getOperand(0);
3411   EVT VT = N->getValueType(0);
3412
3413   // fold (sext c1) -> c1
3414   if (isa<ConstantSDNode>(N0))
3415     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3416
3417   // fold (sext (sext x)) -> (sext x)
3418   // fold (sext (aext x)) -> (sext x)
3419   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3420     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3421                        N0.getOperand(0));
3422
3423   if (N0.getOpcode() == ISD::TRUNCATE) {
3424     // fold (sext (truncate (load x))) -> (sext (smaller load x))
3425     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3426     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3427     if (NarrowLoad.getNode()) {
3428       if (NarrowLoad.getNode() != N0.getNode())
3429         CombineTo(N0.getNode(), NarrowLoad);
3430       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3431     }
3432
3433     // See if the value being truncated is already sign extended.  If so, just
3434     // eliminate the trunc/sext pair.
3435     SDValue Op = N0.getOperand(0);
3436     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
3437     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
3438     unsigned DestBits = VT.getScalarType().getSizeInBits();
3439     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3440
3441     if (OpBits == DestBits) {
3442       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
3443       // bits, it is already ready.
3444       if (NumSignBits > DestBits-MidBits)
3445         return Op;
3446     } else if (OpBits < DestBits) {
3447       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
3448       // bits, just sext from i32.
3449       if (NumSignBits > OpBits-MidBits)
3450         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3451     } else {
3452       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
3453       // bits, just truncate to i32.
3454       if (NumSignBits > OpBits-MidBits)
3455         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3456     }
3457
3458     // fold (sext (truncate x)) -> (sextinreg x).
3459     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3460                                                  N0.getValueType())) {
3461       if (OpBits < DestBits)
3462         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3463       else if (OpBits > DestBits)
3464         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3465       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3466                          DAG.getValueType(N0.getValueType()));
3467     }
3468   }
3469
3470   // fold (sext (load x)) -> (sext (truncate (sextload x)))
3471   if (ISD::isNON_EXTLoad(N0.getNode()) &&
3472       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3473        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3474     bool DoXform = true;
3475     SmallVector<SDNode*, 4> SetCCs;
3476     if (!N0.hasOneUse())
3477       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3478     if (DoXform) {
3479       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3480       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3481                                        LN0->getChain(),
3482                                        LN0->getBasePtr(), LN0->getSrcValue(),
3483                                        LN0->getSrcValueOffset(),
3484                                        N0.getValueType(),
3485                                        LN0->isVolatile(), LN0->isNonTemporal(),
3486                                        LN0->getAlignment());
3487       CombineTo(N, ExtLoad);
3488       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3489                                   N0.getValueType(), ExtLoad);
3490       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3491
3492       // Extend SetCC uses if necessary.
3493       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3494         SDNode *SetCC = SetCCs[i];
3495         SmallVector<SDValue, 4> Ops;
3496
3497         for (unsigned j = 0; j != 2; ++j) {
3498           SDValue SOp = SetCC->getOperand(j);
3499           if (SOp == Trunc)
3500             Ops.push_back(ExtLoad);
3501           else
3502             Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3503                                       N->getDebugLoc(), VT, SOp));
3504         }
3505
3506         Ops.push_back(SetCC->getOperand(2));
3507         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3508                                      SetCC->getValueType(0),
3509                                      &Ops[0], Ops.size()));
3510       }
3511
3512       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3513     }
3514   }
3515
3516   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3517   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3518   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3519       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3520     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3521     EVT MemVT = LN0->getMemoryVT();
3522     if ((!LegalOperations && !LN0->isVolatile()) ||
3523         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3524       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3525                                        LN0->getChain(),
3526                                        LN0->getBasePtr(), LN0->getSrcValue(),
3527                                        LN0->getSrcValueOffset(), MemVT,
3528                                        LN0->isVolatile(), LN0->isNonTemporal(),
3529                                        LN0->getAlignment());
3530       CombineTo(N, ExtLoad);
3531       CombineTo(N0.getNode(),
3532                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3533                             N0.getValueType(), ExtLoad),
3534                 ExtLoad.getValue(1));
3535       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3536     }
3537   }
3538
3539   if (N0.getOpcode() == ISD::SETCC) {
3540     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3541     if (VT.isVector() &&
3542         // We know that the # elements of the results is the same as the
3543         // # elements of the compare (and the # elements of the compare result
3544         // for that matter).  Check to see that they are the same size.  If so,
3545         // we know that the element size of the sext'd result matches the
3546         // element size of the compare operands.
3547         VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3548       
3549         // Only do this before legalize for now.
3550         !LegalOperations) {
3551       return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3552                            N0.getOperand(1),
3553                            cast<CondCodeSDNode>(N0.getOperand(2))->get());
3554     }
3555     
3556     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3557     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3558     SDValue NegOne =
3559       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3560     SDValue SCC =
3561       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3562                        NegOne, DAG.getConstant(0, VT),
3563                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3564     if (SCC.getNode()) return SCC;
3565     if (!LegalOperations ||
3566         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3567       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3568                          DAG.getSetCC(N->getDebugLoc(),
3569                                       TLI.getSetCCResultType(VT),
3570                                       N0.getOperand(0), N0.getOperand(1),
3571                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3572                          NegOne, DAG.getConstant(0, VT));
3573   }
3574   
3575   
3576
3577   // fold (sext x) -> (zext x) if the sign bit is known zero.
3578   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3579       DAG.SignBitIsZero(N0))
3580     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3581
3582   return SDValue();
3583 }
3584
3585 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3586   SDValue N0 = N->getOperand(0);
3587   EVT VT = N->getValueType(0);
3588
3589   // fold (zext c1) -> c1
3590   if (isa<ConstantSDNode>(N0))
3591     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3592   // fold (zext (zext x)) -> (zext x)
3593   // fold (zext (aext x)) -> (zext x)
3594   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3595     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3596                        N0.getOperand(0));
3597
3598   // fold (zext (truncate (load x))) -> (zext (smaller load x))
3599   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3600   if (N0.getOpcode() == ISD::TRUNCATE) {
3601     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3602     if (NarrowLoad.getNode()) {
3603       if (NarrowLoad.getNode() != N0.getNode())
3604         CombineTo(N0.getNode(), NarrowLoad);
3605       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3606     }
3607   }
3608
3609   // fold (zext (truncate x)) -> (and x, mask)
3610   if (N0.getOpcode() == ISD::TRUNCATE &&
3611       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3612       (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3613                            N0.getValueType()) ||
3614        !TLI.isZExtFree(N0.getValueType(), VT))) {
3615     SDValue Op = N0.getOperand(0);
3616     if (Op.getValueType().bitsLT(VT)) {
3617       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3618     } else if (Op.getValueType().bitsGT(VT)) {
3619       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3620     }
3621     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3622                                   N0.getValueType().getScalarType());
3623   }
3624
3625   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3626   // if either of the casts is not free.
3627   if (N0.getOpcode() == ISD::AND &&
3628       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3629       N0.getOperand(1).getOpcode() == ISD::Constant &&
3630       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3631                            N0.getValueType()) ||
3632        !TLI.isZExtFree(N0.getValueType(), VT))) {
3633     SDValue X = N0.getOperand(0).getOperand(0);
3634     if (X.getValueType().bitsLT(VT)) {
3635       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3636     } else if (X.getValueType().bitsGT(VT)) {
3637       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3638     }
3639     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3640     Mask.zext(VT.getSizeInBits());
3641     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3642                        X, DAG.getConstant(Mask, VT));
3643   }
3644
3645   // fold (zext (load x)) -> (zext (truncate (zextload x)))
3646   if (ISD::isNON_EXTLoad(N0.getNode()) &&
3647       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3648        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3649     bool DoXform = true;
3650     SmallVector<SDNode*, 4> SetCCs;
3651     if (!N0.hasOneUse())
3652       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3653     if (DoXform) {
3654       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3655       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3656                                        LN0->getChain(),
3657                                        LN0->getBasePtr(), LN0->getSrcValue(),
3658                                        LN0->getSrcValueOffset(),
3659                                        N0.getValueType(),
3660                                        LN0->isVolatile(), LN0->isNonTemporal(),
3661                                        LN0->getAlignment());
3662       CombineTo(N, ExtLoad);
3663       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3664                                   N0.getValueType(), ExtLoad);
3665       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3666
3667       // Extend SetCC uses if necessary.
3668       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3669         SDNode *SetCC = SetCCs[i];
3670         SmallVector<SDValue, 4> Ops;
3671
3672         for (unsigned j = 0; j != 2; ++j) {
3673           SDValue SOp = SetCC->getOperand(j);
3674           if (SOp == Trunc)
3675             Ops.push_back(ExtLoad);
3676           else
3677             Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3678                                       N->getDebugLoc(), VT, SOp));
3679         }
3680
3681         Ops.push_back(SetCC->getOperand(2));
3682         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3683                                      SetCC->getValueType(0),
3684                                      &Ops[0], Ops.size()));
3685       }
3686
3687       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3688     }
3689   }
3690
3691   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3692   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3693   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3694       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3695     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3696     EVT MemVT = LN0->getMemoryVT();
3697     if ((!LegalOperations && !LN0->isVolatile()) ||
3698         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3699       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3700                                        LN0->getChain(),
3701                                        LN0->getBasePtr(), LN0->getSrcValue(),
3702                                        LN0->getSrcValueOffset(), MemVT,
3703                                        LN0->isVolatile(), LN0->isNonTemporal(),
3704                                        LN0->getAlignment());
3705       CombineTo(N, ExtLoad);
3706       CombineTo(N0.getNode(),
3707                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3708                             ExtLoad),
3709                 ExtLoad.getValue(1));
3710       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3711     }
3712   }
3713
3714   // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3715   if (N0.getOpcode() == ISD::SETCC) {
3716     SDValue SCC =
3717       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3718                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3719                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3720     if (SCC.getNode()) return SCC;
3721   }
3722
3723   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3724   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3725       isa<ConstantSDNode>(N0.getOperand(1)) &&
3726       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3727       N0.hasOneUse()) {
3728     if (N0.getOpcode() == ISD::SHL) {
3729       // If the original shl may be shifting out bits, do not perform this
3730       // transformation.
3731       unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3732       unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3733         N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3734       if (ShAmt > KnownZeroBits)
3735         return SDValue();
3736     }
3737     DebugLoc dl = N->getDebugLoc();
3738     return DAG.getNode(N0.getOpcode(), dl, VT,
3739                        DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3740                        DAG.getNode(ISD::ZERO_EXTEND, dl,
3741                                    N0.getOperand(1).getValueType(),
3742                                    N0.getOperand(1)));
3743   }
3744
3745   return SDValue();
3746 }
3747
3748 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3749   SDValue N0 = N->getOperand(0);
3750   EVT VT = N->getValueType(0);
3751
3752   // fold (aext c1) -> c1
3753   if (isa<ConstantSDNode>(N0))
3754     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3755   // fold (aext (aext x)) -> (aext x)
3756   // fold (aext (zext x)) -> (zext x)
3757   // fold (aext (sext x)) -> (sext x)
3758   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
3759       N0.getOpcode() == ISD::ZERO_EXTEND ||
3760       N0.getOpcode() == ISD::SIGN_EXTEND)
3761     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3762
3763   // fold (aext (truncate (load x))) -> (aext (smaller load x))
3764   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3765   if (N0.getOpcode() == ISD::TRUNCATE) {
3766     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3767     if (NarrowLoad.getNode()) {
3768       if (NarrowLoad.getNode() != N0.getNode())
3769         CombineTo(N0.getNode(), NarrowLoad);
3770       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3771     }
3772   }
3773
3774   // fold (aext (truncate x))
3775   if (N0.getOpcode() == ISD::TRUNCATE) {
3776     SDValue TruncOp = N0.getOperand(0);
3777     if (TruncOp.getValueType() == VT)
3778       return TruncOp; // x iff x size == zext size.
3779     if (TruncOp.getValueType().bitsGT(VT))
3780       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3781     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3782   }
3783
3784   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3785   // if the trunc is not free.
3786   if (N0.getOpcode() == ISD::AND &&
3787       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3788       N0.getOperand(1).getOpcode() == ISD::Constant &&
3789       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3790                           N0.getValueType())) {
3791     SDValue X = N0.getOperand(0).getOperand(0);
3792     if (X.getValueType().bitsLT(VT)) {
3793       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3794     } else if (X.getValueType().bitsGT(VT)) {
3795       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3796     }
3797     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3798     Mask.zext(VT.getSizeInBits());
3799     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3800                        X, DAG.getConstant(Mask, VT));
3801   }
3802
3803   // fold (aext (load x)) -> (aext (truncate (extload x)))
3804   if (ISD::isNON_EXTLoad(N0.getNode()) &&
3805       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3806        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3807     bool DoXform = true;
3808     SmallVector<SDNode*, 4> SetCCs;
3809     if (!N0.hasOneUse())
3810       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3811     if (DoXform) {
3812       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3813       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3814                                        LN0->getChain(),
3815                                        LN0->getBasePtr(), LN0->getSrcValue(),
3816                                        LN0->getSrcValueOffset(),
3817                                        N0.getValueType(),
3818                                        LN0->isVolatile(), LN0->isNonTemporal(),
3819                                        LN0->getAlignment());
3820       CombineTo(N, ExtLoad);
3821       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3822                                   N0.getValueType(), ExtLoad);
3823       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3824
3825       // Extend SetCC uses if necessary.
3826       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3827         SDNode *SetCC = SetCCs[i];
3828         SmallVector<SDValue, 4> Ops;
3829
3830         for (unsigned j = 0; j != 2; ++j) {
3831           SDValue SOp = SetCC->getOperand(j);
3832           if (SOp == Trunc)
3833             Ops.push_back(ExtLoad);
3834           else
3835             Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3836                                       N->getDebugLoc(), VT, SOp));
3837         }
3838
3839         Ops.push_back(SetCC->getOperand(2));
3840         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3841                                      SetCC->getValueType(0),
3842                                      &Ops[0], Ops.size()));
3843       }
3844
3845       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3846     }
3847   }
3848
3849   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3850   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3851   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
3852   if (N0.getOpcode() == ISD::LOAD &&
3853       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3854       N0.hasOneUse()) {
3855     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3856     EVT MemVT = LN0->getMemoryVT();
3857     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3858                                      VT, LN0->getChain(), LN0->getBasePtr(),
3859                                      LN0->getSrcValue(),
3860                                      LN0->getSrcValueOffset(), MemVT,
3861                                      LN0->isVolatile(), LN0->isNonTemporal(),
3862                                      LN0->getAlignment());
3863     CombineTo(N, ExtLoad);
3864     CombineTo(N0.getNode(),
3865               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3866                           N0.getValueType(), ExtLoad),
3867               ExtLoad.getValue(1));
3868     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3869   }
3870
3871   // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3872   if (N0.getOpcode() == ISD::SETCC) {
3873     SDValue SCC =
3874       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3875                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3876                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3877     if (SCC.getNode())
3878       return SCC;
3879   }
3880
3881   return SDValue();
3882 }
3883
3884 /// GetDemandedBits - See if the specified operand can be simplified with the
3885 /// knowledge that only the bits specified by Mask are used.  If so, return the
3886 /// simpler operand, otherwise return a null SDValue.
3887 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3888   switch (V.getOpcode()) {
3889   default: break;
3890   case ISD::OR:
3891   case ISD::XOR:
3892     // If the LHS or RHS don't contribute bits to the or, drop them.
3893     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3894       return V.getOperand(1);
3895     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3896       return V.getOperand(0);
3897     break;
3898   case ISD::SRL:
3899     // Only look at single-use SRLs.
3900     if (!V.getNode()->hasOneUse())
3901       break;
3902     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3903       // See if we can recursively simplify the LHS.
3904       unsigned Amt = RHSC->getZExtValue();
3905
3906       // Watch out for shift count overflow though.
3907       if (Amt >= Mask.getBitWidth()) break;
3908       APInt NewMask = Mask << Amt;
3909       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3910       if (SimplifyLHS.getNode())
3911         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3912                            SimplifyLHS, V.getOperand(1));
3913     }
3914   }
3915   return SDValue();
3916 }
3917
3918 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3919 /// bits and then truncated to a narrower type and where N is a multiple
3920 /// of number of bits of the narrower type, transform it to a narrower load
3921 /// from address + N / num of bits of new type. If the result is to be
3922 /// extended, also fold the extension to form a extending load.
3923 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3924   unsigned Opc = N->getOpcode();
3925   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3926   SDValue N0 = N->getOperand(0);
3927   EVT VT = N->getValueType(0);
3928   EVT ExtVT = VT;
3929
3930   // This transformation isn't valid for vector loads.
3931   if (VT.isVector())
3932     return SDValue();
3933
3934   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3935   // extended to VT.
3936   if (Opc == ISD::SIGN_EXTEND_INREG) {
3937     ExtType = ISD::SEXTLOAD;
3938     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3939     if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3940       return SDValue();
3941   }
3942
3943   unsigned EVTBits = ExtVT.getSizeInBits();
3944   unsigned ShAmt = 0;
3945   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3946     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3947       ShAmt = N01->getZExtValue();
3948       // Is the shift amount a multiple of size of VT?
3949       if ((ShAmt & (EVTBits-1)) == 0) {
3950         N0 = N0.getOperand(0);
3951         // Is the load width a multiple of size of VT?
3952         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3953           return SDValue();
3954       }
3955     }
3956   }
3957
3958   // Do not generate loads of non-round integer types since these can
3959   // be expensive (and would be wrong if the type is not byte sized).
3960   if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3961       cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
3962       // Do not change the width of a volatile load.
3963       !cast<LoadSDNode>(N0)->isVolatile()) {
3964     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3965     EVT PtrType = N0.getOperand(1).getValueType();
3966
3967     // For big endian targets, we need to adjust the offset to the pointer to
3968     // load the correct bytes.
3969     if (TLI.isBigEndian()) {
3970       unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3971       unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3972       ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3973     }
3974
3975     uint64_t PtrOff =  ShAmt / 8;
3976     unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3977     SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3978                                  PtrType, LN0->getBasePtr(),
3979                                  DAG.getConstant(PtrOff, PtrType));
3980     AddToWorkList(NewPtr.getNode());
3981
3982     SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3983       ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3984                     LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3985                     LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
3986       : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3987                        LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3988                        ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3989                        NewAlign);
3990
3991     // Replace the old load's chain with the new load's chain.
3992     WorkListRemover DeadNodes(*this);
3993     DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3994                                   &DeadNodes);
3995
3996     // Return the new loaded value.
3997     return Load;
3998   }
3999
4000   return SDValue();
4001 }
4002
4003 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4004   SDValue N0 = N->getOperand(0);
4005   SDValue N1 = N->getOperand(1);
4006   EVT VT = N->getValueType(0);
4007   EVT EVT = cast<VTSDNode>(N1)->getVT();
4008   unsigned VTBits = VT.getScalarType().getSizeInBits();
4009   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4010
4011   // fold (sext_in_reg c1) -> c1
4012   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4013     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4014
4015   // If the input is already sign extended, just drop the extension.
4016   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4017     return N0;
4018
4019   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4020   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4021       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4022     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4023                        N0.getOperand(0), N1);
4024   }
4025
4026   // fold (sext_in_reg (sext x)) -> (sext x)
4027   // fold (sext_in_reg (aext x)) -> (sext x)
4028   // if x is small enough.
4029   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4030     SDValue N00 = N0.getOperand(0);
4031     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4032         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4033       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4034   }
4035
4036   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4037   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4038     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4039
4040   // fold operands of sext_in_reg based on knowledge that the top bits are not
4041   // demanded.
4042   if (SimplifyDemandedBits(SDValue(N, 0)))
4043     return SDValue(N, 0);
4044
4045   // fold (sext_in_reg (load x)) -> (smaller sextload x)
4046   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4047   SDValue NarrowLoad = ReduceLoadWidth(N);
4048   if (NarrowLoad.getNode())
4049     return NarrowLoad;
4050
4051   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4052   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4053   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4054   if (N0.getOpcode() == ISD::SRL) {
4055     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4056       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4057         // We can turn this into an SRA iff the input to the SRL is already sign
4058         // extended enough.
4059         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4060         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4061           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4062                              N0.getOperand(0), N0.getOperand(1));
4063       }
4064   }
4065
4066   // fold (sext_inreg (extload x)) -> (sextload x)
4067   if (ISD::isEXTLoad(N0.getNode()) &&
4068       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4069       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4070       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4071        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4072     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4073     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4074                                      LN0->getChain(),
4075                                      LN0->getBasePtr(), LN0->getSrcValue(),
4076                                      LN0->getSrcValueOffset(), EVT,
4077                                      LN0->isVolatile(), LN0->isNonTemporal(),
4078                                      LN0->getAlignment());
4079     CombineTo(N, ExtLoad);
4080     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4081     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4082   }
4083   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4084   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4085       N0.hasOneUse() &&
4086       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4087       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4088        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4089     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4090     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4091                                      LN0->getChain(),
4092                                      LN0->getBasePtr(), LN0->getSrcValue(),
4093                                      LN0->getSrcValueOffset(), EVT,
4094                                      LN0->isVolatile(), LN0->isNonTemporal(),
4095                                      LN0->getAlignment());
4096     CombineTo(N, ExtLoad);
4097     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4098     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4099   }
4100   return SDValue();
4101 }
4102
4103 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4104   SDValue N0 = N->getOperand(0);
4105   EVT VT = N->getValueType(0);
4106
4107   // noop truncate
4108   if (N0.getValueType() == N->getValueType(0))
4109     return N0;
4110   // fold (truncate c1) -> c1
4111   if (isa<ConstantSDNode>(N0))
4112     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4113   // fold (truncate (truncate x)) -> (truncate x)
4114   if (N0.getOpcode() == ISD::TRUNCATE)
4115     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4116   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4117   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4118       N0.getOpcode() == ISD::SIGN_EXTEND ||
4119       N0.getOpcode() == ISD::ANY_EXTEND) {
4120     if (N0.getOperand(0).getValueType().bitsLT(VT))
4121       // if the source is smaller than the dest, we still need an extend
4122       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4123                          N0.getOperand(0));
4124     else if (N0.getOperand(0).getValueType().bitsGT(VT))
4125       // if the source is larger than the dest, than we just need the truncate
4126       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4127     else
4128       // if the source and dest are the same type, we can drop both the extend
4129       // and the truncate.
4130       return N0.getOperand(0);
4131   }
4132
4133   // See if we can simplify the input to this truncate through knowledge that
4134   // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
4135   // -> trunc y
4136   SDValue Shorter =
4137     GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4138                                              VT.getSizeInBits()));
4139   if (Shorter.getNode())
4140     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4141
4142   // fold (truncate (load x)) -> (smaller load x)
4143   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4144   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT))
4145     return ReduceLoadWidth(N);
4146   return SDValue();
4147 }
4148
4149 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4150   SDValue Elt = N->getOperand(i);
4151   if (Elt.getOpcode() != ISD::MERGE_VALUES)
4152     return Elt.getNode();
4153   return Elt.getOperand(Elt.getResNo()).getNode();
4154 }
4155
4156 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4157 /// if load locations are consecutive.
4158 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4159   assert(N->getOpcode() == ISD::BUILD_PAIR);
4160
4161   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4162   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4163   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
4164     return SDValue();
4165   EVT LD1VT = LD1->getValueType(0);
4166
4167   if (ISD::isNON_EXTLoad(LD2) &&
4168       LD2->hasOneUse() &&
4169       // If both are volatile this would reduce the number of volatile loads.
4170       // If one is volatile it might be ok, but play conservative and bail out.
4171       !LD1->isVolatile() &&
4172       !LD2->isVolatile() &&
4173       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4174     unsigned Align = LD1->getAlignment();
4175     unsigned NewAlign = TLI.getTargetData()->
4176       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4177
4178     if (NewAlign <= Align &&
4179         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4180       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4181                          LD1->getBasePtr(), LD1->getSrcValue(),
4182                          LD1->getSrcValueOffset(), false, false, Align);
4183   }
4184
4185   return SDValue();
4186 }
4187
4188 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4189   SDValue N0 = N->getOperand(0);
4190   EVT VT = N->getValueType(0);
4191
4192   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4193   // Only do this before legalize, since afterward the target may be depending
4194   // on the bitconvert.
4195   // First check to see if this is all constant.
4196   if (!LegalTypes &&
4197       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4198       VT.isVector()) {
4199     bool isSimple = true;
4200     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4201       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4202           N0.getOperand(i).getOpcode() != ISD::Constant &&
4203           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4204         isSimple = false;
4205         break;
4206       }
4207
4208     EVT DestEltVT = N->getValueType(0).getVectorElementType();
4209     assert(!DestEltVT.isVector() &&
4210            "Element type of vector ValueType must not be vector!");
4211     if (isSimple)
4212       return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4213   }
4214
4215   // If the input is a constant, let getNode fold it.
4216   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4217     SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4218     if (Res.getNode() != N) {
4219       if (!LegalOperations ||
4220           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4221         return Res;
4222
4223       // Folding it resulted in an illegal node, and it's too late to
4224       // do that. Clean up the old node and forego the transformation.
4225       // Ideally this won't happen very often, because instcombine
4226       // and the earlier dagcombine runs (where illegal nodes are
4227       // permitted) should have folded most of them already.
4228       DAG.DeleteNode(Res.getNode());
4229     }
4230   }
4231
4232   // (conv (conv x, t1), t2) -> (conv x, t2)
4233   if (N0.getOpcode() == ISD::BIT_CONVERT)
4234     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4235                        N0.getOperand(0));
4236
4237   // fold (conv (load x)) -> (load (conv*)x)
4238   // If the resultant load doesn't need a higher alignment than the original!
4239   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4240       // Do not change the width of a volatile load.
4241       !cast<LoadSDNode>(N0)->isVolatile() &&
4242       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4243     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4244     unsigned Align = TLI.getTargetData()->
4245       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4246     unsigned OrigAlign = LN0->getAlignment();
4247
4248     if (Align <= OrigAlign) {
4249       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4250                                  LN0->getBasePtr(),
4251                                  LN0->getSrcValue(), LN0->getSrcValueOffset(),
4252                                  LN0->isVolatile(), LN0->isNonTemporal(),
4253                                  OrigAlign);
4254       AddToWorkList(N);
4255       CombineTo(N0.getNode(),
4256                 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4257                             N0.getValueType(), Load),
4258                 Load.getValue(1));
4259       return Load;
4260     }
4261   }
4262
4263   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4264   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4265   // This often reduces constant pool loads.
4266   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4267       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4268     SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4269                                   N0.getOperand(0));
4270     AddToWorkList(NewConv.getNode());
4271
4272     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4273     if (N0.getOpcode() == ISD::FNEG)
4274       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4275                          NewConv, DAG.getConstant(SignBit, VT));
4276     assert(N0.getOpcode() == ISD::FABS);
4277     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4278                        NewConv, DAG.getConstant(~SignBit, VT));
4279   }
4280
4281   // fold (bitconvert (fcopysign cst, x)) ->
4282   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
4283   // Note that we don't handle (copysign x, cst) because this can always be
4284   // folded to an fneg or fabs.
4285   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4286       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4287       VT.isInteger() && !VT.isVector()) {
4288     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4289     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4290     if (isTypeLegal(IntXVT)) {
4291       SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4292                               IntXVT, N0.getOperand(1));
4293       AddToWorkList(X.getNode());
4294
4295       // If X has a different width than the result/lhs, sext it or truncate it.
4296       unsigned VTWidth = VT.getSizeInBits();
4297       if (OrigXWidth < VTWidth) {
4298         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4299         AddToWorkList(X.getNode());
4300       } else if (OrigXWidth > VTWidth) {
4301         // To get the sign bit in the right place, we have to shift it right
4302         // before truncating.
4303         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4304                         X.getValueType(), X,
4305                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4306         AddToWorkList(X.getNode());
4307         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4308         AddToWorkList(X.getNode());
4309       }
4310
4311       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4312       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4313                       X, DAG.getConstant(SignBit, VT));
4314       AddToWorkList(X.getNode());
4315
4316       SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4317                                 VT, N0.getOperand(0));
4318       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4319                         Cst, DAG.getConstant(~SignBit, VT));
4320       AddToWorkList(Cst.getNode());
4321
4322       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4323     }
4324   }
4325
4326   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4327   if (N0.getOpcode() == ISD::BUILD_PAIR) {
4328     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4329     if (CombineLD.getNode())
4330       return CombineLD;
4331   }
4332
4333   return SDValue();
4334 }
4335
4336 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4337   EVT VT = N->getValueType(0);
4338   return CombineConsecutiveLoads(N, VT);
4339 }
4340
4341 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4342 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
4343 /// destination element value type.
4344 SDValue DAGCombiner::
4345 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4346   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4347
4348   // If this is already the right type, we're done.
4349   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4350
4351   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4352   unsigned DstBitSize = DstEltVT.getSizeInBits();
4353
4354   // If this is a conversion of N elements of one type to N elements of another
4355   // type, convert each element.  This handles FP<->INT cases.
4356   if (SrcBitSize == DstBitSize) {
4357     SmallVector<SDValue, 8> Ops;
4358     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4359       SDValue Op = BV->getOperand(i);
4360       // If the vector element type is not legal, the BUILD_VECTOR operands
4361       // are promoted and implicitly truncated.  Make that explicit here.
4362       if (Op.getValueType() != SrcEltVT)
4363         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4364       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4365                                 DstEltVT, Op));
4366       AddToWorkList(Ops.back().getNode());
4367     }
4368     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4369                               BV->getValueType(0).getVectorNumElements());
4370     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4371                        &Ops[0], Ops.size());
4372   }
4373
4374   // Otherwise, we're growing or shrinking the elements.  To avoid having to
4375   // handle annoying details of growing/shrinking FP values, we convert them to
4376   // int first.
4377   if (SrcEltVT.isFloatingPoint()) {
4378     // Convert the input float vector to a int vector where the elements are the
4379     // same sizes.
4380     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4381     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4382     BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4383     SrcEltVT = IntVT;
4384   }
4385
4386   // Now we know the input is an integer vector.  If the output is a FP type,
4387   // convert to integer first, then to FP of the right size.
4388   if (DstEltVT.isFloatingPoint()) {
4389     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4390     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4391     SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4392
4393     // Next, convert to FP elements of the same size.
4394     return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4395   }
4396
4397   // Okay, we know the src/dst types are both integers of differing types.
4398   // Handling growing first.
4399   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4400   if (SrcBitSize < DstBitSize) {
4401     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4402
4403     SmallVector<SDValue, 8> Ops;
4404     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4405          i += NumInputsPerOutput) {
4406       bool isLE = TLI.isLittleEndian();
4407       APInt NewBits = APInt(DstBitSize, 0);
4408       bool EltIsUndef = true;
4409       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4410         // Shift the previously computed bits over.
4411         NewBits <<= SrcBitSize;
4412         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4413         if (Op.getOpcode() == ISD::UNDEF) continue;
4414         EltIsUndef = false;
4415
4416         NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4417                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
4418       }
4419
4420       if (EltIsUndef)
4421         Ops.push_back(DAG.getUNDEF(DstEltVT));
4422       else
4423         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4424     }
4425
4426     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4427     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4428                        &Ops[0], Ops.size());
4429   }
4430
4431   // Finally, this must be the case where we are shrinking elements: each input
4432   // turns into multiple outputs.
4433   bool isS2V = ISD::isScalarToVector(BV);
4434   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4435   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4436                             NumOutputsPerInput*BV->getNumOperands());
4437   SmallVector<SDValue, 8> Ops;
4438
4439   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4440     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4441       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4442         Ops.push_back(DAG.getUNDEF(DstEltVT));
4443       continue;
4444     }
4445
4446     APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4447                         getAPIntValue()).zextOrTrunc(SrcBitSize);
4448
4449     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4450       APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4451       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4452       if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4453         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4454         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4455                            Ops[0]);
4456       OpVal = OpVal.lshr(DstBitSize);
4457     }
4458
4459     // For big endian targets, swap the order of the pieces of each element.
4460     if (TLI.isBigEndian())
4461       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4462   }
4463
4464   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4465                      &Ops[0], Ops.size());
4466 }
4467
4468 SDValue DAGCombiner::visitFADD(SDNode *N) {
4469   SDValue N0 = N->getOperand(0);
4470   SDValue N1 = N->getOperand(1);
4471   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4472   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4473   EVT VT = N->getValueType(0);
4474
4475   // fold vector ops
4476   if (VT.isVector()) {
4477     SDValue FoldedVOp = SimplifyVBinOp(N);
4478     if (FoldedVOp.getNode()) return FoldedVOp;
4479   }
4480
4481   // fold (fadd c1, c2) -> (fadd c1, c2)
4482   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4483     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4484   // canonicalize constant to RHS
4485   if (N0CFP && !N1CFP)
4486     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4487   // fold (fadd A, 0) -> A
4488   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4489     return N0;
4490   // fold (fadd A, (fneg B)) -> (fsub A, B)
4491   if (isNegatibleForFree(N1, LegalOperations) == 2)
4492     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4493                        GetNegatedExpression(N1, DAG, LegalOperations));
4494   // fold (fadd (fneg A), B) -> (fsub B, A)
4495   if (isNegatibleForFree(N0, LegalOperations) == 2)
4496     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4497                        GetNegatedExpression(N0, DAG, LegalOperations));
4498
4499   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4500   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4501       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4502     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4503                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4504                                    N0.getOperand(1), N1));
4505
4506   return SDValue();
4507 }
4508
4509 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4510   SDValue N0 = N->getOperand(0);
4511   SDValue N1 = N->getOperand(1);
4512   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4513   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4514   EVT VT = N->getValueType(0);
4515
4516   // fold vector ops
4517   if (VT.isVector()) {
4518     SDValue FoldedVOp = SimplifyVBinOp(N);
4519     if (FoldedVOp.getNode()) return FoldedVOp;
4520   }
4521
4522   // fold (fsub c1, c2) -> c1-c2
4523   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4524     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4525   // fold (fsub A, 0) -> A
4526   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4527     return N0;
4528   // fold (fsub 0, B) -> -B
4529   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4530     if (isNegatibleForFree(N1, LegalOperations))
4531       return GetNegatedExpression(N1, DAG, LegalOperations);
4532     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4533       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4534   }
4535   // fold (fsub A, (fneg B)) -> (fadd A, B)
4536   if (isNegatibleForFree(N1, LegalOperations))
4537     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4538                        GetNegatedExpression(N1, DAG, LegalOperations));
4539
4540   return SDValue();
4541 }
4542
4543 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4544   SDValue N0 = N->getOperand(0);
4545   SDValue N1 = N->getOperand(1);
4546   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4547   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4548   EVT VT = N->getValueType(0);
4549
4550   // fold vector ops
4551   if (VT.isVector()) {
4552     SDValue FoldedVOp = SimplifyVBinOp(N);
4553     if (FoldedVOp.getNode()) return FoldedVOp;
4554   }
4555
4556   // fold (fmul c1, c2) -> c1*c2
4557   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4558     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4559   // canonicalize constant to RHS
4560   if (N0CFP && !N1CFP)
4561     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4562   // fold (fmul A, 0) -> 0
4563   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4564     return N1;
4565   // fold (fmul A, 0) -> 0, vector edition.
4566   if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4567     return N1;
4568   // fold (fmul X, 2.0) -> (fadd X, X)
4569   if (N1CFP && N1CFP->isExactlyValue(+2.0))
4570     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4571   // fold (fmul X, -1.0) -> (fneg X)
4572   if (N1CFP && N1CFP->isExactlyValue(-1.0))
4573     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4574       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4575
4576   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4577   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4578     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4579       // Both can be negated for free, check to see if at least one is cheaper
4580       // negated.
4581       if (LHSNeg == 2 || RHSNeg == 2)
4582         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4583                            GetNegatedExpression(N0, DAG, LegalOperations),
4584                            GetNegatedExpression(N1, DAG, LegalOperations));
4585     }
4586   }
4587
4588   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4589   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4590       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4591     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4592                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4593                                    N0.getOperand(1), N1));
4594
4595   return SDValue();
4596 }
4597
4598 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4599   SDValue N0 = N->getOperand(0);
4600   SDValue N1 = N->getOperand(1);
4601   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4602   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4603   EVT VT = N->getValueType(0);
4604
4605   // fold vector ops
4606   if (VT.isVector()) {
4607     SDValue FoldedVOp = SimplifyVBinOp(N);
4608     if (FoldedVOp.getNode()) return FoldedVOp;
4609   }
4610
4611   // fold (fdiv c1, c2) -> c1/c2
4612   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4613     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4614
4615
4616   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4617   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4618     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4619       // Both can be negated for free, check to see if at least one is cheaper
4620       // negated.
4621       if (LHSNeg == 2 || RHSNeg == 2)
4622         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4623                            GetNegatedExpression(N0, DAG, LegalOperations),
4624                            GetNegatedExpression(N1, DAG, LegalOperations));
4625     }
4626   }
4627
4628   return SDValue();
4629 }
4630
4631 SDValue DAGCombiner::visitFREM(SDNode *N) {
4632   SDValue N0 = N->getOperand(0);
4633   SDValue N1 = N->getOperand(1);
4634   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4635   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4636   EVT VT = N->getValueType(0);
4637
4638   // fold (frem c1, c2) -> fmod(c1,c2)
4639   if (N0CFP && N1CFP && VT != MVT::ppcf128)
4640     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4641
4642   return SDValue();
4643 }
4644
4645 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4646   SDValue N0 = N->getOperand(0);
4647   SDValue N1 = N->getOperand(1);
4648   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4649   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4650   EVT VT = N->getValueType(0);
4651
4652   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
4653     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4654
4655   if (N1CFP) {
4656     const APFloat& V = N1CFP->getValueAPF();
4657     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
4658     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4659     if (!V.isNegative()) {
4660       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4661         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4662     } else {
4663       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4664         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4665                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4666     }
4667   }
4668
4669   // copysign(fabs(x), y) -> copysign(x, y)
4670   // copysign(fneg(x), y) -> copysign(x, y)
4671   // copysign(copysign(x,z), y) -> copysign(x, y)
4672   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4673       N0.getOpcode() == ISD::FCOPYSIGN)
4674     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4675                        N0.getOperand(0), N1);
4676
4677   // copysign(x, abs(y)) -> abs(x)
4678   if (N1.getOpcode() == ISD::FABS)
4679     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4680
4681   // copysign(x, copysign(y,z)) -> copysign(x, z)
4682   if (N1.getOpcode() == ISD::FCOPYSIGN)
4683     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4684                        N0, N1.getOperand(1));
4685
4686   // copysign(x, fp_extend(y)) -> copysign(x, y)
4687   // copysign(x, fp_round(y)) -> copysign(x, y)
4688   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4689     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4690                        N0, N1.getOperand(0));
4691
4692   return SDValue();
4693 }
4694
4695 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4696   SDValue N0 = N->getOperand(0);
4697   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4698   EVT VT = N->getValueType(0);
4699   EVT OpVT = N0.getValueType();
4700
4701   // fold (sint_to_fp c1) -> c1fp
4702   if (N0C && OpVT != MVT::ppcf128)
4703     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4704
4705   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4706   // but UINT_TO_FP is legal on this target, try to convert.
4707   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4708       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4709     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4710     if (DAG.SignBitIsZero(N0))
4711       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4712   }
4713
4714   return SDValue();
4715 }
4716
4717 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4718   SDValue N0 = N->getOperand(0);
4719   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4720   EVT VT = N->getValueType(0);
4721   EVT OpVT = N0.getValueType();
4722
4723   // fold (uint_to_fp c1) -> c1fp
4724   if (N0C && OpVT != MVT::ppcf128)
4725     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4726
4727   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4728   // but SINT_TO_FP is legal on this target, try to convert.
4729   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4730       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4731     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4732     if (DAG.SignBitIsZero(N0))
4733       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4734   }
4735
4736   return SDValue();
4737 }
4738
4739 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4740   SDValue N0 = N->getOperand(0);
4741   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4742   EVT VT = N->getValueType(0);
4743
4744   // fold (fp_to_sint c1fp) -> c1
4745   if (N0CFP)
4746     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4747
4748   return SDValue();
4749 }
4750
4751 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4752   SDValue N0 = N->getOperand(0);
4753   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4754   EVT VT = N->getValueType(0);
4755
4756   // fold (fp_to_uint c1fp) -> c1
4757   if (N0CFP && VT != MVT::ppcf128)
4758     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4759
4760   return SDValue();
4761 }
4762
4763 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4764   SDValue N0 = N->getOperand(0);
4765   SDValue N1 = N->getOperand(1);
4766   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4767   EVT VT = N->getValueType(0);
4768
4769   // fold (fp_round c1fp) -> c1fp
4770   if (N0CFP && N0.getValueType() != MVT::ppcf128)
4771     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4772
4773   // fold (fp_round (fp_extend x)) -> x
4774   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4775     return N0.getOperand(0);
4776
4777   // fold (fp_round (fp_round x)) -> (fp_round x)
4778   if (N0.getOpcode() == ISD::FP_ROUND) {
4779     // This is a value preserving truncation if both round's are.
4780     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4781                    N0.getNode()->getConstantOperandVal(1) == 1;
4782     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4783                        DAG.getIntPtrConstant(IsTrunc));
4784   }
4785
4786   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4787   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4788     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4789                               N0.getOperand(0), N1);
4790     AddToWorkList(Tmp.getNode());
4791     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4792                        Tmp, N0.getOperand(1));
4793   }
4794
4795   return SDValue();
4796 }
4797
4798 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4799   SDValue N0 = N->getOperand(0);
4800   EVT VT = N->getValueType(0);
4801   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4802   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4803
4804   // fold (fp_round_inreg c1fp) -> c1fp
4805   if (N0CFP && isTypeLegal(EVT)) {
4806     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4807     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4808   }
4809
4810   return SDValue();
4811 }
4812
4813 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4814   SDValue N0 = N->getOperand(0);
4815   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4816   EVT VT = N->getValueType(0);
4817
4818   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4819   if (N->hasOneUse() &&
4820       N->use_begin()->getOpcode() == ISD::FP_ROUND)
4821     return SDValue();
4822
4823   // fold (fp_extend c1fp) -> c1fp
4824   if (N0CFP && VT != MVT::ppcf128)
4825     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4826
4827   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4828   // value of X.
4829   if (N0.getOpcode() == ISD::FP_ROUND
4830       && N0.getNode()->getConstantOperandVal(1) == 1) {
4831     SDValue In = N0.getOperand(0);
4832     if (In.getValueType() == VT) return In;
4833     if (VT.bitsLT(In.getValueType()))
4834       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4835                          In, N0.getOperand(1));
4836     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4837   }
4838
4839   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4840   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4841       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4842        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4844     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4845                                      LN0->getChain(),
4846                                      LN0->getBasePtr(), LN0->getSrcValue(),
4847                                      LN0->getSrcValueOffset(),
4848                                      N0.getValueType(),
4849                                      LN0->isVolatile(), LN0->isNonTemporal(),
4850                                      LN0->getAlignment());
4851     CombineTo(N, ExtLoad);
4852     CombineTo(N0.getNode(),
4853               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4854                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4855               ExtLoad.getValue(1));
4856     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4857   }
4858
4859   return SDValue();
4860 }
4861
4862 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4863   SDValue N0 = N->getOperand(0);
4864   EVT VT = N->getValueType(0);
4865
4866   if (isNegatibleForFree(N0, LegalOperations))
4867     return GetNegatedExpression(N0, DAG, LegalOperations);
4868
4869   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4870   // constant pool values.
4871   if (N0.getOpcode() == ISD::BIT_CONVERT && 
4872       !VT.isVector() &&
4873       N0.getNode()->hasOneUse() &&
4874       N0.getOperand(0).getValueType().isInteger()) {
4875     SDValue Int = N0.getOperand(0);
4876     EVT IntVT = Int.getValueType();
4877     if (IntVT.isInteger() && !IntVT.isVector()) {
4878       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4879               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4880       AddToWorkList(Int.getNode());
4881       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4882                          VT, Int);
4883     }
4884   }
4885
4886   return SDValue();
4887 }
4888
4889 SDValue DAGCombiner::visitFABS(SDNode *N) {
4890   SDValue N0 = N->getOperand(0);
4891   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4892   EVT VT = N->getValueType(0);
4893
4894   // fold (fabs c1) -> fabs(c1)
4895   if (N0CFP && VT != MVT::ppcf128)
4896     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4897   // fold (fabs (fabs x)) -> (fabs x)
4898   if (N0.getOpcode() == ISD::FABS)
4899     return N->getOperand(0);
4900   // fold (fabs (fneg x)) -> (fabs x)
4901   // fold (fabs (fcopysign x, y)) -> (fabs x)
4902   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4903     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4904
4905   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4906   // constant pool values.
4907   if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4908       N0.getOperand(0).getValueType().isInteger() &&
4909       !N0.getOperand(0).getValueType().isVector()) {
4910     SDValue Int = N0.getOperand(0);
4911     EVT IntVT = Int.getValueType();
4912     if (IntVT.isInteger() && !IntVT.isVector()) {
4913       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4914              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4915       AddToWorkList(Int.getNode());
4916       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4917                          N->getValueType(0), Int);
4918     }
4919   }
4920
4921   return SDValue();
4922 }
4923
4924 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4925   SDValue Chain = N->getOperand(0);
4926   SDValue N1 = N->getOperand(1);
4927   SDValue N2 = N->getOperand(2);
4928
4929   // If N is a constant we could fold this into a fallthrough or unconditional
4930   // branch. However that doesn't happen very often in normal code, because
4931   // Instcombine/SimplifyCFG should have handled the available opportunities.
4932   // If we did this folding here, it would be necessary to update the
4933   // MachineBasicBlock CFG, which is awkward.
4934
4935   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4936   // on the target.
4937   if (N1.getOpcode() == ISD::SETCC &&
4938       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4939     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4940                        Chain, N1.getOperand(2),
4941                        N1.getOperand(0), N1.getOperand(1), N2);
4942   }
4943
4944   SDNode *Trunc = 0;
4945   if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4946     // Look past truncate.
4947     Trunc = N1.getNode();
4948     N1 = N1.getOperand(0);
4949   }
4950
4951   if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4952     // Match this pattern so that we can generate simpler code:
4953     //
4954     //   %a = ...
4955     //   %b = and i32 %a, 2
4956     //   %c = srl i32 %b, 1
4957     //   brcond i32 %c ...
4958     //
4959     // into
4960     // 
4961     //   %a = ...
4962     //   %b = and i32 %a, 2
4963     //   %c = setcc eq %b, 0
4964     //   brcond %c ...
4965     //
4966     // This applies only when the AND constant value has one bit set and the
4967     // SRL constant is equal to the log2 of the AND constant. The back-end is
4968     // smart enough to convert the result into a TEST/JMP sequence.
4969     SDValue Op0 = N1.getOperand(0);
4970     SDValue Op1 = N1.getOperand(1);
4971
4972     if (Op0.getOpcode() == ISD::AND &&
4973         Op1.getOpcode() == ISD::Constant) {
4974       SDValue AndOp1 = Op0.getOperand(1);
4975
4976       if (AndOp1.getOpcode() == ISD::Constant) {
4977         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4978
4979         if (AndConst.isPowerOf2() &&
4980             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4981           SDValue SetCC =
4982             DAG.getSetCC(N->getDebugLoc(),
4983                          TLI.getSetCCResultType(Op0.getValueType()),
4984                          Op0, DAG.getConstant(0, Op0.getValueType()),
4985                          ISD::SETNE);
4986
4987           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4988                                           MVT::Other, Chain, SetCC, N2);
4989           // Don't add the new BRCond into the worklist or else SimplifySelectCC
4990           // will convert it back to (X & C1) >> C2.
4991           CombineTo(N, NewBRCond, false);
4992           // Truncate is dead.
4993           if (Trunc) {
4994             removeFromWorkList(Trunc);
4995             DAG.DeleteNode(Trunc);
4996           }
4997           // Replace the uses of SRL with SETCC
4998           WorkListRemover DeadNodes(*this);
4999           DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5000           removeFromWorkList(N1.getNode());
5001           DAG.DeleteNode(N1.getNode());
5002           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5003         }
5004       }
5005     }
5006   }
5007   
5008   // Transform br(xor(x, y)) -> br(x != y)
5009   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5010   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5011     SDNode *TheXor = N1.getNode();
5012     SDValue Op0 = TheXor->getOperand(0);
5013     SDValue Op1 = TheXor->getOperand(1);
5014     if (Op0.getOpcode() == Op1.getOpcode()) {
5015       // Avoid missing important xor optimizations.
5016       SDValue Tmp = visitXOR(TheXor);
5017       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5018         DEBUG(dbgs() << "\nReplacing.8 ";
5019               TheXor->dump(&DAG);
5020               dbgs() << "\nWith: ";
5021               Tmp.getNode()->dump(&DAG);
5022               dbgs() << '\n');
5023         WorkListRemover DeadNodes(*this);
5024         DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5025         removeFromWorkList(TheXor);
5026         DAG.DeleteNode(TheXor);
5027         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5028                            MVT::Other, Chain, Tmp, N2);
5029       }
5030     }
5031
5032     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5033       bool Equal = false;
5034       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5035         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5036             Op0.getOpcode() == ISD::XOR) {
5037           TheXor = Op0.getNode();
5038           Equal = true;
5039         }
5040
5041       SDValue NodeToReplace = Trunc ? SDValue(Trunc, 0) : N1;
5042       
5043       EVT SetCCVT = NodeToReplace.getValueType();
5044       if (LegalTypes)
5045         SetCCVT = TLI.getSetCCResultType(SetCCVT);
5046       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5047                                    SetCCVT,
5048                                    Op0, Op1,
5049                                    Equal ? ISD::SETEQ : ISD::SETNE);
5050       // Replace the uses of XOR with SETCC
5051       WorkListRemover DeadNodes(*this);
5052       DAG.ReplaceAllUsesOfValueWith(NodeToReplace, SetCC, &DeadNodes);
5053       removeFromWorkList(NodeToReplace.getNode());
5054       DAG.DeleteNode(NodeToReplace.getNode());
5055       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5056                          MVT::Other, Chain, SetCC, N2);
5057     }
5058   }
5059
5060   return SDValue();
5061 }
5062
5063 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5064 //
5065 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5066   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5067   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5068
5069   // If N is a constant we could fold this into a fallthrough or unconditional
5070   // branch. However that doesn't happen very often in normal code, because
5071   // Instcombine/SimplifyCFG should have handled the available opportunities.
5072   // If we did this folding here, it would be necessary to update the
5073   // MachineBasicBlock CFG, which is awkward.
5074
5075   // Use SimplifySetCC to simplify SETCC's.
5076   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5077                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5078                                false);
5079   if (Simp.getNode()) AddToWorkList(Simp.getNode());
5080
5081   // fold to a simpler setcc
5082   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5083     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5084                        N->getOperand(0), Simp.getOperand(2),
5085                        Simp.getOperand(0), Simp.getOperand(1),
5086                        N->getOperand(4));
5087
5088   return SDValue();
5089 }
5090
5091 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5092 /// pre-indexed load / store when the base pointer is an add or subtract
5093 /// and it has other uses besides the load / store. After the
5094 /// transformation, the new indexed load / store has effectively folded
5095 /// the add / subtract in and all of its other uses are redirected to the
5096 /// new load / store.
5097 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5098   if (!LegalOperations)
5099     return false;
5100
5101   bool isLoad = true;
5102   SDValue Ptr;
5103   EVT VT;
5104   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5105     if (LD->isIndexed())
5106       return false;
5107     VT = LD->getMemoryVT();
5108     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5109         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5110       return false;
5111     Ptr = LD->getBasePtr();
5112   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5113     if (ST->isIndexed())
5114       return false;
5115     VT = ST->getMemoryVT();
5116     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5117         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5118       return false;
5119     Ptr = ST->getBasePtr();
5120     isLoad = false;
5121   } else {
5122     return false;
5123   }
5124
5125   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5126   // out.  There is no reason to make this a preinc/predec.
5127   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5128       Ptr.getNode()->hasOneUse())
5129     return false;
5130
5131   // Ask the target to do addressing mode selection.
5132   SDValue BasePtr;
5133   SDValue Offset;
5134   ISD::MemIndexedMode AM = ISD::UNINDEXED;
5135   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5136     return false;
5137   // Don't create a indexed load / store with zero offset.
5138   if (isa<ConstantSDNode>(Offset) &&
5139       cast<ConstantSDNode>(Offset)->isNullValue())
5140     return false;
5141
5142   // Try turning it into a pre-indexed load / store except when:
5143   // 1) The new base ptr is a frame index.
5144   // 2) If N is a store and the new base ptr is either the same as or is a
5145   //    predecessor of the value being stored.
5146   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5147   //    that would create a cycle.
5148   // 4) All uses are load / store ops that use it as old base ptr.
5149
5150   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
5151   // (plus the implicit offset) to a register to preinc anyway.
5152   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5153     return false;
5154
5155   // Check #2.
5156   if (!isLoad) {
5157     SDValue Val = cast<StoreSDNode>(N)->getValue();
5158     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5159       return false;
5160   }
5161
5162   // Now check for #3 and #4.
5163   bool RealUse = false;
5164   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5165          E = Ptr.getNode()->use_end(); I != E; ++I) {
5166     SDNode *Use = *I;
5167     if (Use == N)
5168       continue;
5169     if (Use->isPredecessorOf(N))
5170       return false;
5171
5172     if (!((Use->getOpcode() == ISD::LOAD &&
5173            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5174           (Use->getOpcode() == ISD::STORE &&
5175            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5176       RealUse = true;
5177   }
5178
5179   if (!RealUse)
5180     return false;
5181
5182   SDValue Result;
5183   if (isLoad)
5184     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5185                                 BasePtr, Offset, AM);
5186   else
5187     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5188                                  BasePtr, Offset, AM);
5189   ++PreIndexedNodes;
5190   ++NodesCombined;
5191   DEBUG(dbgs() << "\nReplacing.4 ";
5192         N->dump(&DAG);
5193         dbgs() << "\nWith: ";
5194         Result.getNode()->dump(&DAG);
5195         dbgs() << '\n');
5196   WorkListRemover DeadNodes(*this);
5197   if (isLoad) {
5198     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5199                                   &DeadNodes);
5200     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5201                                   &DeadNodes);
5202   } else {
5203     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5204                                   &DeadNodes);
5205   }
5206
5207   // Finally, since the node is now dead, remove it from the graph.
5208   DAG.DeleteNode(N);
5209
5210   // Replace the uses of Ptr with uses of the updated base value.
5211   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5212                                 &DeadNodes);
5213   removeFromWorkList(Ptr.getNode());
5214   DAG.DeleteNode(Ptr.getNode());
5215
5216   return true;
5217 }
5218
5219 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5220 /// add / sub of the base pointer node into a post-indexed load / store.
5221 /// The transformation folded the add / subtract into the new indexed
5222 /// load / store effectively and all of its uses are redirected to the
5223 /// new load / store.
5224 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5225   if (!LegalOperations)
5226     return false;
5227
5228   bool isLoad = true;
5229   SDValue Ptr;
5230   EVT VT;
5231   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
5232     if (LD->isIndexed())
5233       return false;
5234     VT = LD->getMemoryVT();
5235     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5236         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5237       return false;
5238     Ptr = LD->getBasePtr();
5239   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
5240     if (ST->isIndexed())
5241       return false;
5242     VT = ST->getMemoryVT();
5243     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5244         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5245       return false;
5246     Ptr = ST->getBasePtr();
5247     isLoad = false;
5248   } else {
5249     return false;
5250   }
5251
5252   if (Ptr.getNode()->hasOneUse())
5253     return false;
5254
5255   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5256          E = Ptr.getNode()->use_end(); I != E; ++I) {
5257     SDNode *Op = *I;
5258     if (Op == N ||
5259         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5260       continue;
5261
5262     SDValue BasePtr;
5263     SDValue Offset;
5264     ISD::MemIndexedMode AM = ISD::UNINDEXED;
5265     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5266       if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
5267         std::swap(BasePtr, Offset);
5268       if (Ptr != BasePtr)
5269         continue;
5270       // Don't create a indexed load / store with zero offset.
5271       if (isa<ConstantSDNode>(Offset) &&
5272           cast<ConstantSDNode>(Offset)->isNullValue())
5273         continue;
5274
5275       // Try turning it into a post-indexed load / store except when
5276       // 1) All uses are load / store ops that use it as base ptr.
5277       // 2) Op must be independent of N, i.e. Op is neither a predecessor
5278       //    nor a successor of N. Otherwise, if Op is folded that would
5279       //    create a cycle.
5280
5281       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5282         continue;
5283
5284       // Check for #1.
5285       bool TryNext = false;
5286       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5287              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5288         SDNode *Use = *II;
5289         if (Use == Ptr.getNode())
5290           continue;
5291
5292         // If all the uses are load / store addresses, then don't do the
5293         // transformation.
5294         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5295           bool RealUse = false;
5296           for (SDNode::use_iterator III = Use->use_begin(),
5297                  EEE = Use->use_end(); III != EEE; ++III) {
5298             SDNode *UseUse = *III;
5299             if (!((UseUse->getOpcode() == ISD::LOAD &&
5300                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5301                   (UseUse->getOpcode() == ISD::STORE &&
5302                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5303               RealUse = true;
5304           }
5305
5306           if (!RealUse) {
5307             TryNext = true;
5308             break;
5309           }
5310         }
5311       }
5312
5313       if (TryNext)
5314         continue;
5315
5316       // Check for #2
5317       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5318         SDValue Result = isLoad
5319           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5320                                BasePtr, Offset, AM)
5321           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5322                                 BasePtr, Offset, AM);
5323         ++PostIndexedNodes;
5324         ++NodesCombined;
5325         DEBUG(dbgs() << "\nReplacing.5 ";
5326               N->dump(&DAG);
5327               dbgs() << "\nWith: ";
5328               Result.getNode()->dump(&DAG);
5329               dbgs() << '\n');
5330         WorkListRemover DeadNodes(*this);
5331         if (isLoad) {
5332           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5333                                         &DeadNodes);
5334           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5335                                         &DeadNodes);
5336         } else {
5337           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5338                                         &DeadNodes);
5339         }
5340
5341         // Finally, since the node is now dead, remove it from the graph.
5342         DAG.DeleteNode(N);
5343
5344         // Replace the uses of Use with uses of the updated base value.
5345         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5346                                       Result.getValue(isLoad ? 1 : 0),
5347                                       &DeadNodes);
5348         removeFromWorkList(Op);
5349         DAG.DeleteNode(Op);
5350         return true;
5351       }
5352     }
5353   }
5354
5355   return false;
5356 }
5357
5358 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5359   LoadSDNode *LD  = cast<LoadSDNode>(N);
5360   SDValue Chain = LD->getChain();
5361   SDValue Ptr   = LD->getBasePtr();
5362
5363   // If load is not volatile and there are no uses of the loaded value (and
5364   // the updated indexed value in case of indexed loads), change uses of the
5365   // chain value into uses of the chain input (i.e. delete the dead load).
5366   if (!LD->isVolatile()) {
5367     if (N->getValueType(1) == MVT::Other) {
5368       // Unindexed loads.
5369       if (N->hasNUsesOfValue(0, 0)) {
5370         // It's not safe to use the two value CombineTo variant here. e.g.
5371         // v1, chain2 = load chain1, loc
5372         // v2, chain3 = load chain2, loc
5373         // v3         = add v2, c
5374         // Now we replace use of chain2 with chain1.  This makes the second load
5375         // isomorphic to the one we are deleting, and thus makes this load live.
5376         DEBUG(dbgs() << "\nReplacing.6 ";
5377               N->dump(&DAG);
5378               dbgs() << "\nWith chain: ";
5379               Chain.getNode()->dump(&DAG);
5380               dbgs() << "\n");
5381         WorkListRemover DeadNodes(*this);
5382         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5383
5384         if (N->use_empty()) {
5385           removeFromWorkList(N);
5386           DAG.DeleteNode(N);
5387         }
5388
5389         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5390       }
5391     } else {
5392       // Indexed loads.
5393       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5394       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5395         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5396         DEBUG(dbgs() << "\nReplacing.7 ";
5397               N->dump(&DAG);
5398               dbgs() << "\nWith: ";
5399               Undef.getNode()->dump(&DAG);
5400               dbgs() << " and 2 other values\n");
5401         WorkListRemover DeadNodes(*this);
5402         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5403         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5404                                       DAG.getUNDEF(N->getValueType(1)),
5405                                       &DeadNodes);
5406         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5407         removeFromWorkList(N);
5408         DAG.DeleteNode(N);
5409         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5410       }
5411     }
5412   }
5413
5414   // If this load is directly stored, replace the load value with the stored
5415   // value.
5416   // TODO: Handle store large -> read small portion.
5417   // TODO: Handle TRUNCSTORE/LOADEXT
5418   if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5419       !LD->isVolatile()) {
5420     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5421       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5422       if (PrevST->getBasePtr() == Ptr &&
5423           PrevST->getValue().getValueType() == N->getValueType(0))
5424       return CombineTo(N, Chain.getOperand(1), Chain);
5425     }
5426   }
5427
5428   // Try to infer better alignment information than the load already has.
5429   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5430     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5431       if (Align > LD->getAlignment())
5432         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5433                               LD->getValueType(0),
5434                               Chain, Ptr, LD->getSrcValue(),
5435                               LD->getSrcValueOffset(), LD->getMemoryVT(),
5436                               LD->isVolatile(), LD->isNonTemporal(), Align);
5437     }
5438   }
5439
5440   if (CombinerAA) {
5441     // Walk up chain skipping non-aliasing memory nodes.
5442     SDValue BetterChain = FindBetterChain(N, Chain);
5443
5444     // If there is a better chain.
5445     if (Chain != BetterChain) {
5446       SDValue ReplLoad;
5447
5448       // Replace the chain to void dependency.
5449       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5450         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5451                                BetterChain, Ptr,
5452                                LD->getSrcValue(), LD->getSrcValueOffset(),
5453                                LD->isVolatile(), LD->isNonTemporal(),
5454                                LD->getAlignment());
5455       } else {
5456         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5457                                   LD->getValueType(0),
5458                                   BetterChain, Ptr, LD->getSrcValue(),
5459                                   LD->getSrcValueOffset(),
5460                                   LD->getMemoryVT(),
5461                                   LD->isVolatile(),
5462                                   LD->isNonTemporal(),
5463                                   LD->getAlignment());
5464       }
5465
5466       // Create token factor to keep old chain connected.
5467       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5468                                   MVT::Other, Chain, ReplLoad.getValue(1));
5469       
5470       // Make sure the new and old chains are cleaned up.
5471       AddToWorkList(Token.getNode());
5472       
5473       // Replace uses with load result and token factor. Don't add users
5474       // to work list.
5475       return CombineTo(N, ReplLoad.getValue(0), Token, false);
5476     }
5477   }
5478
5479   // Try transforming N to an indexed load.
5480   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5481     return SDValue(N, 0);
5482
5483   return SDValue();
5484 }
5485
5486 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5487 /// load is having specific bytes cleared out.  If so, return the byte size
5488 /// being masked out and the shift amount.
5489 static std::pair<unsigned, unsigned>
5490 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5491   std::pair<unsigned, unsigned> Result(0, 0);
5492   
5493   // Check for the structure we're looking for.
5494   if (V->getOpcode() != ISD::AND ||
5495       !isa<ConstantSDNode>(V->getOperand(1)) ||
5496       !ISD::isNormalLoad(V->getOperand(0).getNode()))
5497     return Result;
5498   
5499   // Check the chain and pointer.
5500   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5501   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
5502   
5503   // The store should be chained directly to the load or be an operand of a
5504   // tokenfactor.
5505   if (LD == Chain.getNode())
5506     ; // ok.
5507   else if (Chain->getOpcode() != ISD::TokenFactor)
5508     return Result; // Fail.
5509   else {
5510     bool isOk = false;
5511     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5512       if (Chain->getOperand(i).getNode() == LD) {
5513         isOk = true;
5514         break;
5515       }
5516     if (!isOk) return Result;
5517   }
5518   
5519   // This only handles simple types.
5520   if (V.getValueType() != MVT::i16 &&
5521       V.getValueType() != MVT::i32 &&
5522       V.getValueType() != MVT::i64)
5523     return Result;
5524
5525   // Check the constant mask.  Invert it so that the bits being masked out are
5526   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
5527   // follow the sign bit for uniformity.
5528   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5529   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5530   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
5531   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5532   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
5533   if (NotMaskLZ == 64) return Result;  // All zero mask.
5534   
5535   // See if we have a continuous run of bits.  If so, we have 0*1+0*
5536   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5537     return Result;
5538
5539   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5540   if (V.getValueType() != MVT::i64 && NotMaskLZ)
5541     NotMaskLZ -= 64-V.getValueSizeInBits();
5542   
5543   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5544   switch (MaskedBytes) {
5545   case 1: 
5546   case 2: 
5547   case 4: break;
5548   default: return Result; // All one mask, or 5-byte mask.
5549   }
5550   
5551   // Verify that the first bit starts at a multiple of mask so that the access
5552   // is aligned the same as the access width.
5553   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5554   
5555   Result.first = MaskedBytes;
5556   Result.second = NotMaskTZ/8;
5557   return Result;
5558 }
5559
5560
5561 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5562 /// provides a value as specified by MaskInfo.  If so, replace the specified
5563 /// store with a narrower store of truncated IVal.
5564 static SDNode *
5565 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5566                                 SDValue IVal, StoreSDNode *St,
5567                                 DAGCombiner *DC) {
5568   unsigned NumBytes = MaskInfo.first;
5569   unsigned ByteShift = MaskInfo.second;
5570   SelectionDAG &DAG = DC->getDAG();
5571   
5572   // Check to see if IVal is all zeros in the part being masked in by the 'or'
5573   // that uses this.  If not, this is not a replacement.
5574   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5575                                   ByteShift*8, (ByteShift+NumBytes)*8);
5576   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5577   
5578   // Check that it is legal on the target to do this.  It is legal if the new
5579   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5580   // legalization.
5581   MVT VT = MVT::getIntegerVT(NumBytes*8);
5582   if (!DC->isTypeLegal(VT))
5583     return 0;
5584   
5585   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
5586   // shifted by ByteShift and truncated down to NumBytes.
5587   if (ByteShift)
5588     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5589                        DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5590
5591   // Figure out the offset for the store and the alignment of the access.
5592   unsigned StOffset;
5593   unsigned NewAlign = St->getAlignment();
5594
5595   if (DAG.getTargetLoweringInfo().isLittleEndian())
5596     StOffset = ByteShift;
5597   else
5598     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5599   
5600   SDValue Ptr = St->getBasePtr();
5601   if (StOffset) {
5602     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5603                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5604     NewAlign = MinAlign(NewAlign, StOffset);
5605   }
5606   
5607   // Truncate down to the new size.
5608   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5609   
5610   ++OpsNarrowed;
5611   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr, 
5612                       St->getSrcValue(), St->getSrcValueOffset()+StOffset,
5613                       false, false, NewAlign).getNode();
5614 }
5615
5616
5617 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5618 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5619 /// of the loaded bits, try narrowing the load and store if it would end up
5620 /// being a win for performance or code size.
5621 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5622   StoreSDNode *ST  = cast<StoreSDNode>(N);
5623   if (ST->isVolatile())
5624     return SDValue();
5625
5626   SDValue Chain = ST->getChain();
5627   SDValue Value = ST->getValue();
5628   SDValue Ptr   = ST->getBasePtr();
5629   EVT VT = Value.getValueType();
5630
5631   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5632     return SDValue();
5633
5634   unsigned Opc = Value.getOpcode();
5635   
5636   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5637   // is a byte mask indicating a consecutive number of bytes, check to see if
5638   // Y is known to provide just those bytes.  If so, we try to replace the
5639   // load + replace + store sequence with a single (narrower) store, which makes
5640   // the load dead.
5641   if (Opc == ISD::OR) {
5642     std::pair<unsigned, unsigned> MaskedLoad;
5643     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5644     if (MaskedLoad.first)
5645       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5646                                                   Value.getOperand(1), ST,this))
5647         return SDValue(NewST, 0);
5648                                            
5649     // Or is commutative, so try swapping X and Y.
5650     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5651     if (MaskedLoad.first)
5652       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5653                                                   Value.getOperand(0), ST,this))
5654         return SDValue(NewST, 0);
5655   }
5656   
5657   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5658       Value.getOperand(1).getOpcode() != ISD::Constant)
5659     return SDValue();
5660
5661   SDValue N0 = Value.getOperand(0);
5662   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5663     LoadSDNode *LD = cast<LoadSDNode>(N0);
5664     if (LD->getBasePtr() != Ptr)
5665       return SDValue();
5666
5667     // Find the type to narrow it the load / op / store to.
5668     SDValue N1 = Value.getOperand(1);
5669     unsigned BitWidth = N1.getValueSizeInBits();
5670     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5671     if (Opc == ISD::AND)
5672       Imm ^= APInt::getAllOnesValue(BitWidth);
5673     if (Imm == 0 || Imm.isAllOnesValue())
5674       return SDValue();
5675     unsigned ShAmt = Imm.countTrailingZeros();
5676     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5677     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5678     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5679     while (NewBW < BitWidth &&
5680            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5681              TLI.isNarrowingProfitable(VT, NewVT))) {
5682       NewBW = NextPowerOf2(NewBW);
5683       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5684     }
5685     if (NewBW >= BitWidth)
5686       return SDValue();
5687
5688     // If the lsb changed does not start at the type bitwidth boundary,
5689     // start at the previous one.
5690     if (ShAmt % NewBW)
5691       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5692     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5693     if ((Imm & Mask) == Imm) {
5694       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5695       if (Opc == ISD::AND)
5696         NewImm ^= APInt::getAllOnesValue(NewBW);
5697       uint64_t PtrOff = ShAmt / 8;
5698       // For big endian targets, we need to adjust the offset to the pointer to
5699       // load the correct bytes.
5700       if (TLI.isBigEndian())
5701         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5702
5703       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5704       const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5705       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5706         return SDValue();
5707
5708       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5709                                    Ptr.getValueType(), Ptr,
5710                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
5711       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5712                                   LD->getChain(), NewPtr,
5713                                   LD->getSrcValue(), LD->getSrcValueOffset(),
5714                                   LD->isVolatile(), LD->isNonTemporal(),
5715                                   NewAlign);
5716       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5717                                    DAG.getConstant(NewImm, NewVT));
5718       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5719                                    NewVal, NewPtr,
5720                                    ST->getSrcValue(), ST->getSrcValueOffset(),
5721                                    false, false, NewAlign);
5722
5723       AddToWorkList(NewPtr.getNode());
5724       AddToWorkList(NewLD.getNode());
5725       AddToWorkList(NewVal.getNode());
5726       WorkListRemover DeadNodes(*this);
5727       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5728                                     &DeadNodes);
5729       ++OpsNarrowed;
5730       return NewST;
5731     }
5732   }
5733
5734   return SDValue();
5735 }
5736
5737 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5738   StoreSDNode *ST  = cast<StoreSDNode>(N);
5739   SDValue Chain = ST->getChain();
5740   SDValue Value = ST->getValue();
5741   SDValue Ptr   = ST->getBasePtr();
5742
5743   // If this is a store of a bit convert, store the input value if the
5744   // resultant store does not need a higher alignment than the original.
5745   if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5746       ST->isUnindexed()) {
5747     unsigned OrigAlign = ST->getAlignment();
5748     EVT SVT = Value.getOperand(0).getValueType();
5749     unsigned Align = TLI.getTargetData()->
5750       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5751     if (Align <= OrigAlign &&
5752         ((!LegalOperations && !ST->isVolatile()) ||
5753          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5754       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5755                           Ptr, ST->getSrcValue(),
5756                           ST->getSrcValueOffset(), ST->isVolatile(),
5757                           ST->isNonTemporal(), OrigAlign);
5758   }
5759
5760   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5761   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5762     // NOTE: If the original store is volatile, this transform must not increase
5763     // the number of stores.  For example, on x86-32 an f64 can be stored in one
5764     // processor operation but an i64 (which is not legal) requires two.  So the
5765     // transform should not be done in this case.
5766     if (Value.getOpcode() != ISD::TargetConstantFP) {
5767       SDValue Tmp;
5768       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5769       default: llvm_unreachable("Unknown FP type");
5770       case MVT::f80:    // We don't do this for these yet.
5771       case MVT::f128:
5772       case MVT::ppcf128:
5773         break;
5774       case MVT::f32:
5775         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5776             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5777           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5778                               bitcastToAPInt().getZExtValue(), MVT::i32);
5779           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5780                               Ptr, ST->getSrcValue(),
5781                               ST->getSrcValueOffset(), ST->isVolatile(),
5782                               ST->isNonTemporal(), ST->getAlignment());
5783         }
5784         break;
5785       case MVT::f64:
5786         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5787              !ST->isVolatile()) ||
5788             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5789           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5790                                 getZExtValue(), MVT::i64);
5791           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5792                               Ptr, ST->getSrcValue(),
5793                               ST->getSrcValueOffset(), ST->isVolatile(),
5794                               ST->isNonTemporal(), ST->getAlignment());
5795         } else if (!ST->isVolatile() &&
5796                    TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5797           // Many FP stores are not made apparent until after legalize, e.g. for
5798           // argument passing.  Since this is so common, custom legalize the
5799           // 64-bit integer store into two 32-bit stores.
5800           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5801           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5802           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5803           if (TLI.isBigEndian()) std::swap(Lo, Hi);
5804
5805           int SVOffset = ST->getSrcValueOffset();
5806           unsigned Alignment = ST->getAlignment();
5807           bool isVolatile = ST->isVolatile();
5808           bool isNonTemporal = ST->isNonTemporal();
5809
5810           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5811                                      Ptr, ST->getSrcValue(),
5812                                      ST->getSrcValueOffset(),
5813                                      isVolatile, isNonTemporal,
5814                                      ST->getAlignment());
5815           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5816                             DAG.getConstant(4, Ptr.getValueType()));
5817           SVOffset += 4;
5818           Alignment = MinAlign(Alignment, 4U);
5819           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5820                                      Ptr, ST->getSrcValue(),
5821                                      SVOffset, isVolatile, isNonTemporal,
5822                                      Alignment);
5823           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5824                              St0, St1);
5825         }
5826
5827         break;
5828       }
5829     }
5830   }
5831
5832   // Try to infer better alignment information than the store already has.
5833   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5834     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5835       if (Align > ST->getAlignment())
5836         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5837                                  Ptr, ST->getSrcValue(),
5838                                  ST->getSrcValueOffset(), ST->getMemoryVT(),
5839                                  ST->isVolatile(), ST->isNonTemporal(), Align);
5840     }
5841   }
5842
5843   if (CombinerAA) {
5844     // Walk up chain skipping non-aliasing memory nodes.
5845     SDValue BetterChain = FindBetterChain(N, Chain);
5846
5847     // If there is a better chain.
5848     if (Chain != BetterChain) {
5849       SDValue ReplStore;
5850
5851       // Replace the chain to avoid dependency.
5852       if (ST->isTruncatingStore()) {
5853         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5854                                       ST->getSrcValue(),ST->getSrcValueOffset(),
5855                                       ST->getMemoryVT(), ST->isVolatile(),
5856                                       ST->isNonTemporal(), ST->getAlignment());
5857       } else {
5858         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5859                                  ST->getSrcValue(), ST->getSrcValueOffset(),
5860                                  ST->isVolatile(), ST->isNonTemporal(),
5861                                  ST->getAlignment());
5862       }
5863
5864       // Create token to keep both nodes around.
5865       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5866                                   MVT::Other, Chain, ReplStore);
5867
5868       // Make sure the new and old chains are cleaned up.
5869       AddToWorkList(Token.getNode());
5870
5871       // Don't add users to work list.
5872       return CombineTo(N, Token, false);
5873     }
5874   }
5875
5876   // Try transforming N to an indexed store.
5877   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5878     return SDValue(N, 0);
5879
5880   // FIXME: is there such a thing as a truncating indexed store?
5881   if (ST->isTruncatingStore() && ST->isUnindexed() &&
5882       Value.getValueType().isInteger()) {
5883     // See if we can simplify the input to this truncstore with knowledge that
5884     // only the low bits are being used.  For example:
5885     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
5886     SDValue Shorter =
5887       GetDemandedBits(Value,
5888                       APInt::getLowBitsSet(Value.getValueSizeInBits(),
5889                                            ST->getMemoryVT().getSizeInBits()));
5890     AddToWorkList(Value.getNode());
5891     if (Shorter.getNode())
5892       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5893                                Ptr, ST->getSrcValue(),
5894                                ST->getSrcValueOffset(), ST->getMemoryVT(),
5895                                ST->isVolatile(), ST->isNonTemporal(),
5896                                ST->getAlignment());
5897
5898     // Otherwise, see if we can simplify the operation with
5899     // SimplifyDemandedBits, which only works if the value has a single use.
5900     if (SimplifyDemandedBits(Value,
5901                              APInt::getLowBitsSet(
5902                                Value.getValueType().getScalarType().getSizeInBits(),
5903                                ST->getMemoryVT().getScalarType().getSizeInBits())))
5904       return SDValue(N, 0);
5905   }
5906
5907   // If this is a load followed by a store to the same location, then the store
5908   // is dead/noop.
5909   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5910     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5911         ST->isUnindexed() && !ST->isVolatile() &&
5912         // There can't be any side effects between the load and store, such as
5913         // a call or store.
5914         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5915       // The store is dead, remove it.
5916       return Chain;
5917     }
5918   }
5919
5920   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5921   // truncating store.  We can do this even if this is already a truncstore.
5922   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5923       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5924       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5925                             ST->getMemoryVT())) {
5926     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5927                              Ptr, ST->getSrcValue(),
5928                              ST->getSrcValueOffset(), ST->getMemoryVT(),
5929                              ST->isVolatile(), ST->isNonTemporal(),
5930                              ST->getAlignment());
5931   }
5932
5933   return ReduceLoadOpStoreWidth(N);
5934 }
5935
5936 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5937   SDValue InVec = N->getOperand(0);
5938   SDValue InVal = N->getOperand(1);
5939   SDValue EltNo = N->getOperand(2);
5940
5941   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5942   // vector with the inserted element.
5943   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5944     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5945     SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5946                                 InVec.getNode()->op_end());
5947     if (Elt < Ops.size())
5948       Ops[Elt] = InVal;
5949     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5950                        InVec.getValueType(), &Ops[0], Ops.size());
5951   }
5952   // If the invec is an UNDEF and if EltNo is a constant, create a new 
5953   // BUILD_VECTOR with undef elements and the inserted element.
5954   if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF && 
5955       isa<ConstantSDNode>(EltNo)) {
5956     EVT VT = InVec.getValueType();
5957     EVT EltVT = VT.getVectorElementType();
5958     unsigned NElts = VT.getVectorNumElements();
5959     SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5960
5961     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5962     if (Elt < Ops.size())
5963       Ops[Elt] = InVal;
5964     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5965                        InVec.getValueType(), &Ops[0], Ops.size());
5966   }
5967   return SDValue();
5968 }
5969
5970 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5971   // (vextract (scalar_to_vector val, 0) -> val
5972   SDValue InVec = N->getOperand(0);
5973
5974  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5975    // Check if the result type doesn't match the inserted element type. A
5976    // SCALAR_TO_VECTOR may truncate the inserted element and the
5977    // EXTRACT_VECTOR_ELT may widen the extracted vector.
5978    EVT EltVT = InVec.getValueType().getVectorElementType();
5979    SDValue InOp = InVec.getOperand(0);
5980    EVT NVT = N->getValueType(0);
5981    if (InOp.getValueType() != NVT) {
5982      assert(InOp.getValueType().isInteger() && NVT.isInteger());
5983      return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
5984    }
5985    return InOp;
5986  }
5987
5988   // Perform only after legalization to ensure build_vector / vector_shuffle
5989   // optimizations have already been done.
5990   if (!LegalOperations) return SDValue();
5991
5992   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5993   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5994   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5995   SDValue EltNo = N->getOperand(1);
5996
5997   if (isa<ConstantSDNode>(EltNo)) {
5998     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5999     bool NewLoad = false;
6000     bool BCNumEltsChanged = false;
6001     EVT VT = InVec.getValueType();
6002     EVT ExtVT = VT.getVectorElementType();
6003     EVT LVT = ExtVT;
6004
6005     if (InVec.getOpcode() == ISD::BIT_CONVERT) {
6006       EVT BCVT = InVec.getOperand(0).getValueType();
6007       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6008         return SDValue();
6009       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6010         BCNumEltsChanged = true;
6011       InVec = InVec.getOperand(0);
6012       ExtVT = BCVT.getVectorElementType();
6013       NewLoad = true;
6014     }
6015
6016     LoadSDNode *LN0 = NULL;
6017     const ShuffleVectorSDNode *SVN = NULL;
6018     if (ISD::isNormalLoad(InVec.getNode())) {
6019       LN0 = cast<LoadSDNode>(InVec);
6020     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6021                InVec.getOperand(0).getValueType() == ExtVT &&
6022                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6023       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6024     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6025       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6026       // =>
6027       // (load $addr+1*size)
6028
6029       // If the bit convert changed the number of elements, it is unsafe
6030       // to examine the mask.
6031       if (BCNumEltsChanged)
6032         return SDValue();
6033
6034       // Select the input vector, guarding against out of range extract vector.
6035       unsigned NumElems = VT.getVectorNumElements();
6036       int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
6037       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6038
6039       if (InVec.getOpcode() == ISD::BIT_CONVERT)
6040         InVec = InVec.getOperand(0);
6041       if (ISD::isNormalLoad(InVec.getNode())) {
6042         LN0 = cast<LoadSDNode>(InVec);
6043         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6044       }
6045     }
6046
6047     if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6048       return SDValue();
6049
6050     unsigned Align = LN0->getAlignment();
6051     if (NewLoad) {
6052       // Check the resultant load doesn't need a higher alignment than the
6053       // original load.
6054       unsigned NewAlign =
6055         TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6056
6057       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6058         return SDValue();
6059
6060       Align = NewAlign;
6061     }
6062
6063     SDValue NewPtr = LN0->getBasePtr();
6064     if (Elt) {
6065       unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
6066       EVT PtrType = NewPtr.getValueType();
6067       if (TLI.isBigEndian())
6068         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6069       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6070                            DAG.getConstant(PtrOff, PtrType));
6071     }
6072
6073     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6074                        LN0->getSrcValue(), LN0->getSrcValueOffset(),
6075                        LN0->isVolatile(), LN0->isNonTemporal(), Align);
6076   }
6077
6078   return SDValue();
6079 }
6080
6081 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6082   unsigned NumInScalars = N->getNumOperands();
6083   EVT VT = N->getValueType(0);
6084
6085   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6086   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6087   // at most two distinct vectors, turn this into a shuffle node.
6088   SDValue VecIn1, VecIn2;
6089   for (unsigned i = 0; i != NumInScalars; ++i) {
6090     // Ignore undef inputs.
6091     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6092
6093     // If this input is something other than a EXTRACT_VECTOR_ELT with a
6094     // constant index, bail out.
6095     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6096         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6097       VecIn1 = VecIn2 = SDValue(0, 0);
6098       break;
6099     }
6100
6101     // If the input vector type disagrees with the result of the build_vector,
6102     // we can't make a shuffle.
6103     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6104     if (ExtractedFromVec.getValueType() != VT) {
6105       VecIn1 = VecIn2 = SDValue(0, 0);
6106       break;
6107     }
6108
6109     // Otherwise, remember this.  We allow up to two distinct input vectors.
6110     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6111       continue;
6112
6113     if (VecIn1.getNode() == 0) {
6114       VecIn1 = ExtractedFromVec;
6115     } else if (VecIn2.getNode() == 0) {
6116       VecIn2 = ExtractedFromVec;
6117     } else {
6118       // Too many inputs.
6119       VecIn1 = VecIn2 = SDValue(0, 0);
6120       break;
6121     }
6122   }
6123
6124   // If everything is good, we can make a shuffle operation.
6125   if (VecIn1.getNode()) {
6126     SmallVector<int, 8> Mask;
6127     for (unsigned i = 0; i != NumInScalars; ++i) {
6128       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6129         Mask.push_back(-1);
6130         continue;
6131       }
6132
6133       // If extracting from the first vector, just use the index directly.
6134       SDValue Extract = N->getOperand(i);
6135       SDValue ExtVal = Extract.getOperand(1);
6136       if (Extract.getOperand(0) == VecIn1) {
6137         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6138         if (ExtIndex > VT.getVectorNumElements())
6139           return SDValue();
6140         
6141         Mask.push_back(ExtIndex);
6142         continue;
6143       }
6144
6145       // Otherwise, use InIdx + VecSize
6146       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6147       Mask.push_back(Idx+NumInScalars);
6148     }
6149
6150     // Add count and size info.
6151     if (!isTypeLegal(VT))
6152       return SDValue();
6153
6154     // Return the new VECTOR_SHUFFLE node.
6155     SDValue Ops[2];
6156     Ops[0] = VecIn1;
6157     Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6158     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6159   }
6160
6161   return SDValue();
6162 }
6163
6164 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6165   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6166   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
6167   // inputs come from at most two distinct vectors, turn this into a shuffle
6168   // node.
6169
6170   // If we only have one input vector, we don't need to do any concatenation.
6171   if (N->getNumOperands() == 1)
6172     return N->getOperand(0);
6173
6174   return SDValue();
6175 }
6176
6177 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6178   return SDValue();
6179   
6180   EVT VT = N->getValueType(0);
6181   unsigned NumElts = VT.getVectorNumElements();
6182
6183   SDValue N0 = N->getOperand(0);
6184
6185   assert(N0.getValueType().getVectorNumElements() == NumElts &&
6186         "Vector shuffle must be normalized in DAG");
6187
6188   // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6189
6190   // If it is a splat, check if the argument vector is a build_vector with
6191   // all scalar elements the same.
6192   if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
6193     SDNode *V = N0.getNode();
6194     
6195
6196     // If this is a bit convert that changes the element type of the vector but
6197     // not the number of vector elements, look through it.  Be careful not to
6198     // look though conversions that change things like v4f32 to v2f64.
6199     if (V->getOpcode() == ISD::BIT_CONVERT) {
6200       SDValue ConvInput = V->getOperand(0);
6201       if (ConvInput.getValueType().isVector() &&
6202           ConvInput.getValueType().getVectorNumElements() == NumElts)
6203         V = ConvInput.getNode();
6204     }
6205
6206     if (V->getOpcode() == ISD::BUILD_VECTOR) {
6207       unsigned NumElems = V->getNumOperands();
6208       unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
6209       if (NumElems > BaseIdx) {
6210         SDValue Base;
6211         bool AllSame = true;
6212         for (unsigned i = 0; i != NumElems; ++i) {
6213           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6214             Base = V->getOperand(i);
6215             break;
6216           }
6217         }
6218         // Splat of <u, u, u, u>, return <u, u, u, u>
6219         if (!Base.getNode())
6220           return N0;
6221         for (unsigned i = 0; i != NumElems; ++i) {
6222           if (V->getOperand(i) != Base) {
6223             AllSame = false;
6224             break;
6225           }
6226         }
6227         // Splat of <x, x, x, x>, return <x, x, x, x>
6228         if (AllSame)
6229           return N0;
6230       }
6231     }
6232   }
6233   return SDValue();
6234 }
6235
6236 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6237 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6238 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6239 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
6240 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6241   EVT VT = N->getValueType(0);
6242   DebugLoc dl = N->getDebugLoc();
6243   SDValue LHS = N->getOperand(0);
6244   SDValue RHS = N->getOperand(1);
6245   if (N->getOpcode() == ISD::AND) {
6246     if (RHS.getOpcode() == ISD::BIT_CONVERT)
6247       RHS = RHS.getOperand(0);
6248     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6249       SmallVector<int, 8> Indices;
6250       unsigned NumElts = RHS.getNumOperands();
6251       for (unsigned i = 0; i != NumElts; ++i) {
6252         SDValue Elt = RHS.getOperand(i);
6253         if (!isa<ConstantSDNode>(Elt))
6254           return SDValue();
6255         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6256           Indices.push_back(i);
6257         else if (cast<ConstantSDNode>(Elt)->isNullValue())
6258           Indices.push_back(NumElts);
6259         else
6260           return SDValue();
6261       }
6262
6263       // Let's see if the target supports this vector_shuffle.
6264       EVT RVT = RHS.getValueType();
6265       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6266         return SDValue();
6267
6268       // Return the new VECTOR_SHUFFLE node.
6269       EVT EltVT = RVT.getVectorElementType();
6270       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6271                                      DAG.getConstant(0, EltVT));
6272       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6273                                  RVT, &ZeroOps[0], ZeroOps.size());
6274       LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6275       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6276       return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6277     }
6278   }
6279
6280   return SDValue();
6281 }
6282
6283 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6284 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6285   // After legalize, the target may be depending on adds and other
6286   // binary ops to provide legal ways to construct constants or other
6287   // things. Simplifying them may result in a loss of legality.
6288   if (LegalOperations) return SDValue();
6289
6290   EVT VT = N->getValueType(0);
6291   assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6292
6293   EVT EltType = VT.getVectorElementType();
6294   SDValue LHS = N->getOperand(0);
6295   SDValue RHS = N->getOperand(1);
6296   SDValue Shuffle = XformToShuffleWithZero(N);
6297   if (Shuffle.getNode()) return Shuffle;
6298
6299   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6300   // this operation.
6301   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6302       RHS.getOpcode() == ISD::BUILD_VECTOR) {
6303     SmallVector<SDValue, 8> Ops;
6304     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6305       SDValue LHSOp = LHS.getOperand(i);
6306       SDValue RHSOp = RHS.getOperand(i);
6307       // If these two elements can't be folded, bail out.
6308       if ((LHSOp.getOpcode() != ISD::UNDEF &&
6309            LHSOp.getOpcode() != ISD::Constant &&
6310            LHSOp.getOpcode() != ISD::ConstantFP) ||
6311           (RHSOp.getOpcode() != ISD::UNDEF &&
6312            RHSOp.getOpcode() != ISD::Constant &&
6313            RHSOp.getOpcode() != ISD::ConstantFP))
6314         break;
6315
6316       // Can't fold divide by zero.
6317       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6318           N->getOpcode() == ISD::FDIV) {
6319         if ((RHSOp.getOpcode() == ISD::Constant &&
6320              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6321             (RHSOp.getOpcode() == ISD::ConstantFP &&
6322              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6323           break;
6324       }
6325
6326       Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
6327                                 EltType, LHSOp, RHSOp));
6328       AddToWorkList(Ops.back().getNode());
6329       assert((Ops.back().getOpcode() == ISD::UNDEF ||
6330               Ops.back().getOpcode() == ISD::Constant ||
6331               Ops.back().getOpcode() == ISD::ConstantFP) &&
6332              "Scalar binop didn't fold!");
6333     }
6334
6335     if (Ops.size() == LHS.getNumOperands()) {
6336       EVT VT = LHS.getValueType();
6337       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6338                          &Ops[0], Ops.size());
6339     }
6340   }
6341
6342   return SDValue();
6343 }
6344
6345 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6346                                     SDValue N1, SDValue N2){
6347   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6348
6349   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6350                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
6351
6352   // If we got a simplified select_cc node back from SimplifySelectCC, then
6353   // break it down into a new SETCC node, and a new SELECT node, and then return
6354   // the SELECT node, since we were called with a SELECT node.
6355   if (SCC.getNode()) {
6356     // Check to see if we got a select_cc back (to turn into setcc/select).
6357     // Otherwise, just return whatever node we got back, like fabs.
6358     if (SCC.getOpcode() == ISD::SELECT_CC) {
6359       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6360                                   N0.getValueType(),
6361                                   SCC.getOperand(0), SCC.getOperand(1),
6362                                   SCC.getOperand(4));
6363       AddToWorkList(SETCC.getNode());
6364       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6365                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
6366     }
6367
6368     return SCC;
6369   }
6370   return SDValue();
6371 }
6372
6373 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6374 /// are the two values being selected between, see if we can simplify the
6375 /// select.  Callers of this should assume that TheSelect is deleted if this
6376 /// returns true.  As such, they should return the appropriate thing (e.g. the
6377 /// node) back to the top-level of the DAG combiner loop to avoid it being
6378 /// looked at.
6379 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6380                                     SDValue RHS) {
6381
6382   // If this is a select from two identical things, try to pull the operation
6383   // through the select.
6384   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
6385     // If this is a load and the token chain is identical, replace the select
6386     // of two loads with a load through a select of the address to load from.
6387     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6388     // constants have been dropped into the constant pool.
6389     if (LHS.getOpcode() == ISD::LOAD &&
6390         // Do not let this transformation reduce the number of volatile loads.
6391         !cast<LoadSDNode>(LHS)->isVolatile() &&
6392         !cast<LoadSDNode>(RHS)->isVolatile() &&
6393         // Token chains must be identical.
6394         LHS.getOperand(0) == RHS.getOperand(0)) {
6395       LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6396       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6397
6398       // If this is an EXTLOAD, the VT's must match.
6399       if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
6400         // FIXME: this discards src value information.  This is
6401         // over-conservative. It would be beneficial to be able to remember
6402         // both potential memory locations.  Since we are discarding
6403         // src value info, don't do the transformation if the memory
6404         // locations are not in the default address space.
6405         unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
6406         if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
6407           if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
6408             LLDAddrSpace = PT->getAddressSpace();
6409         }
6410         if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
6411           if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
6412             RLDAddrSpace = PT->getAddressSpace();
6413         }
6414         SDValue Addr;
6415         if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
6416           if (TheSelect->getOpcode() == ISD::SELECT) {
6417             // Check that the condition doesn't reach either load.  If so, folding
6418             // this will induce a cycle into the DAG.
6419             if ((!LLD->hasAnyUseOfValue(1) ||
6420                  !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
6421                 (!RLD->hasAnyUseOfValue(1) ||
6422                  !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
6423               Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6424                                  LLD->getBasePtr().getValueType(),
6425                                  TheSelect->getOperand(0), LLD->getBasePtr(),
6426                                  RLD->getBasePtr());
6427             }
6428           } else {
6429             // Check that the condition doesn't reach either load.  If so, folding
6430             // this will induce a cycle into the DAG.
6431             if ((!LLD->hasAnyUseOfValue(1) ||
6432                  (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6433                   !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
6434                 (!RLD->hasAnyUseOfValue(1) ||
6435                  (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6436                   !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
6437               Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6438                                  LLD->getBasePtr().getValueType(),
6439                                  TheSelect->getOperand(0),
6440                                  TheSelect->getOperand(1),
6441                                  LLD->getBasePtr(), RLD->getBasePtr(),
6442                                  TheSelect->getOperand(4));
6443             }
6444           }
6445         }
6446
6447         if (Addr.getNode()) {
6448           SDValue Load;
6449           if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6450             Load = DAG.getLoad(TheSelect->getValueType(0),
6451                                TheSelect->getDebugLoc(),
6452                                LLD->getChain(),
6453                                Addr, 0, 0,
6454                                LLD->isVolatile(),
6455                                LLD->isNonTemporal(),
6456                                LLD->getAlignment());
6457           } else {
6458             Load = DAG.getExtLoad(LLD->getExtensionType(),
6459                                   TheSelect->getDebugLoc(),
6460                                   TheSelect->getValueType(0),
6461                                   LLD->getChain(), Addr, 0, 0,
6462                                   LLD->getMemoryVT(),
6463                                   LLD->isVolatile(),
6464                                   LLD->isNonTemporal(),
6465                                   LLD->getAlignment());
6466           }
6467
6468           // Users of the select now use the result of the load.
6469           CombineTo(TheSelect, Load);
6470
6471           // Users of the old loads now use the new load's chain.  We know the
6472           // old-load value is dead now.
6473           CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6474           CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6475           return true;
6476         }
6477       }
6478     }
6479   }
6480
6481   return false;
6482 }
6483
6484 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6485 /// where 'cond' is the comparison specified by CC.
6486 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6487                                       SDValue N2, SDValue N3,
6488                                       ISD::CondCode CC, bool NotExtCompare) {
6489   // (x ? y : y) -> y.
6490   if (N2 == N3) return N2;
6491   
6492   EVT VT = N2.getValueType();
6493   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6494   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6495   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6496
6497   // Determine if the condition we're dealing with is constant
6498   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6499                               N0, N1, CC, DL, false);
6500   if (SCC.getNode()) AddToWorkList(SCC.getNode());
6501   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6502
6503   // fold select_cc true, x, y -> x
6504   if (SCCC && !SCCC->isNullValue())
6505     return N2;
6506   // fold select_cc false, x, y -> y
6507   if (SCCC && SCCC->isNullValue())
6508     return N3;
6509
6510   // Check to see if we can simplify the select into an fabs node
6511   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6512     // Allow either -0.0 or 0.0
6513     if (CFP->getValueAPF().isZero()) {
6514       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6515       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6516           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6517           N2 == N3.getOperand(0))
6518         return DAG.getNode(ISD::FABS, DL, VT, N0);
6519
6520       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6521       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6522           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6523           N2.getOperand(0) == N3)
6524         return DAG.getNode(ISD::FABS, DL, VT, N3);
6525     }
6526   }
6527   
6528   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6529   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6530   // in it.  This is a win when the constant is not otherwise available because
6531   // it replaces two constant pool loads with one.  We only do this if the FP
6532   // type is known to be legal, because if it isn't, then we are before legalize
6533   // types an we want the other legalization to happen first (e.g. to avoid
6534   // messing with soft float) and if the ConstantFP is not legal, because if
6535   // it is legal, we may not need to store the FP constant in a constant pool.
6536   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6537     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6538       if (TLI.isTypeLegal(N2.getValueType()) &&
6539           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6540            TargetLowering::Legal) &&
6541           // If both constants have multiple uses, then we won't need to do an
6542           // extra load, they are likely around in registers for other users.
6543           (TV->hasOneUse() || FV->hasOneUse())) {
6544         Constant *Elts[] = {
6545           const_cast<ConstantFP*>(FV->getConstantFPValue()),
6546           const_cast<ConstantFP*>(TV->getConstantFPValue())
6547         };
6548         const Type *FPTy = Elts[0]->getType();
6549         const TargetData &TD = *TLI.getTargetData();
6550         
6551         // Create a ConstantArray of the two constants.
6552         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6553         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6554                                             TD.getPrefTypeAlignment(FPTy));
6555         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6556
6557         // Get the offsets to the 0 and 1 element of the array so that we can
6558         // select between them.
6559         SDValue Zero = DAG.getIntPtrConstant(0);
6560         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6561         SDValue One = DAG.getIntPtrConstant(EltSize);
6562         
6563         SDValue Cond = DAG.getSetCC(DL,
6564                                     TLI.getSetCCResultType(N0.getValueType()),
6565                                     N0, N1, CC);
6566         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6567                                         Cond, One, Zero);
6568         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6569                             CstOffset);
6570         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6571                            PseudoSourceValue::getConstantPool(), 0, false,
6572                            false, Alignment);
6573
6574       }
6575     }  
6576
6577   // Check to see if we can perform the "gzip trick", transforming
6578   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6579   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6580       N0.getValueType().isInteger() &&
6581       N2.getValueType().isInteger() &&
6582       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
6583        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
6584     EVT XType = N0.getValueType();
6585     EVT AType = N2.getValueType();
6586     if (XType.bitsGE(AType)) {
6587       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6588       // single-bit constant.
6589       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6590         unsigned ShCtV = N2C->getAPIntValue().logBase2();
6591         ShCtV = XType.getSizeInBits()-ShCtV-1;
6592         SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6593         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6594                                     XType, N0, ShCt);
6595         AddToWorkList(Shift.getNode());
6596
6597         if (XType.bitsGT(AType)) {
6598           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6599           AddToWorkList(Shift.getNode());
6600         }
6601
6602         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6603       }
6604
6605       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6606                                   XType, N0,
6607                                   DAG.getConstant(XType.getSizeInBits()-1,
6608                                                   getShiftAmountTy()));
6609       AddToWorkList(Shift.getNode());
6610
6611       if (XType.bitsGT(AType)) {
6612         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6613         AddToWorkList(Shift.getNode());
6614       }
6615
6616       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6617     }
6618   }
6619
6620   // fold select C, 16, 0 -> shl C, 4
6621   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6622       TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6623
6624     // If the caller doesn't want us to simplify this into a zext of a compare,
6625     // don't do it.
6626     if (NotExtCompare && N2C->getAPIntValue() == 1)
6627       return SDValue();
6628
6629     // Get a SetCC of the condition
6630     // FIXME: Should probably make sure that setcc is legal if we ever have a
6631     // target where it isn't.
6632     SDValue Temp, SCC;
6633     // cast from setcc result type to select result type
6634     if (LegalTypes) {
6635       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6636                           N0, N1, CC);
6637       if (N2.getValueType().bitsLT(SCC.getValueType()))
6638         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6639       else
6640         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6641                            N2.getValueType(), SCC);
6642     } else {
6643       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6644       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6645                          N2.getValueType(), SCC);
6646     }
6647
6648     AddToWorkList(SCC.getNode());
6649     AddToWorkList(Temp.getNode());
6650
6651     if (N2C->getAPIntValue() == 1)
6652       return Temp;
6653
6654     // shl setcc result by log2 n2c
6655     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6656                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
6657                                        getShiftAmountTy()));
6658   }
6659
6660   // Check to see if this is the equivalent of setcc
6661   // FIXME: Turn all of these into setcc if setcc if setcc is legal
6662   // otherwise, go ahead with the folds.
6663   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6664     EVT XType = N0.getValueType();
6665     if (!LegalOperations ||
6666         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6667       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6668       if (Res.getValueType() != VT)
6669         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6670       return Res;
6671     }
6672
6673     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6674     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6675         (!LegalOperations ||
6676          TLI.isOperationLegal(ISD::CTLZ, XType))) {
6677       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6678       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6679                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
6680                                          getShiftAmountTy()));
6681     }
6682     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6683     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6684       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6685                                   XType, DAG.getConstant(0, XType), N0);
6686       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6687       return DAG.getNode(ISD::SRL, DL, XType,
6688                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6689                          DAG.getConstant(XType.getSizeInBits()-1,
6690                                          getShiftAmountTy()));
6691     }
6692     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6693     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6694       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6695                                  DAG.getConstant(XType.getSizeInBits()-1,
6696                                                  getShiftAmountTy()));
6697       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6698     }
6699   }
6700
6701   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6702   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6703   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6704       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6705       N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6706     EVT XType = N0.getValueType();
6707     SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6708                                 DAG.getConstant(XType.getSizeInBits()-1,
6709                                                 getShiftAmountTy()));
6710     SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6711                               N0, Shift);
6712     AddToWorkList(Shift.getNode());
6713     AddToWorkList(Add.getNode());
6714     return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6715   }
6716   // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6717   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6718   if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6719       N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6720     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6721       EVT XType = N0.getValueType();
6722       if (SubC->isNullValue() && XType.isInteger()) {
6723         SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6724                                     N0,
6725                                     DAG.getConstant(XType.getSizeInBits()-1,
6726                                                     getShiftAmountTy()));
6727         SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6728                                   XType, N0, Shift);
6729         AddToWorkList(Shift.getNode());
6730         AddToWorkList(Add.getNode());
6731         return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6732       }
6733     }
6734   }
6735
6736   return SDValue();
6737 }
6738
6739 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6740 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6741                                    SDValue N1, ISD::CondCode Cond,
6742                                    DebugLoc DL, bool foldBooleans) {
6743   TargetLowering::DAGCombinerInfo
6744     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6745   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6746 }
6747
6748 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6749 /// return a DAG expression to select that will generate the same value by
6750 /// multiplying by a magic number.  See:
6751 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6752 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6753   std::vector<SDNode*> Built;
6754   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6755
6756   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6757        ii != ee; ++ii)
6758     AddToWorkList(*ii);
6759   return S;
6760 }
6761
6762 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6763 /// return a DAG expression to select that will generate the same value by
6764 /// multiplying by a magic number.  See:
6765 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6766 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6767   std::vector<SDNode*> Built;
6768   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6769
6770   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6771        ii != ee; ++ii)
6772     AddToWorkList(*ii);
6773   return S;
6774 }
6775
6776 /// FindBaseOffset - Return true if base is a frame index, which is known not
6777 // to alias with anything but itself.  Provides base object and offset as results.
6778 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6779                            const GlobalValue *&GV, void *&CV) {
6780   // Assume it is a primitive operation.
6781   Base = Ptr; Offset = 0; GV = 0; CV = 0;
6782
6783   // If it's an adding a simple constant then integrate the offset.
6784   if (Base.getOpcode() == ISD::ADD) {
6785     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6786       Base = Base.getOperand(0);
6787       Offset += C->getZExtValue();
6788     }
6789   }
6790   
6791   // Return the underlying GlobalValue, and update the Offset.  Return false
6792   // for GlobalAddressSDNode since the same GlobalAddress may be represented
6793   // by multiple nodes with different offsets.
6794   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6795     GV = G->getGlobal();
6796     Offset += G->getOffset();
6797     return false;
6798   }
6799
6800   // Return the underlying Constant value, and update the Offset.  Return false
6801   // for ConstantSDNodes since the same constant pool entry may be represented
6802   // by multiple nodes with different offsets.
6803   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6804     CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6805                                          : (void *)C->getConstVal();
6806     Offset += C->getOffset();
6807     return false;
6808   }
6809   // If it's any of the following then it can't alias with anything but itself.
6810   return isa<FrameIndexSDNode>(Base);
6811 }
6812
6813 /// isAlias - Return true if there is any possibility that the two addresses
6814 /// overlap.
6815 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6816                           const Value *SrcValue1, int SrcValueOffset1,
6817                           unsigned SrcValueAlign1,
6818                           SDValue Ptr2, int64_t Size2,
6819                           const Value *SrcValue2, int SrcValueOffset2,
6820                           unsigned SrcValueAlign2) const {
6821   // If they are the same then they must be aliases.
6822   if (Ptr1 == Ptr2) return true;
6823
6824   // Gather base node and offset information.
6825   SDValue Base1, Base2;
6826   int64_t Offset1, Offset2;
6827   const GlobalValue *GV1, *GV2;
6828   void *CV1, *CV2;
6829   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6830   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6831
6832   // If they have a same base address then check to see if they overlap.
6833   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6834     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6835
6836   // If we know what the bases are, and they aren't identical, then we know they
6837   // cannot alias.
6838   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6839     return false;
6840
6841   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6842   // compared to the size and offset of the access, we may be able to prove they
6843   // do not alias.  This check is conservative for now to catch cases created by
6844   // splitting vector types.
6845   if ((SrcValueAlign1 == SrcValueAlign2) &&
6846       (SrcValueOffset1 != SrcValueOffset2) &&
6847       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6848     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6849     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6850     
6851     // There is no overlap between these relatively aligned accesses of similar
6852     // size, return no alias.
6853     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6854       return false;
6855   }
6856   
6857   if (CombinerGlobalAA) {
6858     // Use alias analysis information.
6859     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6860     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6861     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6862     AliasAnalysis::AliasResult AAResult =
6863                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6864     if (AAResult == AliasAnalysis::NoAlias)
6865       return false;
6866   }
6867
6868   // Otherwise we have to assume they alias.
6869   return true;
6870 }
6871
6872 /// FindAliasInfo - Extracts the relevant alias information from the memory
6873 /// node.  Returns true if the operand was a load.
6874 bool DAGCombiner::FindAliasInfo(SDNode *N,
6875                         SDValue &Ptr, int64_t &Size,
6876                         const Value *&SrcValue, 
6877                         int &SrcValueOffset,
6878                         unsigned &SrcValueAlign) const {
6879   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6880     Ptr = LD->getBasePtr();
6881     Size = LD->getMemoryVT().getSizeInBits() >> 3;
6882     SrcValue = LD->getSrcValue();
6883     SrcValueOffset = LD->getSrcValueOffset();
6884     SrcValueAlign = LD->getOriginalAlignment();
6885     return true;
6886   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6887     Ptr = ST->getBasePtr();
6888     Size = ST->getMemoryVT().getSizeInBits() >> 3;
6889     SrcValue = ST->getSrcValue();
6890     SrcValueOffset = ST->getSrcValueOffset();
6891     SrcValueAlign = ST->getOriginalAlignment();
6892   } else {
6893     llvm_unreachable("FindAliasInfo expected a memory operand");
6894   }
6895
6896   return false;
6897 }
6898
6899 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6900 /// looking for aliasing nodes and adding them to the Aliases vector.
6901 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6902                                    SmallVector<SDValue, 8> &Aliases) {
6903   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
6904   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
6905
6906   // Get alias information for node.
6907   SDValue Ptr;
6908   int64_t Size;
6909   const Value *SrcValue;
6910   int SrcValueOffset;
6911   unsigned SrcValueAlign;
6912   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset, 
6913                               SrcValueAlign);
6914
6915   // Starting off.
6916   Chains.push_back(OriginalChain);
6917   unsigned Depth = 0;
6918   
6919   // Look at each chain and determine if it is an alias.  If so, add it to the
6920   // aliases list.  If not, then continue up the chain looking for the next
6921   // candidate.
6922   while (!Chains.empty()) {
6923     SDValue Chain = Chains.back();
6924     Chains.pop_back();
6925     
6926     // For TokenFactor nodes, look at each operand and only continue up the 
6927     // chain until we find two aliases.  If we've seen two aliases, assume we'll 
6928     // find more and revert to original chain since the xform is unlikely to be
6929     // profitable.
6930     // 
6931     // FIXME: The depth check could be made to return the last non-aliasing 
6932     // chain we found before we hit a tokenfactor rather than the original
6933     // chain.
6934     if (Depth > 6 || Aliases.size() == 2) {
6935       Aliases.clear();
6936       Aliases.push_back(OriginalChain);
6937       break;
6938     }
6939
6940     // Don't bother if we've been before.
6941     if (!Visited.insert(Chain.getNode()))
6942       continue;
6943
6944     switch (Chain.getOpcode()) {
6945     case ISD::EntryToken:
6946       // Entry token is ideal chain operand, but handled in FindBetterChain.
6947       break;
6948
6949     case ISD::LOAD:
6950     case ISD::STORE: {
6951       // Get alias information for Chain.
6952       SDValue OpPtr;
6953       int64_t OpSize;
6954       const Value *OpSrcValue;
6955       int OpSrcValueOffset;
6956       unsigned OpSrcValueAlign;
6957       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6958                                     OpSrcValue, OpSrcValueOffset,
6959                                     OpSrcValueAlign);
6960
6961       // If chain is alias then stop here.
6962       if (!(IsLoad && IsOpLoad) &&
6963           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6964                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6965                   OpSrcValueAlign)) {
6966         Aliases.push_back(Chain);
6967       } else {
6968         // Look further up the chain.
6969         Chains.push_back(Chain.getOperand(0));
6970         ++Depth;
6971       }
6972       break;
6973     }
6974
6975     case ISD::TokenFactor:
6976       // We have to check each of the operands of the token factor for "small"
6977       // token factors, so we queue them up.  Adding the operands to the queue
6978       // (stack) in reverse order maintains the original order and increases the
6979       // likelihood that getNode will find a matching token factor (CSE.)
6980       if (Chain.getNumOperands() > 16) {
6981         Aliases.push_back(Chain);
6982         break;
6983       }
6984       for (unsigned n = Chain.getNumOperands(); n;)
6985         Chains.push_back(Chain.getOperand(--n));
6986       ++Depth;
6987       break;
6988
6989     default:
6990       // For all other instructions we will just have to take what we can get.
6991       Aliases.push_back(Chain);
6992       break;
6993     }
6994   }
6995 }
6996
6997 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6998 /// for a better chain (aliasing node.)
6999 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7000   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
7001
7002   // Accumulate all the aliases to this node.
7003   GatherAllAliases(N, OldChain, Aliases);
7004
7005   if (Aliases.size() == 0) {
7006     // If no operands then chain to entry token.
7007     return DAG.getEntryNode();
7008   } else if (Aliases.size() == 1) {
7009     // If a single operand then chain to it.  We don't need to revisit it.
7010     return Aliases[0];
7011   }
7012   
7013   // Construct a custom tailored token factor.
7014   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other, 
7015                      &Aliases[0], Aliases.size());
7016 }
7017
7018 // SelectionDAG::Combine - This is the entry point for the file.
7019 //
7020 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7021                            CodeGenOpt::Level OptLevel) {
7022   /// run - This is the main entry point to this class.
7023   ///
7024   DAGCombiner(*this, AA, OptLevel).Run(Level);
7025 }