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