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