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