Prevent assert in CombinerGlobalAA with null values
[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/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NodesCombined   , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
47
48 namespace {
49   static cl::opt<bool>
50     CombinerAA("combiner-alias-analysis", cl::Hidden,
51                cl::desc("Turn on alias analysis during testing"));
52
53   static cl::opt<bool>
54     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
55                cl::desc("Include global information in alias analysis"));
56
57 //------------------------------ DAGCombiner ---------------------------------//
58
59   class DAGCombiner {
60     SelectionDAG &DAG;
61     const TargetLowering &TLI;
62     CombineLevel Level;
63     CodeGenOpt::Level OptLevel;
64     bool LegalOperations;
65     bool LegalTypes;
66
67     // Worklist of all of the nodes that need to be simplified.
68     //
69     // This has the semantics that when adding to the worklist,
70     // the item added must be next to be processed. It should
71     // also only appear once. The naive approach to this takes
72     // linear time.
73     //
74     // To reduce the insert/remove time to logarithmic, we use
75     // a set and a vector to maintain our worklist.
76     //
77     // The set contains the items on the worklist, but does not
78     // maintain the order they should be visited.
79     //
80     // The vector maintains the order nodes should be visited, but may
81     // contain duplicate or removed nodes. When choosing a node to
82     // visit, we pop off the order stack until we find an item that is
83     // also in the contents set. All operations are O(log N).
84     SmallPtrSet<SDNode*, 64> WorkListContents;
85     SmallVector<SDNode*, 64> WorkListOrder;
86
87     // AA - Used for DAG load/store alias analysis.
88     AliasAnalysis &AA;
89
90     /// AddUsersToWorkList - When an instruction is simplified, add all users of
91     /// the instruction to the work lists because they might get more simplified
92     /// now.
93     ///
94     void AddUsersToWorkList(SDNode *N) {
95       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
96            UI != UE; ++UI)
97         AddToWorkList(*UI);
98     }
99
100     /// visit - call the node-specific routine that knows how to fold each
101     /// particular type of node.
102     SDValue visit(SDNode *N);
103
104   public:
105     /// AddToWorkList - Add to the work list making sure its instance is at the
106     /// back (next to be processed.)
107     void AddToWorkList(SDNode *N) {
108       WorkListContents.insert(N);
109       WorkListOrder.push_back(N);
110     }
111
112     /// removeFromWorkList - remove all instances of N from the worklist.
113     ///
114     void removeFromWorkList(SDNode *N) {
115       WorkListContents.erase(N);
116     }
117
118     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
119                       bool AddTo = true);
120
121     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
122       return CombineTo(N, &Res, 1, AddTo);
123     }
124
125     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126                       bool AddTo = true) {
127       SDValue To[] = { Res0, Res1 };
128       return CombineTo(N, To, 2, AddTo);
129     }
130
131     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
132
133   private:
134
135     /// SimplifyDemandedBits - Check the specified integer node value to see if
136     /// it can be simplified or if things it uses can be simplified by bit
137     /// propagation.  If so, return true.
138     bool SimplifyDemandedBits(SDValue Op) {
139       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
140       APInt Demanded = APInt::getAllOnesValue(BitWidth);
141       return SimplifyDemandedBits(Op, Demanded);
142     }
143
144     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145
146     bool CombineToPreIndexedLoadStore(SDNode *N);
147     bool CombineToPostIndexedLoadStore(SDNode *N);
148
149     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
150     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
151     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
153     SDValue PromoteIntBinOp(SDValue Op);
154     SDValue PromoteIntShiftOp(SDValue Op);
155     SDValue PromoteExtend(SDValue Op);
156     bool PromoteLoad(SDValue Op);
157
158     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
159                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
160                          ISD::NodeType ExtType);
161
162     /// combine - call the node-specific routine that knows how to fold each
163     /// particular type of node. If that doesn't do anything, try the
164     /// target-specific DAG combines.
165     SDValue combine(SDNode *N);
166
167     // Visitation implementation - Implement dag node combining for different
168     // node types.  The semantics are as follows:
169     // Return Value:
170     //   SDValue.getNode() == 0 - No change was made
171     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
172     //   otherwise              - N should be replaced by the returned Operand.
173     //
174     SDValue visitTokenFactor(SDNode *N);
175     SDValue visitMERGE_VALUES(SDNode *N);
176     SDValue visitADD(SDNode *N);
177     SDValue visitSUB(SDNode *N);
178     SDValue visitADDC(SDNode *N);
179     SDValue visitSUBC(SDNode *N);
180     SDValue visitADDE(SDNode *N);
181     SDValue visitSUBE(SDNode *N);
182     SDValue visitMUL(SDNode *N);
183     SDValue visitSDIV(SDNode *N);
184     SDValue visitUDIV(SDNode *N);
185     SDValue visitSREM(SDNode *N);
186     SDValue visitUREM(SDNode *N);
187     SDValue visitMULHU(SDNode *N);
188     SDValue visitMULHS(SDNode *N);
189     SDValue visitSMUL_LOHI(SDNode *N);
190     SDValue visitUMUL_LOHI(SDNode *N);
191     SDValue visitSMULO(SDNode *N);
192     SDValue visitUMULO(SDNode *N);
193     SDValue visitSDIVREM(SDNode *N);
194     SDValue visitUDIVREM(SDNode *N);
195     SDValue visitAND(SDNode *N);
196     SDValue visitOR(SDNode *N);
197     SDValue visitXOR(SDNode *N);
198     SDValue SimplifyVBinOp(SDNode *N);
199     SDValue SimplifyVUnaryOp(SDNode *N);
200     SDValue visitSHL(SDNode *N);
201     SDValue visitSRA(SDNode *N);
202     SDValue visitSRL(SDNode *N);
203     SDValue visitCTLZ(SDNode *N);
204     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTTZ(SDNode *N);
206     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
207     SDValue visitCTPOP(SDNode *N);
208     SDValue visitSELECT(SDNode *N);
209     SDValue visitVSELECT(SDNode *N);
210     SDValue visitSELECT_CC(SDNode *N);
211     SDValue visitSETCC(SDNode *N);
212     SDValue visitSIGN_EXTEND(SDNode *N);
213     SDValue visitZERO_EXTEND(SDNode *N);
214     SDValue visitANY_EXTEND(SDNode *N);
215     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
216     SDValue visitTRUNCATE(SDNode *N);
217     SDValue visitBITCAST(SDNode *N);
218     SDValue visitBUILD_PAIR(SDNode *N);
219     SDValue visitFADD(SDNode *N);
220     SDValue visitFSUB(SDNode *N);
221     SDValue visitFMUL(SDNode *N);
222     SDValue visitFMA(SDNode *N);
223     SDValue visitFDIV(SDNode *N);
224     SDValue visitFREM(SDNode *N);
225     SDValue visitFCOPYSIGN(SDNode *N);
226     SDValue visitSINT_TO_FP(SDNode *N);
227     SDValue visitUINT_TO_FP(SDNode *N);
228     SDValue visitFP_TO_SINT(SDNode *N);
229     SDValue visitFP_TO_UINT(SDNode *N);
230     SDValue visitFP_ROUND(SDNode *N);
231     SDValue visitFP_ROUND_INREG(SDNode *N);
232     SDValue visitFP_EXTEND(SDNode *N);
233     SDValue visitFNEG(SDNode *N);
234     SDValue visitFABS(SDNode *N);
235     SDValue visitFCEIL(SDNode *N);
236     SDValue visitFTRUNC(SDNode *N);
237     SDValue visitFFLOOR(SDNode *N);
238     SDValue visitBRCOND(SDNode *N);
239     SDValue visitBR_CC(SDNode *N);
240     SDValue visitLOAD(SDNode *N);
241     SDValue visitSTORE(SDNode *N);
242     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
243     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
244     SDValue visitBUILD_VECTOR(SDNode *N);
245     SDValue visitCONCAT_VECTORS(SDNode *N);
246     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
247     SDValue visitVECTOR_SHUFFLE(SDNode *N);
248
249     SDValue XformToShuffleWithZero(SDNode *N);
250     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
251
252     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253
254     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
255     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
256     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
257     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
258                              SDValue N3, ISD::CondCode CC,
259                              bool NotExtCompare = false);
260     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
261                           SDLoc DL, bool foldBooleans = true);
262     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263                                          unsigned HiOp);
264     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
265     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
266     SDValue BuildSDIV(SDNode *N);
267     SDValue BuildUDIV(SDNode *N);
268     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
269                                bool DemandHighBits = true);
270     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
271     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
272     SDValue ReduceLoadWidth(SDNode *N);
273     SDValue ReduceLoadOpStoreWidth(SDNode *N);
274     SDValue TransformFPLoadStorePair(SDNode *N);
275     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
276     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277
278     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279
280     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
281     /// looking for aliasing nodes and adding them to the Aliases vector.
282     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
283                           SmallVectorImpl<SDValue> &Aliases);
284
285     /// isAlias - Return true if there is any possibility that the two addresses
286     /// overlap.
287     bool isAlias(SDValue Ptr1, int64_t Size1,
288                  const Value *SrcValue1, int SrcValueOffset1,
289                  unsigned SrcValueAlign1,
290                  const MDNode *TBAAInfo1,
291                  SDValue Ptr2, int64_t Size2,
292                  const Value *SrcValue2, int SrcValueOffset2,
293                  unsigned SrcValueAlign2,
294                  const MDNode *TBAAInfo2) const;
295
296     /// isAlias - Return true if there is any possibility that the two addresses
297     /// overlap.
298     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299
300     /// FindAliasInfo - Extracts the relevant alias information from the memory
301     /// node.  Returns true if the operand was a load.
302     bool FindAliasInfo(SDNode *N,
303                        SDValue &Ptr, int64_t &Size,
304                        const Value *&SrcValue, int &SrcValueOffset,
305                        unsigned &SrcValueAlignment,
306                        const MDNode *&TBAAInfo) const;
307
308     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
309     /// looking for a better chain (aliasing node.)
310     SDValue FindBetterChain(SDNode *N, SDValue Chain);
311
312     /// Merge consecutive store operations into a wide store.
313     /// This optimization uses wide integers or vectors when possible.
314     /// \return True if some memory operations were changed.
315     bool MergeConsecutiveStores(StoreSDNode *N);
316
317   public:
318     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
319       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
320         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321
322     /// Run - runs the dag combiner on all nodes in the work list
323     void Run(CombineLevel AtLevel);
324
325     SelectionDAG &getDAG() const { return DAG; }
326
327     /// getShiftAmountTy - Returns a type large enough to hold any valid
328     /// shift amount - before type legalization these can be huge.
329     EVT getShiftAmountTy(EVT LHSTy) {
330       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
331       if (LHSTy.isVector())
332         return LHSTy;
333       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
334     }
335
336     /// isTypeLegal - This method returns true if we are running before type
337     /// legalization or if the specified VT is legal.
338     bool isTypeLegal(const EVT &VT) {
339       if (!LegalTypes) return true;
340       return TLI.isTypeLegal(VT);
341     }
342
343     /// getSetCCResultType - Convenience wrapper around
344     /// TargetLowering::getSetCCResultType
345     EVT getSetCCResultType(EVT VT) const {
346       return TLI.getSetCCResultType(*DAG.getContext(), VT);
347     }
348   };
349 }
350
351
352 namespace {
353 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
354 /// nodes from the worklist.
355 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
356   DAGCombiner &DC;
357 public:
358   explicit WorkListRemover(DAGCombiner &dc)
359     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
360
361   virtual void NodeDeleted(SDNode *N, SDNode *E) {
362     DC.removeFromWorkList(N);
363   }
364 };
365 }
366
367 //===----------------------------------------------------------------------===//
368 //  TargetLowering::DAGCombinerInfo implementation
369 //===----------------------------------------------------------------------===//
370
371 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
372   ((DAGCombiner*)DC)->AddToWorkList(N);
373 }
374
375 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
376   ((DAGCombiner*)DC)->removeFromWorkList(N);
377 }
378
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
381   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
382 }
383
384 SDValue TargetLowering::DAGCombinerInfo::
385 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
386   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
387 }
388
389
390 SDValue TargetLowering::DAGCombinerInfo::
391 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
392   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
393 }
394
395 void TargetLowering::DAGCombinerInfo::
396 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
397   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
398 }
399
400 //===----------------------------------------------------------------------===//
401 // Helper Functions
402 //===----------------------------------------------------------------------===//
403
404 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
405 /// specified expression for the same cost as the expression itself, or 2 if we
406 /// can compute the negated form more cheaply than the expression itself.
407 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
408                                const TargetLowering &TLI,
409                                const TargetOptions *Options,
410                                unsigned Depth = 0) {
411   // fneg is removable even if it has multiple uses.
412   if (Op.getOpcode() == ISD::FNEG) return 2;
413
414   // Don't allow anything with multiple uses.
415   if (!Op.hasOneUse()) return 0;
416
417   // Don't recurse exponentially.
418   if (Depth > 6) return 0;
419
420   switch (Op.getOpcode()) {
421   default: return false;
422   case ISD::ConstantFP:
423     // Don't invert constant FP values after legalize.  The negated constant
424     // isn't necessarily legal.
425     return LegalOperations ? 0 : 1;
426   case ISD::FADD:
427     // FIXME: determine better conditions for this xform.
428     if (!Options->UnsafeFPMath) return 0;
429
430     // After operation legalization, it might not be legal to create new FSUBs.
431     if (LegalOperations &&
432         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
433       return 0;
434
435     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
436     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
437                                     Options, Depth + 1))
438       return V;
439     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
440     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
441                               Depth + 1);
442   case ISD::FSUB:
443     // We can't turn -(A-B) into B-A when we honor signed zeros.
444     if (!Options->UnsafeFPMath) return 0;
445
446     // fold (fneg (fsub A, B)) -> (fsub B, A)
447     return 1;
448
449   case ISD::FMUL:
450   case ISD::FDIV:
451     if (Options->HonorSignDependentRoundingFPMath()) return 0;
452
453     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
454     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
455                                     Options, Depth + 1))
456       return V;
457
458     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
459                               Depth + 1);
460
461   case ISD::FP_EXTEND:
462   case ISD::FP_ROUND:
463   case ISD::FSIN:
464     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
465                               Depth + 1);
466   }
467 }
468
469 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
470 /// returns the newly negated expression.
471 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
472                                     bool LegalOperations, unsigned Depth = 0) {
473   // fneg is removable even if it has multiple uses.
474   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
475
476   // Don't allow anything with multiple uses.
477   assert(Op.hasOneUse() && "Unknown reuse!");
478
479   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
480   switch (Op.getOpcode()) {
481   default: llvm_unreachable("Unknown code");
482   case ISD::ConstantFP: {
483     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
484     V.changeSign();
485     return DAG.getConstantFP(V, Op.getValueType());
486   }
487   case ISD::FADD:
488     // FIXME: determine better conditions for this xform.
489     assert(DAG.getTarget().Options.UnsafeFPMath);
490
491     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
493                            DAG.getTargetLoweringInfo(),
494                            &DAG.getTarget().Options, Depth+1))
495       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
496                          GetNegatedExpression(Op.getOperand(0), DAG,
497                                               LegalOperations, Depth+1),
498                          Op.getOperand(1));
499     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
500     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
501                        GetNegatedExpression(Op.getOperand(1), DAG,
502                                             LegalOperations, Depth+1),
503                        Op.getOperand(0));
504   case ISD::FSUB:
505     // We can't turn -(A-B) into B-A when we honor signed zeros.
506     assert(DAG.getTarget().Options.UnsafeFPMath);
507
508     // fold (fneg (fsub 0, B)) -> B
509     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
510       if (N0CFP->getValueAPF().isZero())
511         return Op.getOperand(1);
512
513     // fold (fneg (fsub A, B)) -> (fsub B, A)
514     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515                        Op.getOperand(1), Op.getOperand(0));
516
517   case ISD::FMUL:
518   case ISD::FDIV:
519     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
520
521     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
522     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523                            DAG.getTargetLoweringInfo(),
524                            &DAG.getTarget().Options, Depth+1))
525       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
526                          GetNegatedExpression(Op.getOperand(0), DAG,
527                                               LegalOperations, Depth+1),
528                          Op.getOperand(1));
529
530     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
531     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
532                        Op.getOperand(0),
533                        GetNegatedExpression(Op.getOperand(1), DAG,
534                                             LegalOperations, Depth+1));
535
536   case ISD::FP_EXTEND:
537   case ISD::FSIN:
538     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
539                        GetNegatedExpression(Op.getOperand(0), DAG,
540                                             LegalOperations, Depth+1));
541   case ISD::FP_ROUND:
542       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
543                          GetNegatedExpression(Op.getOperand(0), DAG,
544                                               LegalOperations, Depth+1),
545                          Op.getOperand(1));
546   }
547 }
548
549
550 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
551 // that selects between the values 1 and 0, making it equivalent to a setcc.
552 // Also, set the incoming LHS, RHS, and CC references to the appropriate
553 // nodes based on the type of node we are checking.  This simplifies life a
554 // bit for the callers.
555 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
556                               SDValue &CC) {
557   if (N.getOpcode() == ISD::SETCC) {
558     LHS = N.getOperand(0);
559     RHS = N.getOperand(1);
560     CC  = N.getOperand(2);
561     return true;
562   }
563   if (N.getOpcode() == ISD::SELECT_CC &&
564       N.getOperand(2).getOpcode() == ISD::Constant &&
565       N.getOperand(3).getOpcode() == ISD::Constant &&
566       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
567       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
568     LHS = N.getOperand(0);
569     RHS = N.getOperand(1);
570     CC  = N.getOperand(4);
571     return true;
572   }
573   return false;
574 }
575
576 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
577 // one use.  If this is true, it allows the users to invert the operation for
578 // free when it is profitable to do so.
579 static bool isOneUseSetCC(SDValue N) {
580   SDValue N0, N1, N2;
581   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
582     return true;
583   return false;
584 }
585
586 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
587                                     SDValue N0, SDValue N1) {
588   EVT VT = N0.getValueType();
589   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
590     if (isa<ConstantSDNode>(N1)) {
591       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592       SDValue OpNode =
593         DAG.FoldConstantArithmetic(Opc, VT,
594                                    cast<ConstantSDNode>(N0.getOperand(1)),
595                                    cast<ConstantSDNode>(N1));
596       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
597     }
598     if (N0.hasOneUse()) {
599       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
601                                    N0.getOperand(0), N1);
602       AddToWorkList(OpNode.getNode());
603       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
604     }
605   }
606
607   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
608     if (isa<ConstantSDNode>(N0)) {
609       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
610       SDValue OpNode =
611         DAG.FoldConstantArithmetic(Opc, VT,
612                                    cast<ConstantSDNode>(N1.getOperand(1)),
613                                    cast<ConstantSDNode>(N0));
614       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
615     }
616     if (N1.hasOneUse()) {
617       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
618       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
619                                    N1.getOperand(0), N0);
620       AddToWorkList(OpNode.getNode());
621       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
622     }
623   }
624
625   return SDValue();
626 }
627
628 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
629                                bool AddTo) {
630   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
631   ++NodesCombined;
632   DEBUG(dbgs() << "\nReplacing.1 ";
633         N->dump(&DAG);
634         dbgs() << "\nWith: ";
635         To[0].getNode()->dump(&DAG);
636         dbgs() << " and " << NumTo-1 << " other values\n";
637         for (unsigned i = 0, e = NumTo; i != e; ++i)
638           assert((!To[i].getNode() ||
639                   N->getValueType(i) == To[i].getValueType()) &&
640                  "Cannot combine value to value of different type!"));
641   WorkListRemover DeadNodes(*this);
642   DAG.ReplaceAllUsesWith(N, To);
643   if (AddTo) {
644     // Push the new nodes and any users onto the worklist
645     for (unsigned i = 0, e = NumTo; i != e; ++i) {
646       if (To[i].getNode()) {
647         AddToWorkList(To[i].getNode());
648         AddUsersToWorkList(To[i].getNode());
649       }
650     }
651   }
652
653   // Finally, if the node is now dead, remove it from the graph.  The node
654   // may not be dead if the replacement process recursively simplified to
655   // something else needing this node.
656   if (N->use_empty()) {
657     // Nodes can be reintroduced into the worklist.  Make sure we do not
658     // process a node that has been replaced.
659     removeFromWorkList(N);
660
661     // Finally, since the node is now dead, remove it from the graph.
662     DAG.DeleteNode(N);
663   }
664   return SDValue(N, 0);
665 }
666
667 void DAGCombiner::
668 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
669   // Replace all uses.  If any nodes become isomorphic to other nodes and
670   // are deleted, make sure to remove them from our worklist.
671   WorkListRemover DeadNodes(*this);
672   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
673
674   // Push the new node and any (possibly new) users onto the worklist.
675   AddToWorkList(TLO.New.getNode());
676   AddUsersToWorkList(TLO.New.getNode());
677
678   // Finally, if the node is now dead, remove it from the graph.  The node
679   // may not be dead if the replacement process recursively simplified to
680   // something else needing this node.
681   if (TLO.Old.getNode()->use_empty()) {
682     removeFromWorkList(TLO.Old.getNode());
683
684     // If the operands of this node are only used by the node, they will now
685     // be dead.  Make sure to visit them first to delete dead nodes early.
686     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
687       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
688         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
689
690     DAG.DeleteNode(TLO.Old.getNode());
691   }
692 }
693
694 /// SimplifyDemandedBits - Check the specified integer node value to see if
695 /// it can be simplified or if things it uses can be simplified by bit
696 /// propagation.  If so, return true.
697 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
698   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
699   APInt KnownZero, KnownOne;
700   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
701     return false;
702
703   // Revisit the node.
704   AddToWorkList(Op.getNode());
705
706   // Replace the old value with the new one.
707   ++NodesCombined;
708   DEBUG(dbgs() << "\nReplacing.2 ";
709         TLO.Old.getNode()->dump(&DAG);
710         dbgs() << "\nWith: ";
711         TLO.New.getNode()->dump(&DAG);
712         dbgs() << '\n');
713
714   CommitTargetLoweringOpt(TLO);
715   return true;
716 }
717
718 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
719   SDLoc dl(Load);
720   EVT VT = Load->getValueType(0);
721   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
722
723   DEBUG(dbgs() << "\nReplacing.9 ";
724         Load->dump(&DAG);
725         dbgs() << "\nWith: ";
726         Trunc.getNode()->dump(&DAG);
727         dbgs() << '\n');
728   WorkListRemover DeadNodes(*this);
729   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
730   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
731   removeFromWorkList(Load);
732   DAG.DeleteNode(Load);
733   AddToWorkList(Trunc.getNode());
734 }
735
736 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
737   Replace = false;
738   SDLoc dl(Op);
739   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
740     EVT MemVT = LD->getMemoryVT();
741     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
742       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
743                                                   : ISD::EXTLOAD)
744       : LD->getExtensionType();
745     Replace = true;
746     return DAG.getExtLoad(ExtType, dl, PVT,
747                           LD->getChain(), LD->getBasePtr(),
748                           LD->getPointerInfo(),
749                           MemVT, LD->isVolatile(),
750                           LD->isNonTemporal(), LD->getAlignment());
751   }
752
753   unsigned Opc = Op.getOpcode();
754   switch (Opc) {
755   default: break;
756   case ISD::AssertSext:
757     return DAG.getNode(ISD::AssertSext, dl, PVT,
758                        SExtPromoteOperand(Op.getOperand(0), PVT),
759                        Op.getOperand(1));
760   case ISD::AssertZext:
761     return DAG.getNode(ISD::AssertZext, dl, PVT,
762                        ZExtPromoteOperand(Op.getOperand(0), PVT),
763                        Op.getOperand(1));
764   case ISD::Constant: {
765     unsigned ExtOpc =
766       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
767     return DAG.getNode(ExtOpc, dl, PVT, Op);
768   }
769   }
770
771   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
772     return SDValue();
773   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
774 }
775
776 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
777   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
778     return SDValue();
779   EVT OldVT = Op.getValueType();
780   SDLoc dl(Op);
781   bool Replace = false;
782   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
783   if (NewOp.getNode() == 0)
784     return SDValue();
785   AddToWorkList(NewOp.getNode());
786
787   if (Replace)
788     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
789   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
790                      DAG.getValueType(OldVT));
791 }
792
793 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
794   EVT OldVT = Op.getValueType();
795   SDLoc dl(Op);
796   bool Replace = false;
797   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
798   if (NewOp.getNode() == 0)
799     return SDValue();
800   AddToWorkList(NewOp.getNode());
801
802   if (Replace)
803     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
804   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
805 }
806
807 /// PromoteIntBinOp - Promote the specified integer binary operation if the
808 /// target indicates it is beneficial. e.g. On x86, it's usually better to
809 /// promote i16 operations to i32 since i16 instructions are longer.
810 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
811   if (!LegalOperations)
812     return SDValue();
813
814   EVT VT = Op.getValueType();
815   if (VT.isVector() || !VT.isInteger())
816     return SDValue();
817
818   // If operation type is 'undesirable', e.g. i16 on x86, consider
819   // promoting it.
820   unsigned Opc = Op.getOpcode();
821   if (TLI.isTypeDesirableForOp(Opc, VT))
822     return SDValue();
823
824   EVT PVT = VT;
825   // Consult target whether it is a good idea to promote this operation and
826   // what's the right type to promote it to.
827   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
828     assert(PVT != VT && "Don't know what type to promote to!");
829
830     bool Replace0 = false;
831     SDValue N0 = Op.getOperand(0);
832     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
833     if (NN0.getNode() == 0)
834       return SDValue();
835
836     bool Replace1 = false;
837     SDValue N1 = Op.getOperand(1);
838     SDValue NN1;
839     if (N0 == N1)
840       NN1 = NN0;
841     else {
842       NN1 = PromoteOperand(N1, PVT, Replace1);
843       if (NN1.getNode() == 0)
844         return SDValue();
845     }
846
847     AddToWorkList(NN0.getNode());
848     if (NN1.getNode())
849       AddToWorkList(NN1.getNode());
850
851     if (Replace0)
852       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
853     if (Replace1)
854       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
855
856     DEBUG(dbgs() << "\nPromoting ";
857           Op.getNode()->dump(&DAG));
858     SDLoc dl(Op);
859     return DAG.getNode(ISD::TRUNCATE, dl, VT,
860                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
861   }
862   return SDValue();
863 }
864
865 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
866 /// target indicates it is beneficial. e.g. On x86, it's usually better to
867 /// promote i16 operations to i32 since i16 instructions are longer.
868 SDValue DAGCombiner::PromoteIntShiftOp(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
888     bool Replace = false;
889     SDValue N0 = Op.getOperand(0);
890     if (Opc == ISD::SRA)
891       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
892     else if (Opc == ISD::SRL)
893       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
894     else
895       N0 = PromoteOperand(N0, PVT, Replace);
896     if (N0.getNode() == 0)
897       return SDValue();
898
899     AddToWorkList(N0.getNode());
900     if (Replace)
901       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
902
903     DEBUG(dbgs() << "\nPromoting ";
904           Op.getNode()->dump(&DAG));
905     SDLoc dl(Op);
906     return DAG.getNode(ISD::TRUNCATE, dl, VT,
907                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
908   }
909   return SDValue();
910 }
911
912 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
913   if (!LegalOperations)
914     return SDValue();
915
916   EVT VT = Op.getValueType();
917   if (VT.isVector() || !VT.isInteger())
918     return SDValue();
919
920   // If operation type is 'undesirable', e.g. i16 on x86, consider
921   // promoting it.
922   unsigned Opc = Op.getOpcode();
923   if (TLI.isTypeDesirableForOp(Opc, VT))
924     return SDValue();
925
926   EVT PVT = VT;
927   // Consult target whether it is a good idea to promote this operation and
928   // what's the right type to promote it to.
929   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
930     assert(PVT != VT && "Don't know what type to promote to!");
931     // fold (aext (aext x)) -> (aext x)
932     // fold (aext (zext x)) -> (zext x)
933     // fold (aext (sext x)) -> (sext x)
934     DEBUG(dbgs() << "\nPromoting ";
935           Op.getNode()->dump(&DAG));
936     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
937   }
938   return SDValue();
939 }
940
941 bool DAGCombiner::PromoteLoad(SDValue Op) {
942   if (!LegalOperations)
943     return false;
944
945   EVT VT = Op.getValueType();
946   if (VT.isVector() || !VT.isInteger())
947     return false;
948
949   // If operation type is 'undesirable', e.g. i16 on x86, consider
950   // promoting it.
951   unsigned Opc = Op.getOpcode();
952   if (TLI.isTypeDesirableForOp(Opc, VT))
953     return false;
954
955   EVT PVT = VT;
956   // Consult target whether it is a good idea to promote this operation and
957   // what's the right type to promote it to.
958   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
959     assert(PVT != VT && "Don't know what type to promote to!");
960
961     SDLoc dl(Op);
962     SDNode *N = Op.getNode();
963     LoadSDNode *LD = cast<LoadSDNode>(N);
964     EVT MemVT = LD->getMemoryVT();
965     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
966       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
967                                                   : ISD::EXTLOAD)
968       : LD->getExtensionType();
969     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
970                                    LD->getChain(), LD->getBasePtr(),
971                                    LD->getPointerInfo(),
972                                    MemVT, LD->isVolatile(),
973                                    LD->isNonTemporal(), LD->getAlignment());
974     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
975
976     DEBUG(dbgs() << "\nPromoting ";
977           N->dump(&DAG);
978           dbgs() << "\nTo: ";
979           Result.getNode()->dump(&DAG);
980           dbgs() << '\n');
981     WorkListRemover DeadNodes(*this);
982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
983     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
984     removeFromWorkList(N);
985     DAG.DeleteNode(N);
986     AddToWorkList(Result.getNode());
987     return true;
988   }
989   return false;
990 }
991
992
993 //===----------------------------------------------------------------------===//
994 //  Main DAG Combiner implementation
995 //===----------------------------------------------------------------------===//
996
997 void DAGCombiner::Run(CombineLevel AtLevel) {
998   // set the instance variables, so that the various visit routines may use it.
999   Level = AtLevel;
1000   LegalOperations = Level >= AfterLegalizeVectorOps;
1001   LegalTypes = Level >= AfterLegalizeTypes;
1002
1003   // Add all the dag nodes to the worklist.
1004   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1005        E = DAG.allnodes_end(); I != E; ++I)
1006     AddToWorkList(I);
1007
1008   // Create a dummy node (which is not added to allnodes), that adds a reference
1009   // to the root node, preventing it from being deleted, and tracking any
1010   // changes of the root.
1011   HandleSDNode Dummy(DAG.getRoot());
1012
1013   // The root of the dag may dangle to deleted nodes until the dag combiner is
1014   // done.  Set it to null to avoid confusion.
1015   DAG.setRoot(SDValue());
1016
1017   // while the worklist isn't empty, find a node and
1018   // try and combine it.
1019   while (!WorkListContents.empty()) {
1020     SDNode *N;
1021     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1022     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1023     // worklist *should* contain, and check the node we want to visit is should
1024     // actually be visited.
1025     do {
1026       N = WorkListOrder.pop_back_val();
1027     } while (!WorkListContents.erase(N));
1028
1029     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1030     // N is deleted from the DAG, since they too may now be dead or may have a
1031     // reduced number of uses, allowing other xforms.
1032     if (N->use_empty() && N != &Dummy) {
1033       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1034         AddToWorkList(N->getOperand(i).getNode());
1035
1036       DAG.DeleteNode(N);
1037       continue;
1038     }
1039
1040     SDValue RV = combine(N);
1041
1042     if (RV.getNode() == 0)
1043       continue;
1044
1045     ++NodesCombined;
1046
1047     // If we get back the same node we passed in, rather than a new node or
1048     // zero, we know that the node must have defined multiple values and
1049     // CombineTo was used.  Since CombineTo takes care of the worklist
1050     // mechanics for us, we have no work to do in this case.
1051     if (RV.getNode() == N)
1052       continue;
1053
1054     assert(N->getOpcode() != ISD::DELETED_NODE &&
1055            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1056            "Node was deleted but visit returned new node!");
1057
1058     DEBUG(dbgs() << "\nReplacing.3 ";
1059           N->dump(&DAG);
1060           dbgs() << "\nWith: ";
1061           RV.getNode()->dump(&DAG);
1062           dbgs() << '\n');
1063
1064     // Transfer debug value.
1065     DAG.TransferDbgValues(SDValue(N, 0), RV);
1066     WorkListRemover DeadNodes(*this);
1067     if (N->getNumValues() == RV.getNode()->getNumValues())
1068       DAG.ReplaceAllUsesWith(N, RV.getNode());
1069     else {
1070       assert(N->getValueType(0) == RV.getValueType() &&
1071              N->getNumValues() == 1 && "Type mismatch");
1072       SDValue OpV = RV;
1073       DAG.ReplaceAllUsesWith(N, &OpV);
1074     }
1075
1076     // Push the new node and any users onto the worklist
1077     AddToWorkList(RV.getNode());
1078     AddUsersToWorkList(RV.getNode());
1079
1080     // Add any uses of the old node to the worklist in case this node is the
1081     // last one that uses them.  They may become dead after this node is
1082     // deleted.
1083     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1084       AddToWorkList(N->getOperand(i).getNode());
1085
1086     // Finally, if the node is now dead, remove it from the graph.  The node
1087     // may not be dead if the replacement process recursively simplified to
1088     // something else needing this node.
1089     if (N->use_empty()) {
1090       // Nodes can be reintroduced into the worklist.  Make sure we do not
1091       // process a node that has been replaced.
1092       removeFromWorkList(N);
1093
1094       // Finally, since the node is now dead, remove it from the graph.
1095       DAG.DeleteNode(N);
1096     }
1097   }
1098
1099   // If the root changed (e.g. it was a dead load, update the root).
1100   DAG.setRoot(Dummy.getValue());
1101   DAG.RemoveDeadNodes();
1102 }
1103
1104 SDValue DAGCombiner::visit(SDNode *N) {
1105   switch (N->getOpcode()) {
1106   default: break;
1107   case ISD::TokenFactor:        return visitTokenFactor(N);
1108   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1109   case ISD::ADD:                return visitADD(N);
1110   case ISD::SUB:                return visitSUB(N);
1111   case ISD::ADDC:               return visitADDC(N);
1112   case ISD::SUBC:               return visitSUBC(N);
1113   case ISD::ADDE:               return visitADDE(N);
1114   case ISD::SUBE:               return visitSUBE(N);
1115   case ISD::MUL:                return visitMUL(N);
1116   case ISD::SDIV:               return visitSDIV(N);
1117   case ISD::UDIV:               return visitUDIV(N);
1118   case ISD::SREM:               return visitSREM(N);
1119   case ISD::UREM:               return visitUREM(N);
1120   case ISD::MULHU:              return visitMULHU(N);
1121   case ISD::MULHS:              return visitMULHS(N);
1122   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1123   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1124   case ISD::SMULO:              return visitSMULO(N);
1125   case ISD::UMULO:              return visitUMULO(N);
1126   case ISD::SDIVREM:            return visitSDIVREM(N);
1127   case ISD::UDIVREM:            return visitUDIVREM(N);
1128   case ISD::AND:                return visitAND(N);
1129   case ISD::OR:                 return visitOR(N);
1130   case ISD::XOR:                return visitXOR(N);
1131   case ISD::SHL:                return visitSHL(N);
1132   case ISD::SRA:                return visitSRA(N);
1133   case ISD::SRL:                return visitSRL(N);
1134   case ISD::CTLZ:               return visitCTLZ(N);
1135   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1136   case ISD::CTTZ:               return visitCTTZ(N);
1137   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1138   case ISD::CTPOP:              return visitCTPOP(N);
1139   case ISD::SELECT:             return visitSELECT(N);
1140   case ISD::VSELECT:            return visitVSELECT(N);
1141   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1142   case ISD::SETCC:              return visitSETCC(N);
1143   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1144   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1145   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1146   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1147   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1148   case ISD::BITCAST:            return visitBITCAST(N);
1149   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1150   case ISD::FADD:               return visitFADD(N);
1151   case ISD::FSUB:               return visitFSUB(N);
1152   case ISD::FMUL:               return visitFMUL(N);
1153   case ISD::FMA:                return visitFMA(N);
1154   case ISD::FDIV:               return visitFDIV(N);
1155   case ISD::FREM:               return visitFREM(N);
1156   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1157   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1158   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1159   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1160   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1161   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1162   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1163   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1164   case ISD::FNEG:               return visitFNEG(N);
1165   case ISD::FABS:               return visitFABS(N);
1166   case ISD::FFLOOR:             return visitFFLOOR(N);
1167   case ISD::FCEIL:              return visitFCEIL(N);
1168   case ISD::FTRUNC:             return visitFTRUNC(N);
1169   case ISD::BRCOND:             return visitBRCOND(N);
1170   case ISD::BR_CC:              return visitBR_CC(N);
1171   case ISD::LOAD:               return visitLOAD(N);
1172   case ISD::STORE:              return visitSTORE(N);
1173   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1174   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1175   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1176   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1177   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1178   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1179   }
1180   return SDValue();
1181 }
1182
1183 SDValue DAGCombiner::combine(SDNode *N) {
1184   SDValue RV = visit(N);
1185
1186   // If nothing happened, try a target-specific DAG combine.
1187   if (RV.getNode() == 0) {
1188     assert(N->getOpcode() != ISD::DELETED_NODE &&
1189            "Node was deleted but visit returned NULL!");
1190
1191     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1192         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1193
1194       // Expose the DAG combiner to the target combiner impls.
1195       TargetLowering::DAGCombinerInfo
1196         DagCombineInfo(DAG, Level, false, this);
1197
1198       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1199     }
1200   }
1201
1202   // If nothing happened still, try promoting the operation.
1203   if (RV.getNode() == 0) {
1204     switch (N->getOpcode()) {
1205     default: break;
1206     case ISD::ADD:
1207     case ISD::SUB:
1208     case ISD::MUL:
1209     case ISD::AND:
1210     case ISD::OR:
1211     case ISD::XOR:
1212       RV = PromoteIntBinOp(SDValue(N, 0));
1213       break;
1214     case ISD::SHL:
1215     case ISD::SRA:
1216     case ISD::SRL:
1217       RV = PromoteIntShiftOp(SDValue(N, 0));
1218       break;
1219     case ISD::SIGN_EXTEND:
1220     case ISD::ZERO_EXTEND:
1221     case ISD::ANY_EXTEND:
1222       RV = PromoteExtend(SDValue(N, 0));
1223       break;
1224     case ISD::LOAD:
1225       if (PromoteLoad(SDValue(N, 0)))
1226         RV = SDValue(N, 0);
1227       break;
1228     }
1229   }
1230
1231   // If N is a commutative binary node, try commuting it to enable more
1232   // sdisel CSE.
1233   if (RV.getNode() == 0 &&
1234       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1235       N->getNumValues() == 1) {
1236     SDValue N0 = N->getOperand(0);
1237     SDValue N1 = N->getOperand(1);
1238
1239     // Constant operands are canonicalized to RHS.
1240     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1241       SDValue Ops[] = { N1, N0 };
1242       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1243                                             Ops, 2);
1244       if (CSENode)
1245         return SDValue(CSENode, 0);
1246     }
1247   }
1248
1249   return RV;
1250 }
1251
1252 /// getInputChainForNode - Given a node, return its input chain if it has one,
1253 /// otherwise return a null sd operand.
1254 static SDValue getInputChainForNode(SDNode *N) {
1255   if (unsigned NumOps = N->getNumOperands()) {
1256     if (N->getOperand(0).getValueType() == MVT::Other)
1257       return N->getOperand(0);
1258     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1259       return N->getOperand(NumOps-1);
1260     for (unsigned i = 1; i < NumOps-1; ++i)
1261       if (N->getOperand(i).getValueType() == MVT::Other)
1262         return N->getOperand(i);
1263   }
1264   return SDValue();
1265 }
1266
1267 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1268   // If N has two operands, where one has an input chain equal to the other,
1269   // the 'other' chain is redundant.
1270   if (N->getNumOperands() == 2) {
1271     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1272       return N->getOperand(0);
1273     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1274       return N->getOperand(1);
1275   }
1276
1277   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1278   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1279   SmallPtrSet<SDNode*, 16> SeenOps;
1280   bool Changed = false;             // If we should replace this token factor.
1281
1282   // Start out with this token factor.
1283   TFs.push_back(N);
1284
1285   // Iterate through token factors.  The TFs grows when new token factors are
1286   // encountered.
1287   for (unsigned i = 0; i < TFs.size(); ++i) {
1288     SDNode *TF = TFs[i];
1289
1290     // Check each of the operands.
1291     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1292       SDValue Op = TF->getOperand(i);
1293
1294       switch (Op.getOpcode()) {
1295       case ISD::EntryToken:
1296         // Entry tokens don't need to be added to the list. They are
1297         // rededundant.
1298         Changed = true;
1299         break;
1300
1301       case ISD::TokenFactor:
1302         if (Op.hasOneUse() &&
1303             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1304           // Queue up for processing.
1305           TFs.push_back(Op.getNode());
1306           // Clean up in case the token factor is removed.
1307           AddToWorkList(Op.getNode());
1308           Changed = true;
1309           break;
1310         }
1311         // Fall thru
1312
1313       default:
1314         // Only add if it isn't already in the list.
1315         if (SeenOps.insert(Op.getNode()))
1316           Ops.push_back(Op);
1317         else
1318           Changed = true;
1319         break;
1320       }
1321     }
1322   }
1323
1324   SDValue Result;
1325
1326   // If we've change things around then replace token factor.
1327   if (Changed) {
1328     if (Ops.empty()) {
1329       // The entry token is the only possible outcome.
1330       Result = DAG.getEntryNode();
1331     } else {
1332       // New and improved token factor.
1333       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1334                            MVT::Other, &Ops[0], Ops.size());
1335     }
1336
1337     // Don't add users to work list.
1338     return CombineTo(N, Result, false);
1339   }
1340
1341   return Result;
1342 }
1343
1344 /// MERGE_VALUES can always be eliminated.
1345 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1346   WorkListRemover DeadNodes(*this);
1347   // Replacing results may cause a different MERGE_VALUES to suddenly
1348   // be CSE'd with N, and carry its uses with it. Iterate until no
1349   // uses remain, to ensure that the node can be safely deleted.
1350   // First add the users of this node to the work list so that they
1351   // can be tried again once they have new operands.
1352   AddUsersToWorkList(N);
1353   do {
1354     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1355       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1356   } while (!N->use_empty());
1357   removeFromWorkList(N);
1358   DAG.DeleteNode(N);
1359   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1360 }
1361
1362 static
1363 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1364                               SelectionDAG &DAG) {
1365   EVT VT = N0.getValueType();
1366   SDValue N00 = N0.getOperand(0);
1367   SDValue N01 = N0.getOperand(1);
1368   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1369
1370   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1371       isa<ConstantSDNode>(N00.getOperand(1))) {
1372     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1373     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1374                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1375                                  N00.getOperand(0), N01),
1376                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1377                                  N00.getOperand(1), N01));
1378     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1379   }
1380
1381   return SDValue();
1382 }
1383
1384 SDValue DAGCombiner::visitADD(SDNode *N) {
1385   SDValue N0 = N->getOperand(0);
1386   SDValue N1 = N->getOperand(1);
1387   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1389   EVT VT = N0.getValueType();
1390
1391   // fold vector ops
1392   if (VT.isVector()) {
1393     SDValue FoldedVOp = SimplifyVBinOp(N);
1394     if (FoldedVOp.getNode()) return FoldedVOp;
1395
1396     // fold (add x, 0) -> x, vector edition
1397     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1398       return N0;
1399     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1400       return N1;
1401   }
1402
1403   // fold (add x, undef) -> undef
1404   if (N0.getOpcode() == ISD::UNDEF)
1405     return N0;
1406   if (N1.getOpcode() == ISD::UNDEF)
1407     return N1;
1408   // fold (add c1, c2) -> c1+c2
1409   if (N0C && N1C)
1410     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1411   // canonicalize constant to RHS
1412   if (N0C && !N1C)
1413     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1414   // fold (add x, 0) -> x
1415   if (N1C && N1C->isNullValue())
1416     return N0;
1417   // fold (add Sym, c) -> Sym+c
1418   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1419     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1420         GA->getOpcode() == ISD::GlobalAddress)
1421       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1422                                   GA->getOffset() +
1423                                     (uint64_t)N1C->getSExtValue());
1424   // fold ((c1-A)+c2) -> (c1+c2)-A
1425   if (N1C && N0.getOpcode() == ISD::SUB)
1426     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1427       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1428                          DAG.getConstant(N1C->getAPIntValue()+
1429                                          N0C->getAPIntValue(), VT),
1430                          N0.getOperand(1));
1431   // reassociate add
1432   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1433   if (RADD.getNode() != 0)
1434     return RADD;
1435   // fold ((0-A) + B) -> B-A
1436   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1437       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1438     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1439   // fold (A + (0-B)) -> A-B
1440   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1441       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1442     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1443   // fold (A+(B-A)) -> B
1444   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1445     return N1.getOperand(0);
1446   // fold ((B-A)+A) -> B
1447   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1448     return N0.getOperand(0);
1449   // fold (A+(B-(A+C))) to (B-C)
1450   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1451       N0 == N1.getOperand(1).getOperand(0))
1452     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1453                        N1.getOperand(1).getOperand(1));
1454   // fold (A+(B-(C+A))) to (B-C)
1455   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1456       N0 == N1.getOperand(1).getOperand(1))
1457     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1458                        N1.getOperand(1).getOperand(0));
1459   // fold (A+((B-A)+or-C)) to (B+or-C)
1460   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1461       N1.getOperand(0).getOpcode() == ISD::SUB &&
1462       N0 == N1.getOperand(0).getOperand(1))
1463     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1464                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1465
1466   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1467   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1468     SDValue N00 = N0.getOperand(0);
1469     SDValue N01 = N0.getOperand(1);
1470     SDValue N10 = N1.getOperand(0);
1471     SDValue N11 = N1.getOperand(1);
1472
1473     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1474       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1475                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1476                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1477   }
1478
1479   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1480     return SDValue(N, 0);
1481
1482   // fold (a+b) -> (a|b) iff a and b share no bits.
1483   if (VT.isInteger() && !VT.isVector()) {
1484     APInt LHSZero, LHSOne;
1485     APInt RHSZero, RHSOne;
1486     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1487
1488     if (LHSZero.getBoolValue()) {
1489       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1490
1491       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1492       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1493       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1494         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1495     }
1496   }
1497
1498   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1499   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1500     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1501     if (Result.getNode()) return Result;
1502   }
1503   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1504     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1505     if (Result.getNode()) return Result;
1506   }
1507
1508   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1509   if (N1.getOpcode() == ISD::SHL &&
1510       N1.getOperand(0).getOpcode() == ISD::SUB)
1511     if (ConstantSDNode *C =
1512           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1513       if (C->getAPIntValue() == 0)
1514         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1515                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1516                                        N1.getOperand(0).getOperand(1),
1517                                        N1.getOperand(1)));
1518   if (N0.getOpcode() == ISD::SHL &&
1519       N0.getOperand(0).getOpcode() == ISD::SUB)
1520     if (ConstantSDNode *C =
1521           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1522       if (C->getAPIntValue() == 0)
1523         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1524                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1525                                        N0.getOperand(0).getOperand(1),
1526                                        N0.getOperand(1)));
1527
1528   if (N1.getOpcode() == ISD::AND) {
1529     SDValue AndOp0 = N1.getOperand(0);
1530     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1531     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1532     unsigned DestBits = VT.getScalarType().getSizeInBits();
1533
1534     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1535     // and similar xforms where the inner op is either ~0 or 0.
1536     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1537       SDLoc DL(N);
1538       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1539     }
1540   }
1541
1542   // add (sext i1), X -> sub X, (zext i1)
1543   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1544       N0.getOperand(0).getValueType() == MVT::i1 &&
1545       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1546     SDLoc DL(N);
1547     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1548     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1549   }
1550
1551   return SDValue();
1552 }
1553
1554 SDValue DAGCombiner::visitADDC(SDNode *N) {
1555   SDValue N0 = N->getOperand(0);
1556   SDValue N1 = N->getOperand(1);
1557   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1558   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559   EVT VT = N0.getValueType();
1560
1561   // If the flag result is dead, turn this into an ADD.
1562   if (!N->hasAnyUseOfValue(1))
1563     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1564                      DAG.getNode(ISD::CARRY_FALSE,
1565                                  SDLoc(N), MVT::Glue));
1566
1567   // canonicalize constant to RHS.
1568   if (N0C && !N1C)
1569     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1570
1571   // fold (addc x, 0) -> x + no carry out
1572   if (N1C && N1C->isNullValue())
1573     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1574                                         SDLoc(N), MVT::Glue));
1575
1576   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1577   APInt LHSZero, LHSOne;
1578   APInt RHSZero, RHSOne;
1579   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1580
1581   if (LHSZero.getBoolValue()) {
1582     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1583
1584     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1587       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1588                        DAG.getNode(ISD::CARRY_FALSE,
1589                                    SDLoc(N), MVT::Glue));
1590   }
1591
1592   return SDValue();
1593 }
1594
1595 SDValue DAGCombiner::visitADDE(SDNode *N) {
1596   SDValue N0 = N->getOperand(0);
1597   SDValue N1 = N->getOperand(1);
1598   SDValue CarryIn = N->getOperand(2);
1599   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601
1602   // canonicalize constant to RHS
1603   if (N0C && !N1C)
1604     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1605                        N1, N0, CarryIn);
1606
1607   // fold (adde x, y, false) -> (addc x, y)
1608   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1609     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1610
1611   return SDValue();
1612 }
1613
1614 // Since it may not be valid to emit a fold to zero for vector initializers
1615 // check if we can before folding.
1616 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1617                              SelectionDAG &DAG,
1618                              bool LegalOperations, bool LegalTypes) {
1619   if (!VT.isVector())
1620     return DAG.getConstant(0, VT);
1621   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1622     // Produce a vector of zeros.
1623     EVT ElemTy = VT.getVectorElementType();
1624     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1625                       TargetLowering::TypePromoteInteger)
1626       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1627     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1628            "Type for zero vector elements is not legal");
1629     SDValue El = DAG.getConstant(0, ElemTy);
1630     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1631     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1632       &Ops[0], Ops.size());
1633   }
1634   return SDValue();
1635 }
1636
1637 SDValue DAGCombiner::visitSUB(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1642   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1643     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1644   EVT VT = N0.getValueType();
1645
1646   // fold vector ops
1647   if (VT.isVector()) {
1648     SDValue FoldedVOp = SimplifyVBinOp(N);
1649     if (FoldedVOp.getNode()) return FoldedVOp;
1650
1651     // fold (sub x, 0) -> x, vector edition
1652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1653       return N0;
1654   }
1655
1656   // fold (sub x, x) -> 0
1657   // FIXME: Refactor this and xor and other similar operations together.
1658   if (N0 == N1)
1659     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1660   // fold (sub c1, c2) -> c1-c2
1661   if (N0C && N1C)
1662     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1663   // fold (sub x, c) -> (add x, -c)
1664   if (N1C)
1665     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1666                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1667   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1668   if (N0C && N0C->isAllOnesValue())
1669     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1670   // fold A-(A-B) -> B
1671   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1672     return N1.getOperand(1);
1673   // fold (A+B)-A -> B
1674   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1675     return N0.getOperand(1);
1676   // fold (A+B)-B -> A
1677   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1678     return N0.getOperand(0);
1679   // fold C2-(A+C1) -> (C2-C1)-A
1680   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1681     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1682                                    VT);
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1684                        N1.getOperand(0));
1685   }
1686   // fold ((A+(B+or-C))-B) -> A+or-C
1687   if (N0.getOpcode() == ISD::ADD &&
1688       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1689        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1690       N0.getOperand(1).getOperand(0) == N1)
1691     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1692                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1693   // fold ((A+(C+B))-B) -> A+C
1694   if (N0.getOpcode() == ISD::ADD &&
1695       N0.getOperand(1).getOpcode() == ISD::ADD &&
1696       N0.getOperand(1).getOperand(1) == N1)
1697     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1698                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1699   // fold ((A-(B-C))-C) -> A-B
1700   if (N0.getOpcode() == ISD::SUB &&
1701       N0.getOperand(1).getOpcode() == ISD::SUB &&
1702       N0.getOperand(1).getOperand(1) == N1)
1703     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1704                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705
1706   // If either operand of a sub is undef, the result is undef
1707   if (N0.getOpcode() == ISD::UNDEF)
1708     return N0;
1709   if (N1.getOpcode() == ISD::UNDEF)
1710     return N1;
1711
1712   // If the relocation model supports it, consider symbol offsets.
1713   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1714     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1715       // fold (sub Sym, c) -> Sym-c
1716       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1717         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1718                                     GA->getOffset() -
1719                                       (uint64_t)N1C->getSExtValue());
1720       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1721       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1722         if (GA->getGlobal() == GB->getGlobal())
1723           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1724                                  VT);
1725     }
1726
1727   return SDValue();
1728 }
1729
1730 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1731   SDValue N0 = N->getOperand(0);
1732   SDValue N1 = N->getOperand(1);
1733   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735   EVT VT = N0.getValueType();
1736
1737   // If the flag result is dead, turn this into an SUB.
1738   if (!N->hasAnyUseOfValue(1))
1739     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1740                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1741                                  MVT::Glue));
1742
1743   // fold (subc x, x) -> 0 + no borrow
1744   if (N0 == N1)
1745     return CombineTo(N, DAG.getConstant(0, VT),
1746                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                  MVT::Glue));
1748
1749   // fold (subc x, 0) -> x + no borrow
1750   if (N1C && N1C->isNullValue())
1751     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1752                                         MVT::Glue));
1753
1754   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1755   if (N0C && N0C->isAllOnesValue())
1756     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1757                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                  MVT::Glue));
1759
1760   return SDValue();
1761 }
1762
1763 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1764   SDValue N0 = N->getOperand(0);
1765   SDValue N1 = N->getOperand(1);
1766   SDValue CarryIn = N->getOperand(2);
1767
1768   // fold (sube x, y, false) -> (subc x, y)
1769   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1770     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1771
1772   return SDValue();
1773 }
1774
1775 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1776 /// all the same constant or undefined.
1777 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1778   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1779   if (!C)
1780     return false;
1781
1782   APInt SplatUndef;
1783   unsigned SplatBitSize;
1784   bool HasAnyUndefs;
1785   EVT EltVT = N->getValueType(0).getVectorElementType();
1786   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1787                              HasAnyUndefs) &&
1788           EltVT.getSizeInBits() >= SplatBitSize);
1789 }
1790
1791 SDValue DAGCombiner::visitMUL(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // fold (mul x, undef) -> 0
1797   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1798     return DAG.getConstant(0, VT);
1799
1800   bool N0IsConst = false;
1801   bool N1IsConst = false;
1802   APInt ConstValue0, ConstValue1;
1803   // fold vector ops
1804   if (VT.isVector()) {
1805     SDValue FoldedVOp = SimplifyVBinOp(N);
1806     if (FoldedVOp.getNode()) return FoldedVOp;
1807
1808     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1809     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1810   } else {
1811     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1812     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1813     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1814     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1815   }
1816
1817   // fold (mul c1, c2) -> c1*c2
1818   if (N0IsConst && N1IsConst)
1819     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1820
1821   // canonicalize constant to RHS
1822   if (N0IsConst && !N1IsConst)
1823     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1824   // fold (mul x, 0) -> 0
1825   if (N1IsConst && ConstValue1 == 0)
1826     return N1;
1827   // fold (mul x, 1) -> x
1828   if (N1IsConst && ConstValue1 == 1)
1829     return N0;
1830   // fold (mul x, -1) -> 0-x
1831   if (N1IsConst && ConstValue1.isAllOnesValue())
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1833                        DAG.getConstant(0, VT), N0);
1834   // fold (mul x, (1 << c)) -> x << c
1835   if (N1IsConst && ConstValue1.isPowerOf2())
1836     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1837                        DAG.getConstant(ConstValue1.logBase2(),
1838                                        getShiftAmountTy(N0.getValueType())));
1839   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1840   if (N1IsConst && (-ConstValue1).isPowerOf2()) {
1841     unsigned Log2Val = (-ConstValue1).logBase2();
1842     // FIXME: If the input is something that is easily negated (e.g. a
1843     // single-use add), we should put the negate there.
1844     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1845                        DAG.getConstant(0, VT),
1846                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1847                             DAG.getConstant(Log2Val,
1848                                       getShiftAmountTy(N0.getValueType()))));
1849   }
1850
1851   APInt Val;
1852   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1853   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1854       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1855                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1856     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1857                              N1, N0.getOperand(1));
1858     AddToWorkList(C3.getNode());
1859     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1860                        N0.getOperand(0), C3);
1861   }
1862
1863   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1864   // use.
1865   {
1866     SDValue Sh(0,0), Y(0,0);
1867     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1868     if (N0.getOpcode() == ISD::SHL &&
1869         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1870                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1871         N0.getNode()->hasOneUse()) {
1872       Sh = N0; Y = N1;
1873     } else if (N1.getOpcode() == ISD::SHL &&
1874                isa<ConstantSDNode>(N1.getOperand(1)) &&
1875                N1.getNode()->hasOneUse()) {
1876       Sh = N1; Y = N0;
1877     }
1878
1879     if (Sh.getNode()) {
1880       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1881                                 Sh.getOperand(0), Y);
1882       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1883                          Mul, Sh.getOperand(1));
1884     }
1885   }
1886
1887   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1888   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1889       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1890                      isa<ConstantSDNode>(N0.getOperand(1))))
1891     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1892                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1893                                    N0.getOperand(0), N1),
1894                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1895                                    N0.getOperand(1), N1));
1896
1897   // reassociate mul
1898   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1899   if (RMUL.getNode() != 0)
1900     return RMUL;
1901
1902   return SDValue();
1903 }
1904
1905 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1906   SDValue N0 = N->getOperand(0);
1907   SDValue N1 = N->getOperand(1);
1908   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1909   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1910   EVT VT = N->getValueType(0);
1911
1912   // fold vector ops
1913   if (VT.isVector()) {
1914     SDValue FoldedVOp = SimplifyVBinOp(N);
1915     if (FoldedVOp.getNode()) return FoldedVOp;
1916   }
1917
1918   // fold (sdiv c1, c2) -> c1/c2
1919   if (N0C && N1C && !N1C->isNullValue())
1920     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1921   // fold (sdiv X, 1) -> X
1922   if (N1C && N1C->getAPIntValue() == 1LL)
1923     return N0;
1924   // fold (sdiv X, -1) -> 0-X
1925   if (N1C && N1C->isAllOnesValue())
1926     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1927                        DAG.getConstant(0, VT), N0);
1928   // If we know the sign bits of both operands are zero, strength reduce to a
1929   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1930   if (!VT.isVector()) {
1931     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1932       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1933                          N0, N1);
1934   }
1935   // fold (sdiv X, pow2) -> simple ops after legalize
1936   if (N1C && !N1C->isNullValue() &&
1937       (N1C->getAPIntValue().isPowerOf2() ||
1938        (-N1C->getAPIntValue()).isPowerOf2())) {
1939     // If dividing by powers of two is cheap, then don't perform the following
1940     // fold.
1941     if (TLI.isPow2DivCheap())
1942       return SDValue();
1943
1944     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1945
1946     // Splat the sign bit into the register
1947     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1948                               DAG.getConstant(VT.getSizeInBits()-1,
1949                                        getShiftAmountTy(N0.getValueType())));
1950     AddToWorkList(SGN.getNode());
1951
1952     // Add (N0 < 0) ? abs2 - 1 : 0;
1953     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1954                               DAG.getConstant(VT.getSizeInBits() - lg2,
1955                                        getShiftAmountTy(SGN.getValueType())));
1956     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1957     AddToWorkList(SRL.getNode());
1958     AddToWorkList(ADD.getNode());    // Divide by pow2
1959     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1960                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1961
1962     // If we're dividing by a positive value, we're done.  Otherwise, we must
1963     // negate the result.
1964     if (N1C->getAPIntValue().isNonNegative())
1965       return SRA;
1966
1967     AddToWorkList(SRA.getNode());
1968     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1969                        DAG.getConstant(0, VT), SRA);
1970   }
1971
1972   // if integer divide is expensive and we satisfy the requirements, emit an
1973   // alternate sequence.
1974   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1975     SDValue Op = BuildSDIV(N);
1976     if (Op.getNode()) return Op;
1977   }
1978
1979   // undef / X -> 0
1980   if (N0.getOpcode() == ISD::UNDEF)
1981     return DAG.getConstant(0, VT);
1982   // X / undef -> undef
1983   if (N1.getOpcode() == ISD::UNDEF)
1984     return N1;
1985
1986   return SDValue();
1987 }
1988
1989 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1990   SDValue N0 = N->getOperand(0);
1991   SDValue N1 = N->getOperand(1);
1992   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1993   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1994   EVT VT = N->getValueType(0);
1995
1996   // fold vector ops
1997   if (VT.isVector()) {
1998     SDValue FoldedVOp = SimplifyVBinOp(N);
1999     if (FoldedVOp.getNode()) return FoldedVOp;
2000   }
2001
2002   // fold (udiv c1, c2) -> c1/c2
2003   if (N0C && N1C && !N1C->isNullValue())
2004     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2005   // fold (udiv x, (1 << c)) -> x >>u c
2006   if (N1C && N1C->getAPIntValue().isPowerOf2())
2007     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2008                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2009                                        getShiftAmountTy(N0.getValueType())));
2010   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2011   if (N1.getOpcode() == ISD::SHL) {
2012     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2013       if (SHC->getAPIntValue().isPowerOf2()) {
2014         EVT ADDVT = N1.getOperand(1).getValueType();
2015         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2016                                   N1.getOperand(1),
2017                                   DAG.getConstant(SHC->getAPIntValue()
2018                                                                   .logBase2(),
2019                                                   ADDVT));
2020         AddToWorkList(Add.getNode());
2021         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2022       }
2023     }
2024   }
2025   // fold (udiv x, c) -> alternate
2026   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2027     SDValue Op = BuildUDIV(N);
2028     if (Op.getNode()) return Op;
2029   }
2030
2031   // undef / X -> 0
2032   if (N0.getOpcode() == ISD::UNDEF)
2033     return DAG.getConstant(0, VT);
2034   // X / undef -> undef
2035   if (N1.getOpcode() == ISD::UNDEF)
2036     return N1;
2037
2038   return SDValue();
2039 }
2040
2041 SDValue DAGCombiner::visitSREM(SDNode *N) {
2042   SDValue N0 = N->getOperand(0);
2043   SDValue N1 = N->getOperand(1);
2044   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2045   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2046   EVT VT = N->getValueType(0);
2047
2048   // fold (srem c1, c2) -> c1%c2
2049   if (N0C && N1C && !N1C->isNullValue())
2050     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2051   // If we know the sign bits of both operands are zero, strength reduce to a
2052   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2053   if (!VT.isVector()) {
2054     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2055       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2056   }
2057
2058   // If X/C can be simplified by the division-by-constant logic, lower
2059   // X%C to the equivalent of X-X/C*C.
2060   if (N1C && !N1C->isNullValue()) {
2061     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2062     AddToWorkList(Div.getNode());
2063     SDValue OptimizedDiv = combine(Div.getNode());
2064     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2065       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066                                 OptimizedDiv, N1);
2067       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2068       AddToWorkList(Mul.getNode());
2069       return Sub;
2070     }
2071   }
2072
2073   // undef % X -> 0
2074   if (N0.getOpcode() == ISD::UNDEF)
2075     return DAG.getConstant(0, VT);
2076   // X % undef -> undef
2077   if (N1.getOpcode() == ISD::UNDEF)
2078     return N1;
2079
2080   return SDValue();
2081 }
2082
2083 SDValue DAGCombiner::visitUREM(SDNode *N) {
2084   SDValue N0 = N->getOperand(0);
2085   SDValue N1 = N->getOperand(1);
2086   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2087   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2088   EVT VT = N->getValueType(0);
2089
2090   // fold (urem c1, c2) -> c1%c2
2091   if (N0C && N1C && !N1C->isNullValue())
2092     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2093   // fold (urem x, pow2) -> (and x, pow2-1)
2094   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2095     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2096                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2097   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2098   if (N1.getOpcode() == ISD::SHL) {
2099     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2100       if (SHC->getAPIntValue().isPowerOf2()) {
2101         SDValue Add =
2102           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2103                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2104                                  VT));
2105         AddToWorkList(Add.getNode());
2106         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2107       }
2108     }
2109   }
2110
2111   // If X/C can be simplified by the division-by-constant logic, lower
2112   // X%C to the equivalent of X-X/C*C.
2113   if (N1C && !N1C->isNullValue()) {
2114     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2115     AddToWorkList(Div.getNode());
2116     SDValue OptimizedDiv = combine(Div.getNode());
2117     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2118       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119                                 OptimizedDiv, N1);
2120       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2121       AddToWorkList(Mul.getNode());
2122       return Sub;
2123     }
2124   }
2125
2126   // undef % X -> 0
2127   if (N0.getOpcode() == ISD::UNDEF)
2128     return DAG.getConstant(0, VT);
2129   // X % undef -> undef
2130   if (N1.getOpcode() == ISD::UNDEF)
2131     return N1;
2132
2133   return SDValue();
2134 }
2135
2136 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2137   SDValue N0 = N->getOperand(0);
2138   SDValue N1 = N->getOperand(1);
2139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2140   EVT VT = N->getValueType(0);
2141   SDLoc DL(N);
2142
2143   // fold (mulhs x, 0) -> 0
2144   if (N1C && N1C->isNullValue())
2145     return N1;
2146   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2147   if (N1C && N1C->getAPIntValue() == 1)
2148     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2149                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2150                                        getShiftAmountTy(N0.getValueType())));
2151   // fold (mulhs x, undef) -> 0
2152   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2153     return DAG.getConstant(0, VT);
2154
2155   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2156   // plus a shift.
2157   if (VT.isSimple() && !VT.isVector()) {
2158     MVT Simple = VT.getSimpleVT();
2159     unsigned SimpleSize = Simple.getSizeInBits();
2160     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2161     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2162       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2163       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2164       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2165       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2166             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2167       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2168     }
2169   }
2170
2171   return SDValue();
2172 }
2173
2174 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2175   SDValue N0 = N->getOperand(0);
2176   SDValue N1 = N->getOperand(1);
2177   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2178   EVT VT = N->getValueType(0);
2179   SDLoc DL(N);
2180
2181   // fold (mulhu x, 0) -> 0
2182   if (N1C && N1C->isNullValue())
2183     return N1;
2184   // fold (mulhu x, 1) -> 0
2185   if (N1C && N1C->getAPIntValue() == 1)
2186     return DAG.getConstant(0, N0.getValueType());
2187   // fold (mulhu x, undef) -> 0
2188   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2189     return DAG.getConstant(0, VT);
2190
2191   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2192   // plus a shift.
2193   if (VT.isSimple() && !VT.isVector()) {
2194     MVT Simple = VT.getSimpleVT();
2195     unsigned SimpleSize = Simple.getSizeInBits();
2196     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2197     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2198       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2199       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2200       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2201       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2202             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2203       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2204     }
2205   }
2206
2207   return SDValue();
2208 }
2209
2210 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2211 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2212 /// that are being performed. Return true if a simplification was made.
2213 ///
2214 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2215                                                 unsigned HiOp) {
2216   // If the high half is not needed, just compute the low half.
2217   bool HiExists = N->hasAnyUseOfValue(1);
2218   if (!HiExists &&
2219       (!LegalOperations ||
2220        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2221     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2222                               N->op_begin(), N->getNumOperands());
2223     return CombineTo(N, Res, Res);
2224   }
2225
2226   // If the low half is not needed, just compute the high half.
2227   bool LoExists = N->hasAnyUseOfValue(0);
2228   if (!LoExists &&
2229       (!LegalOperations ||
2230        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2231     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2232                               N->op_begin(), N->getNumOperands());
2233     return CombineTo(N, Res, Res);
2234   }
2235
2236   // If both halves are used, return as it is.
2237   if (LoExists && HiExists)
2238     return SDValue();
2239
2240   // If the two computed results can be simplified separately, separate them.
2241   if (LoExists) {
2242     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2243                              N->op_begin(), N->getNumOperands());
2244     AddToWorkList(Lo.getNode());
2245     SDValue LoOpt = combine(Lo.getNode());
2246     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2247         (!LegalOperations ||
2248          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2249       return CombineTo(N, LoOpt, LoOpt);
2250   }
2251
2252   if (HiExists) {
2253     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2254                              N->op_begin(), N->getNumOperands());
2255     AddToWorkList(Hi.getNode());
2256     SDValue HiOpt = combine(Hi.getNode());
2257     if (HiOpt.getNode() && HiOpt != Hi &&
2258         (!LegalOperations ||
2259          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2260       return CombineTo(N, HiOpt, HiOpt);
2261   }
2262
2263   return SDValue();
2264 }
2265
2266 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2267   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2268   if (Res.getNode()) return Res;
2269
2270   EVT VT = N->getValueType(0);
2271   SDLoc DL(N);
2272
2273   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2274   // plus a shift.
2275   if (VT.isSimple() && !VT.isVector()) {
2276     MVT Simple = VT.getSimpleVT();
2277     unsigned SimpleSize = Simple.getSizeInBits();
2278     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2279     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2280       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2281       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2282       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2283       // Compute the high part as N1.
2284       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2285             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2286       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2287       // Compute the low part as N0.
2288       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2289       return CombineTo(N, Lo, Hi);
2290     }
2291   }
2292
2293   return SDValue();
2294 }
2295
2296 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2297   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2298   if (Res.getNode()) return Res;
2299
2300   EVT VT = N->getValueType(0);
2301   SDLoc DL(N);
2302
2303   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2304   // plus a shift.
2305   if (VT.isSimple() && !VT.isVector()) {
2306     MVT Simple = VT.getSimpleVT();
2307     unsigned SimpleSize = Simple.getSizeInBits();
2308     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2309     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2310       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2311       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2312       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2313       // Compute the high part as N1.
2314       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2315             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2316       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2317       // Compute the low part as N0.
2318       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2319       return CombineTo(N, Lo, Hi);
2320     }
2321   }
2322
2323   return SDValue();
2324 }
2325
2326 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2327   // (smulo x, 2) -> (saddo x, x)
2328   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2329     if (C2->getAPIntValue() == 2)
2330       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2331                          N->getOperand(0), N->getOperand(0));
2332
2333   return SDValue();
2334 }
2335
2336 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2337   // (umulo x, 2) -> (uaddo x, x)
2338   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2339     if (C2->getAPIntValue() == 2)
2340       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2341                          N->getOperand(0), N->getOperand(0));
2342
2343   return SDValue();
2344 }
2345
2346 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2347   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2348   if (Res.getNode()) return Res;
2349
2350   return SDValue();
2351 }
2352
2353 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2354   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2355   if (Res.getNode()) return Res;
2356
2357   return SDValue();
2358 }
2359
2360 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2361 /// two operands of the same opcode, try to simplify it.
2362 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2363   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2364   EVT VT = N0.getValueType();
2365   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2366
2367   // Bail early if none of these transforms apply.
2368   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2369
2370   // For each of OP in AND/OR/XOR:
2371   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2372   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2373   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2374   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2375   //
2376   // do not sink logical op inside of a vector extend, since it may combine
2377   // into a vsetcc.
2378   EVT Op0VT = N0.getOperand(0).getValueType();
2379   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2380        N0.getOpcode() == ISD::SIGN_EXTEND ||
2381        // Avoid infinite looping with PromoteIntBinOp.
2382        (N0.getOpcode() == ISD::ANY_EXTEND &&
2383         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2384        (N0.getOpcode() == ISD::TRUNCATE &&
2385         (!TLI.isZExtFree(VT, Op0VT) ||
2386          !TLI.isTruncateFree(Op0VT, VT)) &&
2387         TLI.isTypeLegal(Op0VT))) &&
2388       !VT.isVector() &&
2389       Op0VT == N1.getOperand(0).getValueType() &&
2390       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2391     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2392                                  N0.getOperand(0).getValueType(),
2393                                  N0.getOperand(0), N1.getOperand(0));
2394     AddToWorkList(ORNode.getNode());
2395     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2396   }
2397
2398   // For each of OP in SHL/SRL/SRA/AND...
2399   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2400   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2401   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2402   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2403        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2404       N0.getOperand(1) == N1.getOperand(1)) {
2405     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2406                                  N0.getOperand(0).getValueType(),
2407                                  N0.getOperand(0), N1.getOperand(0));
2408     AddToWorkList(ORNode.getNode());
2409     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2410                        ORNode, N0.getOperand(1));
2411   }
2412
2413   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2414   // Only perform this optimization after type legalization and before
2415   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2416   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2417   // we don't want to undo this promotion.
2418   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2419   // on scalars.
2420   if ((N0.getOpcode() == ISD::BITCAST ||
2421        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2422       Level == AfterLegalizeTypes) {
2423     SDValue In0 = N0.getOperand(0);
2424     SDValue In1 = N1.getOperand(0);
2425     EVT In0Ty = In0.getValueType();
2426     EVT In1Ty = In1.getValueType();
2427     SDLoc DL(N);
2428     // If both incoming values are integers, and the original types are the
2429     // same.
2430     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2431       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2432       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2433       AddToWorkList(Op.getNode());
2434       return BC;
2435     }
2436   }
2437
2438   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2439   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2440   // If both shuffles use the same mask, and both shuffle within a single
2441   // vector, then it is worthwhile to move the swizzle after the operation.
2442   // The type-legalizer generates this pattern when loading illegal
2443   // vector types from memory. In many cases this allows additional shuffle
2444   // optimizations.
2445   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2446       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2447       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2448     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2449     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2450
2451     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2452            "Inputs to shuffles are not the same type");
2453
2454     unsigned NumElts = VT.getVectorNumElements();
2455
2456     // Check that both shuffles use the same mask. The masks are known to be of
2457     // the same length because the result vector type is the same.
2458     bool SameMask = true;
2459     for (unsigned i = 0; i != NumElts; ++i) {
2460       int Idx0 = SVN0->getMaskElt(i);
2461       int Idx1 = SVN1->getMaskElt(i);
2462       if (Idx0 != Idx1) {
2463         SameMask = false;
2464         break;
2465       }
2466     }
2467
2468     if (SameMask) {
2469       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2470                                N0.getOperand(0), N1.getOperand(0));
2471       AddToWorkList(Op.getNode());
2472       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2473                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2474     }
2475   }
2476
2477   return SDValue();
2478 }
2479
2480 SDValue DAGCombiner::visitAND(SDNode *N) {
2481   SDValue N0 = N->getOperand(0);
2482   SDValue N1 = N->getOperand(1);
2483   SDValue LL, LR, RL, RR, CC0, CC1;
2484   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2485   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2486   EVT VT = N1.getValueType();
2487   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2488
2489   // fold vector ops
2490   if (VT.isVector()) {
2491     SDValue FoldedVOp = SimplifyVBinOp(N);
2492     if (FoldedVOp.getNode()) return FoldedVOp;
2493
2494     // fold (and x, 0) -> 0, vector edition
2495     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2496       return N0;
2497     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2498       return N1;
2499
2500     // fold (and x, -1) -> x, vector edition
2501     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2502       return N1;
2503     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2504       return N0;
2505   }
2506
2507   // fold (and x, undef) -> 0
2508   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2509     return DAG.getConstant(0, VT);
2510   // fold (and c1, c2) -> c1&c2
2511   if (N0C && N1C)
2512     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2513   // canonicalize constant to RHS
2514   if (N0C && !N1C)
2515     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2516   // fold (and x, -1) -> x
2517   if (N1C && N1C->isAllOnesValue())
2518     return N0;
2519   // if (and x, c) is known to be zero, return 0
2520   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2521                                    APInt::getAllOnesValue(BitWidth)))
2522     return DAG.getConstant(0, VT);
2523   // reassociate and
2524   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2525   if (RAND.getNode() != 0)
2526     return RAND;
2527   // fold (and (or x, C), D) -> D if (C & D) == D
2528   if (N1C && N0.getOpcode() == ISD::OR)
2529     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2530       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2531         return N1;
2532   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2533   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2534     SDValue N0Op0 = N0.getOperand(0);
2535     APInt Mask = ~N1C->getAPIntValue();
2536     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2537     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2538       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2539                                  N0.getValueType(), N0Op0);
2540
2541       // Replace uses of the AND with uses of the Zero extend node.
2542       CombineTo(N, Zext);
2543
2544       // We actually want to replace all uses of the any_extend with the
2545       // zero_extend, to avoid duplicating things.  This will later cause this
2546       // AND to be folded.
2547       CombineTo(N0.getNode(), Zext);
2548       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2549     }
2550   }
2551   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2552   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2553   // already be zero by virtue of the width of the base type of the load.
2554   //
2555   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2556   // more cases.
2557   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2558        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2559       N0.getOpcode() == ISD::LOAD) {
2560     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2561                                          N0 : N0.getOperand(0) );
2562
2563     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2564     // This can be a pure constant or a vector splat, in which case we treat the
2565     // vector as a scalar and use the splat value.
2566     APInt Constant = APInt::getNullValue(1);
2567     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2568       Constant = C->getAPIntValue();
2569     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2570       APInt SplatValue, SplatUndef;
2571       unsigned SplatBitSize;
2572       bool HasAnyUndefs;
2573       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2574                                              SplatBitSize, HasAnyUndefs);
2575       if (IsSplat) {
2576         // Undef bits can contribute to a possible optimisation if set, so
2577         // set them.
2578         SplatValue |= SplatUndef;
2579
2580         // The splat value may be something like "0x00FFFFFF", which means 0 for
2581         // the first vector value and FF for the rest, repeating. We need a mask
2582         // that will apply equally to all members of the vector, so AND all the
2583         // lanes of the constant together.
2584         EVT VT = Vector->getValueType(0);
2585         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2586
2587         // If the splat value has been compressed to a bitlength lower
2588         // than the size of the vector lane, we need to re-expand it to
2589         // the lane size.
2590         if (BitWidth > SplatBitSize)
2591           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2592                SplatBitSize < BitWidth;
2593                SplatBitSize = SplatBitSize * 2)
2594             SplatValue |= SplatValue.shl(SplatBitSize);
2595
2596         Constant = APInt::getAllOnesValue(BitWidth);
2597         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2598           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2599       }
2600     }
2601
2602     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2603     // actually legal and isn't going to get expanded, else this is a false
2604     // optimisation.
2605     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2606                                                     Load->getMemoryVT());
2607
2608     // Resize the constant to the same size as the original memory access before
2609     // extension. If it is still the AllOnesValue then this AND is completely
2610     // unneeded.
2611     Constant =
2612       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2613
2614     bool B;
2615     switch (Load->getExtensionType()) {
2616     default: B = false; break;
2617     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2618     case ISD::ZEXTLOAD:
2619     case ISD::NON_EXTLOAD: B = true; break;
2620     }
2621
2622     if (B && Constant.isAllOnesValue()) {
2623       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2624       // preserve semantics once we get rid of the AND.
2625       SDValue NewLoad(Load, 0);
2626       if (Load->getExtensionType() == ISD::EXTLOAD) {
2627         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2628                               Load->getValueType(0), SDLoc(Load),
2629                               Load->getChain(), Load->getBasePtr(),
2630                               Load->getOffset(), Load->getMemoryVT(),
2631                               Load->getMemOperand());
2632         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2633         if (Load->getNumValues() == 3) {
2634           // PRE/POST_INC loads have 3 values.
2635           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2636                            NewLoad.getValue(2) };
2637           CombineTo(Load, To, 3, true);
2638         } else {
2639           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2640         }
2641       }
2642
2643       // Fold the AND away, taking care not to fold to the old load node if we
2644       // replaced it.
2645       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2646
2647       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2648     }
2649   }
2650   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2651   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2652     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2653     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2654
2655     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2656         LL.getValueType().isInteger()) {
2657       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2658       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2659         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2660                                      LR.getValueType(), LL, RL);
2661         AddToWorkList(ORNode.getNode());
2662         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2663       }
2664       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2665       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2666         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2667                                       LR.getValueType(), LL, RL);
2668         AddToWorkList(ANDNode.getNode());
2669         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2670       }
2671       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2672       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2673         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2674                                      LR.getValueType(), LL, RL);
2675         AddToWorkList(ORNode.getNode());
2676         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2677       }
2678     }
2679     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2680     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2681         Op0 == Op1 && LL.getValueType().isInteger() &&
2682       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2683                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2684                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2685                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2686       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2687                                     LL, DAG.getConstant(1, LL.getValueType()));
2688       AddToWorkList(ADDNode.getNode());
2689       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2690                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2691     }
2692     // canonicalize equivalent to ll == rl
2693     if (LL == RR && LR == RL) {
2694       Op1 = ISD::getSetCCSwappedOperands(Op1);
2695       std::swap(RL, RR);
2696     }
2697     if (LL == RL && LR == RR) {
2698       bool isInteger = LL.getValueType().isInteger();
2699       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2700       if (Result != ISD::SETCC_INVALID &&
2701           (!LegalOperations ||
2702            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2703             TLI.isOperationLegal(ISD::SETCC,
2704                             getSetCCResultType(N0.getSimpleValueType())))))
2705         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2706                             LL, LR, Result);
2707     }
2708   }
2709
2710   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2711   if (N0.getOpcode() == N1.getOpcode()) {
2712     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2713     if (Tmp.getNode()) return Tmp;
2714   }
2715
2716   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2717   // fold (and (sra)) -> (and (srl)) when possible.
2718   if (!VT.isVector() &&
2719       SimplifyDemandedBits(SDValue(N, 0)))
2720     return SDValue(N, 0);
2721
2722   // fold (zext_inreg (extload x)) -> (zextload x)
2723   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2724     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2725     EVT MemVT = LN0->getMemoryVT();
2726     // If we zero all the possible extended bits, then we can turn this into
2727     // a zextload if we are running before legalize or the operation is legal.
2728     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2729     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2730                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2731         ((!LegalOperations && !LN0->isVolatile()) ||
2732          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2733       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2734                                        LN0->getChain(), LN0->getBasePtr(),
2735                                        LN0->getPointerInfo(), MemVT,
2736                                        LN0->isVolatile(), LN0->isNonTemporal(),
2737                                        LN0->getAlignment());
2738       AddToWorkList(N);
2739       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2740       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2741     }
2742   }
2743   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2744   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2745       N0.hasOneUse()) {
2746     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2747     EVT MemVT = LN0->getMemoryVT();
2748     // If we zero all the possible extended bits, then we can turn this into
2749     // a zextload if we are running before legalize or the operation is legal.
2750     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2751     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2752                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2753         ((!LegalOperations && !LN0->isVolatile()) ||
2754          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2755       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2756                                        LN0->getChain(),
2757                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2758                                        MemVT,
2759                                        LN0->isVolatile(), LN0->isNonTemporal(),
2760                                        LN0->getAlignment());
2761       AddToWorkList(N);
2762       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2763       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2764     }
2765   }
2766
2767   // fold (and (load x), 255) -> (zextload x, i8)
2768   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2769   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2770   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2771               (N0.getOpcode() == ISD::ANY_EXTEND &&
2772                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2773     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2774     LoadSDNode *LN0 = HasAnyExt
2775       ? cast<LoadSDNode>(N0.getOperand(0))
2776       : cast<LoadSDNode>(N0);
2777     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2778         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2779       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2780       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2781         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2782         EVT LoadedVT = LN0->getMemoryVT();
2783
2784         if (ExtVT == LoadedVT &&
2785             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2786           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2787
2788           SDValue NewLoad =
2789             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2790                            LN0->getChain(), LN0->getBasePtr(),
2791                            LN0->getPointerInfo(),
2792                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2793                            LN0->getAlignment());
2794           AddToWorkList(N);
2795           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2796           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2797         }
2798
2799         // Do not change the width of a volatile load.
2800         // Do not generate loads of non-round integer types since these can
2801         // be expensive (and would be wrong if the type is not byte sized).
2802         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2803             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2804           EVT PtrType = LN0->getOperand(1).getValueType();
2805
2806           unsigned Alignment = LN0->getAlignment();
2807           SDValue NewPtr = LN0->getBasePtr();
2808
2809           // For big endian targets, we need to add an offset to the pointer
2810           // to load the correct bytes.  For little endian systems, we merely
2811           // need to read fewer bytes from the same pointer.
2812           if (TLI.isBigEndian()) {
2813             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2814             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2815             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2816             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2817                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2818             Alignment = MinAlign(Alignment, PtrOff);
2819           }
2820
2821           AddToWorkList(NewPtr.getNode());
2822
2823           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2824           SDValue Load =
2825             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2826                            LN0->getChain(), NewPtr,
2827                            LN0->getPointerInfo(),
2828                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2829                            Alignment);
2830           AddToWorkList(N);
2831           CombineTo(LN0, Load, Load.getValue(1));
2832           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2833         }
2834       }
2835     }
2836   }
2837
2838   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2839       VT.getSizeInBits() <= 64) {
2840     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2841       APInt ADDC = ADDI->getAPIntValue();
2842       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2843         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2844         // immediate for an add, but it is legal if its top c2 bits are set,
2845         // transform the ADD so the immediate doesn't need to be materialized
2846         // in a register.
2847         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2848           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2849                                              SRLI->getZExtValue());
2850           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2851             ADDC |= Mask;
2852             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2853               SDValue NewAdd =
2854                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2855                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2856               CombineTo(N0.getNode(), NewAdd);
2857               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2858             }
2859           }
2860         }
2861       }
2862     }
2863   }
2864
2865   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2866   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2867     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2868                                        N0.getOperand(1), false);
2869     if (BSwap.getNode())
2870       return BSwap;
2871   }
2872
2873   return SDValue();
2874 }
2875
2876 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2877 ///
2878 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2879                                         bool DemandHighBits) {
2880   if (!LegalOperations)
2881     return SDValue();
2882
2883   EVT VT = N->getValueType(0);
2884   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2885     return SDValue();
2886   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2887     return SDValue();
2888
2889   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2890   bool LookPassAnd0 = false;
2891   bool LookPassAnd1 = false;
2892   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2893       std::swap(N0, N1);
2894   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2895       std::swap(N0, N1);
2896   if (N0.getOpcode() == ISD::AND) {
2897     if (!N0.getNode()->hasOneUse())
2898       return SDValue();
2899     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2900     if (!N01C || N01C->getZExtValue() != 0xFF00)
2901       return SDValue();
2902     N0 = N0.getOperand(0);
2903     LookPassAnd0 = true;
2904   }
2905
2906   if (N1.getOpcode() == ISD::AND) {
2907     if (!N1.getNode()->hasOneUse())
2908       return SDValue();
2909     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2910     if (!N11C || N11C->getZExtValue() != 0xFF)
2911       return SDValue();
2912     N1 = N1.getOperand(0);
2913     LookPassAnd1 = true;
2914   }
2915
2916   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2917     std::swap(N0, N1);
2918   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2919     return SDValue();
2920   if (!N0.getNode()->hasOneUse() ||
2921       !N1.getNode()->hasOneUse())
2922     return SDValue();
2923
2924   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2925   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2926   if (!N01C || !N11C)
2927     return SDValue();
2928   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2929     return SDValue();
2930
2931   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2932   SDValue N00 = N0->getOperand(0);
2933   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2934     if (!N00.getNode()->hasOneUse())
2935       return SDValue();
2936     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2937     if (!N001C || N001C->getZExtValue() != 0xFF)
2938       return SDValue();
2939     N00 = N00.getOperand(0);
2940     LookPassAnd0 = true;
2941   }
2942
2943   SDValue N10 = N1->getOperand(0);
2944   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2945     if (!N10.getNode()->hasOneUse())
2946       return SDValue();
2947     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2948     if (!N101C || N101C->getZExtValue() != 0xFF00)
2949       return SDValue();
2950     N10 = N10.getOperand(0);
2951     LookPassAnd1 = true;
2952   }
2953
2954   if (N00 != N10)
2955     return SDValue();
2956
2957   // Make sure everything beyond the low halfword gets set to zero since the SRL
2958   // 16 will clear the top bits.
2959   unsigned OpSizeInBits = VT.getSizeInBits();
2960   if (DemandHighBits && OpSizeInBits > 16) {
2961     // If the left-shift isn't masked out then the only way this is a bswap is
2962     // if all bits beyond the low 8 are 0. In that case the entire pattern
2963     // reduces to a left shift anyway: leave it for other parts of the combiner.
2964     if (!LookPassAnd0)
2965       return SDValue();
2966
2967     // However, if the right shift isn't masked out then it might be because
2968     // it's not needed. See if we can spot that too.
2969     if (!LookPassAnd1 &&
2970         !DAG.MaskedValueIsZero(
2971             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2972       return SDValue();
2973   }
2974
2975   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2976   if (OpSizeInBits > 16)
2977     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2978                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2979   return Res;
2980 }
2981
2982 /// isBSwapHWordElement - Return true if the specified node is an element
2983 /// that makes up a 32-bit packed halfword byteswap. i.e.
2984 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2985 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2986   if (!N.getNode()->hasOneUse())
2987     return false;
2988
2989   unsigned Opc = N.getOpcode();
2990   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2991     return false;
2992
2993   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2994   if (!N1C)
2995     return false;
2996
2997   unsigned Num;
2998   switch (N1C->getZExtValue()) {
2999   default:
3000     return false;
3001   case 0xFF:       Num = 0; break;
3002   case 0xFF00:     Num = 1; break;
3003   case 0xFF0000:   Num = 2; break;
3004   case 0xFF000000: Num = 3; break;
3005   }
3006
3007   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3008   SDValue N0 = N.getOperand(0);
3009   if (Opc == ISD::AND) {
3010     if (Num == 0 || Num == 2) {
3011       // (x >> 8) & 0xff
3012       // (x >> 8) & 0xff0000
3013       if (N0.getOpcode() != ISD::SRL)
3014         return false;
3015       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3016       if (!C || C->getZExtValue() != 8)
3017         return false;
3018     } else {
3019       // (x << 8) & 0xff00
3020       // (x << 8) & 0xff000000
3021       if (N0.getOpcode() != ISD::SHL)
3022         return false;
3023       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3024       if (!C || C->getZExtValue() != 8)
3025         return false;
3026     }
3027   } else if (Opc == ISD::SHL) {
3028     // (x & 0xff) << 8
3029     // (x & 0xff0000) << 8
3030     if (Num != 0 && Num != 2)
3031       return false;
3032     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3033     if (!C || C->getZExtValue() != 8)
3034       return false;
3035   } else { // Opc == ISD::SRL
3036     // (x & 0xff00) >> 8
3037     // (x & 0xff000000) >> 8
3038     if (Num != 1 && Num != 3)
3039       return false;
3040     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3041     if (!C || C->getZExtValue() != 8)
3042       return false;
3043   }
3044
3045   if (Parts[Num])
3046     return false;
3047
3048   Parts[Num] = N0.getOperand(0).getNode();
3049   return true;
3050 }
3051
3052 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3053 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3054 /// => (rotl (bswap x), 16)
3055 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3056   if (!LegalOperations)
3057     return SDValue();
3058
3059   EVT VT = N->getValueType(0);
3060   if (VT != MVT::i32)
3061     return SDValue();
3062   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3063     return SDValue();
3064
3065   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3066   // Look for either
3067   // (or (or (and), (and)), (or (and), (and)))
3068   // (or (or (or (and), (and)), (and)), (and))
3069   if (N0.getOpcode() != ISD::OR)
3070     return SDValue();
3071   SDValue N00 = N0.getOperand(0);
3072   SDValue N01 = N0.getOperand(1);
3073
3074   if (N1.getOpcode() == ISD::OR &&
3075       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3076     // (or (or (and), (and)), (or (and), (and)))
3077     SDValue N000 = N00.getOperand(0);
3078     if (!isBSwapHWordElement(N000, Parts))
3079       return SDValue();
3080
3081     SDValue N001 = N00.getOperand(1);
3082     if (!isBSwapHWordElement(N001, Parts))
3083       return SDValue();
3084     SDValue N010 = N01.getOperand(0);
3085     if (!isBSwapHWordElement(N010, Parts))
3086       return SDValue();
3087     SDValue N011 = N01.getOperand(1);
3088     if (!isBSwapHWordElement(N011, Parts))
3089       return SDValue();
3090   } else {
3091     // (or (or (or (and), (and)), (and)), (and))
3092     if (!isBSwapHWordElement(N1, Parts))
3093       return SDValue();
3094     if (!isBSwapHWordElement(N01, Parts))
3095       return SDValue();
3096     if (N00.getOpcode() != ISD::OR)
3097       return SDValue();
3098     SDValue N000 = N00.getOperand(0);
3099     if (!isBSwapHWordElement(N000, Parts))
3100       return SDValue();
3101     SDValue N001 = N00.getOperand(1);
3102     if (!isBSwapHWordElement(N001, Parts))
3103       return SDValue();
3104   }
3105
3106   // Make sure the parts are all coming from the same node.
3107   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3108     return SDValue();
3109
3110   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3111                               SDValue(Parts[0],0));
3112
3113   // Result of the bswap should be rotated by 16. If it's not legal, than
3114   // do  (x << 16) | (x >> 16).
3115   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3116   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3117     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3118   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3119     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3120   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3121                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3122                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3123 }
3124
3125 SDValue DAGCombiner::visitOR(SDNode *N) {
3126   SDValue N0 = N->getOperand(0);
3127   SDValue N1 = N->getOperand(1);
3128   SDValue LL, LR, RL, RR, CC0, CC1;
3129   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3130   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3131   EVT VT = N1.getValueType();
3132
3133   // fold vector ops
3134   if (VT.isVector()) {
3135     SDValue FoldedVOp = SimplifyVBinOp(N);
3136     if (FoldedVOp.getNode()) return FoldedVOp;
3137
3138     // fold (or x, 0) -> x, vector edition
3139     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3140       return N1;
3141     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3142       return N0;
3143
3144     // fold (or x, -1) -> -1, vector edition
3145     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3146       return N0;
3147     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3148       return N1;
3149   }
3150
3151   // fold (or x, undef) -> -1
3152   if (!LegalOperations &&
3153       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3154     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3155     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3156   }
3157   // fold (or c1, c2) -> c1|c2
3158   if (N0C && N1C)
3159     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3160   // canonicalize constant to RHS
3161   if (N0C && !N1C)
3162     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3163   // fold (or x, 0) -> x
3164   if (N1C && N1C->isNullValue())
3165     return N0;
3166   // fold (or x, -1) -> -1
3167   if (N1C && N1C->isAllOnesValue())
3168     return N1;
3169   // fold (or x, c) -> c iff (x & ~c) == 0
3170   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3171     return N1;
3172
3173   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3174   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3175   if (BSwap.getNode() != 0)
3176     return BSwap;
3177   BSwap = MatchBSwapHWordLow(N, N0, N1);
3178   if (BSwap.getNode() != 0)
3179     return BSwap;
3180
3181   // reassociate or
3182   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3183   if (ROR.getNode() != 0)
3184     return ROR;
3185   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3186   // iff (c1 & c2) == 0.
3187   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3188              isa<ConstantSDNode>(N0.getOperand(1))) {
3189     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3190     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3191       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3192                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3193                                      N0.getOperand(0), N1),
3194                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3195   }
3196   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3197   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3198     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3199     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3200
3201     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3202         LL.getValueType().isInteger()) {
3203       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3204       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3205       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3206           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3207         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3208                                      LR.getValueType(), LL, RL);
3209         AddToWorkList(ORNode.getNode());
3210         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3211       }
3212       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3213       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3214       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3215           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3216         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3217                                       LR.getValueType(), LL, RL);
3218         AddToWorkList(ANDNode.getNode());
3219         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3220       }
3221     }
3222     // canonicalize equivalent to ll == rl
3223     if (LL == RR && LR == RL) {
3224       Op1 = ISD::getSetCCSwappedOperands(Op1);
3225       std::swap(RL, RR);
3226     }
3227     if (LL == RL && LR == RR) {
3228       bool isInteger = LL.getValueType().isInteger();
3229       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3230       if (Result != ISD::SETCC_INVALID &&
3231           (!LegalOperations ||
3232            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3233             TLI.isOperationLegal(ISD::SETCC,
3234               getSetCCResultType(N0.getValueType())))))
3235         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3236                             LL, LR, Result);
3237     }
3238   }
3239
3240   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3241   if (N0.getOpcode() == N1.getOpcode()) {
3242     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3243     if (Tmp.getNode()) return Tmp;
3244   }
3245
3246   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3247   if (N0.getOpcode() == ISD::AND &&
3248       N1.getOpcode() == ISD::AND &&
3249       N0.getOperand(1).getOpcode() == ISD::Constant &&
3250       N1.getOperand(1).getOpcode() == ISD::Constant &&
3251       // Don't increase # computations.
3252       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3253     // We can only do this xform if we know that bits from X that are set in C2
3254     // but not in C1 are already zero.  Likewise for Y.
3255     const APInt &LHSMask =
3256       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3257     const APInt &RHSMask =
3258       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3259
3260     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3261         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3262       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3263                               N0.getOperand(0), N1.getOperand(0));
3264       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3265                          DAG.getConstant(LHSMask | RHSMask, VT));
3266     }
3267   }
3268
3269   // See if this is some rotate idiom.
3270   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3271     return SDValue(Rot, 0);
3272
3273   // Simplify the operands using demanded-bits information.
3274   if (!VT.isVector() &&
3275       SimplifyDemandedBits(SDValue(N, 0)))
3276     return SDValue(N, 0);
3277
3278   return SDValue();
3279 }
3280
3281 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3282 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3283   if (Op.getOpcode() == ISD::AND) {
3284     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3285       Mask = Op.getOperand(1);
3286       Op = Op.getOperand(0);
3287     } else {
3288       return false;
3289     }
3290   }
3291
3292   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3293     Shift = Op;
3294     return true;
3295   }
3296
3297   return false;
3298 }
3299
3300 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3301 // idioms for rotate, and if the target supports rotation instructions, generate
3302 // a rot[lr].
3303 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3304   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3305   EVT VT = LHS.getValueType();
3306   if (!TLI.isTypeLegal(VT)) return 0;
3307
3308   // The target must have at least one rotate flavor.
3309   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3310   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3311   if (!HasROTL && !HasROTR) return 0;
3312
3313   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3314   SDValue LHSShift;   // The shift.
3315   SDValue LHSMask;    // AND value if any.
3316   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3317     return 0; // Not part of a rotate.
3318
3319   SDValue RHSShift;   // The shift.
3320   SDValue RHSMask;    // AND value if any.
3321   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3322     return 0; // Not part of a rotate.
3323
3324   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3325     return 0;   // Not shifting the same value.
3326
3327   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3328     return 0;   // Shifts must disagree.
3329
3330   // Canonicalize shl to left side in a shl/srl pair.
3331   if (RHSShift.getOpcode() == ISD::SHL) {
3332     std::swap(LHS, RHS);
3333     std::swap(LHSShift, RHSShift);
3334     std::swap(LHSMask , RHSMask );
3335   }
3336
3337   unsigned OpSizeInBits = VT.getSizeInBits();
3338   SDValue LHSShiftArg = LHSShift.getOperand(0);
3339   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3340   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3341
3342   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3343   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3344   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3345       RHSShiftAmt.getOpcode() == ISD::Constant) {
3346     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3347     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3348     if ((LShVal + RShVal) != OpSizeInBits)
3349       return 0;
3350
3351     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3352                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3353
3354     // If there is an AND of either shifted operand, apply it to the result.
3355     if (LHSMask.getNode() || RHSMask.getNode()) {
3356       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3357
3358       if (LHSMask.getNode()) {
3359         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3360         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3361       }
3362       if (RHSMask.getNode()) {
3363         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3364         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3365       }
3366
3367       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3368     }
3369
3370     return Rot.getNode();
3371   }
3372
3373   // If there is a mask here, and we have a variable shift, we can't be sure
3374   // that we're masking out the right stuff.
3375   if (LHSMask.getNode() || RHSMask.getNode())
3376     return 0;
3377
3378   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3379   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3380   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3381       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3382     if (ConstantSDNode *SUBC =
3383           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3384       if (SUBC->getAPIntValue() == OpSizeInBits)
3385         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3386                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3387     }
3388   }
3389
3390   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3391   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3392   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3393       RHSShiftAmt == LHSShiftAmt.getOperand(1))
3394     if (ConstantSDNode *SUBC =
3395           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0)))
3396       if (SUBC->getAPIntValue() == OpSizeInBits)
3397         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3398                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3399
3400   // Look for sign/zext/any-extended or truncate cases:
3401   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3402        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3403        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3404        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3405       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3406        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3407        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3408        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3409     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3410     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3411     if (RExtOp0.getOpcode() == ISD::SUB &&
3412         RExtOp0.getOperand(1) == LExtOp0) {
3413       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3414       //   (rotl x, y)
3415       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3416       //   (rotr x, (sub 32, y))
3417       if (ConstantSDNode *SUBC =
3418             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0)))
3419         if (SUBC->getAPIntValue() == OpSizeInBits)
3420           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3421                              LHSShiftArg,
3422                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3423     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3424                RExtOp0 == LExtOp0.getOperand(1)) {
3425       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3426       //   (rotr x, y)
3427       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3428       //   (rotl x, (sub 32, y))
3429       if (ConstantSDNode *SUBC =
3430             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0)))
3431         if (SUBC->getAPIntValue() == OpSizeInBits)
3432           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3433                              LHSShiftArg,
3434                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3435     }
3436   }
3437
3438   return 0;
3439 }
3440
3441 SDValue DAGCombiner::visitXOR(SDNode *N) {
3442   SDValue N0 = N->getOperand(0);
3443   SDValue N1 = N->getOperand(1);
3444   SDValue LHS, RHS, CC;
3445   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3446   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3447   EVT VT = N0.getValueType();
3448
3449   // fold vector ops
3450   if (VT.isVector()) {
3451     SDValue FoldedVOp = SimplifyVBinOp(N);
3452     if (FoldedVOp.getNode()) return FoldedVOp;
3453
3454     // fold (xor x, 0) -> x, vector edition
3455     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3456       return N1;
3457     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3458       return N0;
3459   }
3460
3461   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3462   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3463     return DAG.getConstant(0, VT);
3464   // fold (xor x, undef) -> undef
3465   if (N0.getOpcode() == ISD::UNDEF)
3466     return N0;
3467   if (N1.getOpcode() == ISD::UNDEF)
3468     return N1;
3469   // fold (xor c1, c2) -> c1^c2
3470   if (N0C && N1C)
3471     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3472   // canonicalize constant to RHS
3473   if (N0C && !N1C)
3474     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3475   // fold (xor x, 0) -> x
3476   if (N1C && N1C->isNullValue())
3477     return N0;
3478   // reassociate xor
3479   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3480   if (RXOR.getNode() != 0)
3481     return RXOR;
3482
3483   // fold !(x cc y) -> (x !cc y)
3484   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3485     bool isInt = LHS.getValueType().isInteger();
3486     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3487                                                isInt);
3488
3489     if (!LegalOperations ||
3490         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3491       switch (N0.getOpcode()) {
3492       default:
3493         llvm_unreachable("Unhandled SetCC Equivalent!");
3494       case ISD::SETCC:
3495         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3496       case ISD::SELECT_CC:
3497         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3498                                N0.getOperand(3), NotCC);
3499       }
3500     }
3501   }
3502
3503   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3504   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3505       N0.getNode()->hasOneUse() &&
3506       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3507     SDValue V = N0.getOperand(0);
3508     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3509                     DAG.getConstant(1, V.getValueType()));
3510     AddToWorkList(V.getNode());
3511     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3512   }
3513
3514   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3515   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3516       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3517     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3518     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3519       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3520       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3521       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3522       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3523       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3524     }
3525   }
3526   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3527   if (N1C && N1C->isAllOnesValue() &&
3528       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3529     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3530     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3531       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3532       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3533       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3534       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3535       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3536     }
3537   }
3538   // fold (xor (and x, y), y) -> (and (not x), y)
3539   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3540       N0->getOperand(1) == N1) {
3541     SDValue X = N0->getOperand(0);
3542     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3543     AddToWorkList(NotX.getNode());
3544     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3545   }
3546   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3547   if (N1C && N0.getOpcode() == ISD::XOR) {
3548     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3549     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3550     if (N00C)
3551       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3552                          DAG.getConstant(N1C->getAPIntValue() ^
3553                                          N00C->getAPIntValue(), VT));
3554     if (N01C)
3555       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3556                          DAG.getConstant(N1C->getAPIntValue() ^
3557                                          N01C->getAPIntValue(), VT));
3558   }
3559   // fold (xor x, x) -> 0
3560   if (N0 == N1)
3561     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3562
3563   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3564   if (N0.getOpcode() == N1.getOpcode()) {
3565     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3566     if (Tmp.getNode()) return Tmp;
3567   }
3568
3569   // Simplify the expression using non-local knowledge.
3570   if (!VT.isVector() &&
3571       SimplifyDemandedBits(SDValue(N, 0)))
3572     return SDValue(N, 0);
3573
3574   return SDValue();
3575 }
3576
3577 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3578 /// the shift amount is a constant.
3579 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3580   SDNode *LHS = N->getOperand(0).getNode();
3581   if (!LHS->hasOneUse()) return SDValue();
3582
3583   // We want to pull some binops through shifts, so that we have (and (shift))
3584   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3585   // thing happens with address calculations, so it's important to canonicalize
3586   // it.
3587   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3588
3589   switch (LHS->getOpcode()) {
3590   default: return SDValue();
3591   case ISD::OR:
3592   case ISD::XOR:
3593     HighBitSet = false; // We can only transform sra if the high bit is clear.
3594     break;
3595   case ISD::AND:
3596     HighBitSet = true;  // We can only transform sra if the high bit is set.
3597     break;
3598   case ISD::ADD:
3599     if (N->getOpcode() != ISD::SHL)
3600       return SDValue(); // only shl(add) not sr[al](add).
3601     HighBitSet = false; // We can only transform sra if the high bit is clear.
3602     break;
3603   }
3604
3605   // We require the RHS of the binop to be a constant as well.
3606   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3607   if (!BinOpCst) return SDValue();
3608
3609   // FIXME: disable this unless the input to the binop is a shift by a constant.
3610   // If it is not a shift, it pessimizes some common cases like:
3611   //
3612   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3613   //    int bar(int *X, int i) { return X[i & 255]; }
3614   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3615   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3616        BinOpLHSVal->getOpcode() != ISD::SRA &&
3617        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3618       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3619     return SDValue();
3620
3621   EVT VT = N->getValueType(0);
3622
3623   // If this is a signed shift right, and the high bit is modified by the
3624   // logical operation, do not perform the transformation. The highBitSet
3625   // boolean indicates the value of the high bit of the constant which would
3626   // cause it to be modified for this operation.
3627   if (N->getOpcode() == ISD::SRA) {
3628     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3629     if (BinOpRHSSignSet != HighBitSet)
3630       return SDValue();
3631   }
3632
3633   // Fold the constants, shifting the binop RHS by the shift amount.
3634   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3635                                N->getValueType(0),
3636                                LHS->getOperand(1), N->getOperand(1));
3637
3638   // Create the new shift.
3639   SDValue NewShift = DAG.getNode(N->getOpcode(),
3640                                  SDLoc(LHS->getOperand(0)),
3641                                  VT, LHS->getOperand(0), N->getOperand(1));
3642
3643   // Create the new binop.
3644   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3645 }
3646
3647 SDValue DAGCombiner::visitSHL(SDNode *N) {
3648   SDValue N0 = N->getOperand(0);
3649   SDValue N1 = N->getOperand(1);
3650   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3651   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3652   EVT VT = N0.getValueType();
3653   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3654
3655   // fold (shl c1, c2) -> c1<<c2
3656   if (N0C && N1C)
3657     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3658   // fold (shl 0, x) -> 0
3659   if (N0C && N0C->isNullValue())
3660     return N0;
3661   // fold (shl x, c >= size(x)) -> undef
3662   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3663     return DAG.getUNDEF(VT);
3664   // fold (shl x, 0) -> x
3665   if (N1C && N1C->isNullValue())
3666     return N0;
3667   // fold (shl undef, x) -> 0
3668   if (N0.getOpcode() == ISD::UNDEF)
3669     return DAG.getConstant(0, VT);
3670   // if (shl x, c) is known to be zero, return 0
3671   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3672                             APInt::getAllOnesValue(OpSizeInBits)))
3673     return DAG.getConstant(0, VT);
3674   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3675   if (N1.getOpcode() == ISD::TRUNCATE &&
3676       N1.getOperand(0).getOpcode() == ISD::AND &&
3677       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3678     SDValue N101 = N1.getOperand(0).getOperand(1);
3679     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3680       EVT TruncVT = N1.getValueType();
3681       SDValue N100 = N1.getOperand(0).getOperand(0);
3682       APInt TruncC = N101C->getAPIntValue();
3683       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3684       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3685                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3686                                      DAG.getNode(ISD::TRUNCATE,
3687                                                  SDLoc(N),
3688                                                  TruncVT, N100),
3689                                      DAG.getConstant(TruncC, TruncVT)));
3690     }
3691   }
3692
3693   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3694     return SDValue(N, 0);
3695
3696   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3697   if (N1C && N0.getOpcode() == ISD::SHL &&
3698       N0.getOperand(1).getOpcode() == ISD::Constant) {
3699     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3700     uint64_t c2 = N1C->getZExtValue();
3701     if (c1 + c2 >= OpSizeInBits)
3702       return DAG.getConstant(0, VT);
3703     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3704                        DAG.getConstant(c1 + c2, N1.getValueType()));
3705   }
3706
3707   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3708   // For this to be valid, the second form must not preserve any of the bits
3709   // that are shifted out by the inner shift in the first form.  This means
3710   // the outer shift size must be >= the number of bits added by the ext.
3711   // As a corollary, we don't care what kind of ext it is.
3712   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3713               N0.getOpcode() == ISD::ANY_EXTEND ||
3714               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3715       N0.getOperand(0).getOpcode() == ISD::SHL &&
3716       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3717     uint64_t c1 =
3718       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3719     uint64_t c2 = N1C->getZExtValue();
3720     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3721     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3722     if (c2 >= OpSizeInBits - InnerShiftSize) {
3723       if (c1 + c2 >= OpSizeInBits)
3724         return DAG.getConstant(0, VT);
3725       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3726                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3727                                      N0.getOperand(0)->getOperand(0)),
3728                          DAG.getConstant(c1 + c2, N1.getValueType()));
3729     }
3730   }
3731
3732   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3733   //                               (and (srl x, (sub c1, c2), MASK)
3734   // Only fold this if the inner shift has no other uses -- if it does, folding
3735   // this will increase the total number of instructions.
3736   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3737       N0.getOperand(1).getOpcode() == ISD::Constant) {
3738     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3739     if (c1 < VT.getSizeInBits()) {
3740       uint64_t c2 = N1C->getZExtValue();
3741       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3742                                          VT.getSizeInBits() - c1);
3743       SDValue Shift;
3744       if (c2 > c1) {
3745         Mask = Mask.shl(c2-c1);
3746         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3747                             DAG.getConstant(c2-c1, N1.getValueType()));
3748       } else {
3749         Mask = Mask.lshr(c1-c2);
3750         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3751                             DAG.getConstant(c1-c2, N1.getValueType()));
3752       }
3753       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3754                          DAG.getConstant(Mask, VT));
3755     }
3756   }
3757   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3758   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3759     SDValue HiBitsMask =
3760       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3761                                             VT.getSizeInBits() -
3762                                               N1C->getZExtValue()),
3763                       VT);
3764     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3765                        HiBitsMask);
3766   }
3767
3768   if (N1C) {
3769     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3770     if (NewSHL.getNode())
3771       return NewSHL;
3772   }
3773
3774   return SDValue();
3775 }
3776
3777 SDValue DAGCombiner::visitSRA(SDNode *N) {
3778   SDValue N0 = N->getOperand(0);
3779   SDValue N1 = N->getOperand(1);
3780   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3781   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3782   EVT VT = N0.getValueType();
3783   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3784
3785   // fold (sra c1, c2) -> (sra c1, c2)
3786   if (N0C && N1C)
3787     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3788   // fold (sra 0, x) -> 0
3789   if (N0C && N0C->isNullValue())
3790     return N0;
3791   // fold (sra -1, x) -> -1
3792   if (N0C && N0C->isAllOnesValue())
3793     return N0;
3794   // fold (sra x, (setge c, size(x))) -> undef
3795   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3796     return DAG.getUNDEF(VT);
3797   // fold (sra x, 0) -> x
3798   if (N1C && N1C->isNullValue())
3799     return N0;
3800   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3801   // sext_inreg.
3802   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3803     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3804     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3805     if (VT.isVector())
3806       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3807                                ExtVT, VT.getVectorNumElements());
3808     if ((!LegalOperations ||
3809          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3810       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3811                          N0.getOperand(0), DAG.getValueType(ExtVT));
3812   }
3813
3814   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3815   if (N1C && N0.getOpcode() == ISD::SRA) {
3816     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3817       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3818       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3819       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3820                          DAG.getConstant(Sum, N1C->getValueType(0)));
3821     }
3822   }
3823
3824   // fold (sra (shl X, m), (sub result_size, n))
3825   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3826   // result_size - n != m.
3827   // If truncate is free for the target sext(shl) is likely to result in better
3828   // code.
3829   if (N0.getOpcode() == ISD::SHL) {
3830     // Get the two constanst of the shifts, CN0 = m, CN = n.
3831     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3832     if (N01C && N1C) {
3833       // Determine what the truncate's result bitsize and type would be.
3834       EVT TruncVT =
3835         EVT::getIntegerVT(*DAG.getContext(),
3836                           OpSizeInBits - N1C->getZExtValue());
3837       // Determine the residual right-shift amount.
3838       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3839
3840       // If the shift is not a no-op (in which case this should be just a sign
3841       // extend already), the truncated to type is legal, sign_extend is legal
3842       // on that type, and the truncate to that type is both legal and free,
3843       // perform the transform.
3844       if ((ShiftAmt > 0) &&
3845           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3846           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3847           TLI.isTruncateFree(VT, TruncVT)) {
3848
3849           SDValue Amt = DAG.getConstant(ShiftAmt,
3850               getShiftAmountTy(N0.getOperand(0).getValueType()));
3851           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3852                                       N0.getOperand(0), Amt);
3853           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3854                                       Shift);
3855           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3856                              N->getValueType(0), Trunc);
3857       }
3858     }
3859   }
3860
3861   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3862   if (N1.getOpcode() == ISD::TRUNCATE &&
3863       N1.getOperand(0).getOpcode() == ISD::AND &&
3864       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3865     SDValue N101 = N1.getOperand(0).getOperand(1);
3866     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3867       EVT TruncVT = N1.getValueType();
3868       SDValue N100 = N1.getOperand(0).getOperand(0);
3869       APInt TruncC = N101C->getAPIntValue();
3870       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3871       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3872                          DAG.getNode(ISD::AND, SDLoc(N),
3873                                      TruncVT,
3874                                      DAG.getNode(ISD::TRUNCATE,
3875                                                  SDLoc(N),
3876                                                  TruncVT, N100),
3877                                      DAG.getConstant(TruncC, TruncVT)));
3878     }
3879   }
3880
3881   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3882   //      if c1 is equal to the number of bits the trunc removes
3883   if (N0.getOpcode() == ISD::TRUNCATE &&
3884       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3885        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3886       N0.getOperand(0).hasOneUse() &&
3887       N0.getOperand(0).getOperand(1).hasOneUse() &&
3888       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3889     EVT LargeVT = N0.getOperand(0).getValueType();
3890     ConstantSDNode *LargeShiftAmt =
3891       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3892
3893     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3894         LargeShiftAmt->getZExtValue()) {
3895       SDValue Amt =
3896         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3897               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3898       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3899                                 N0.getOperand(0).getOperand(0), Amt);
3900       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3901     }
3902   }
3903
3904   // Simplify, based on bits shifted out of the LHS.
3905   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3906     return SDValue(N, 0);
3907
3908
3909   // If the sign bit is known to be zero, switch this to a SRL.
3910   if (DAG.SignBitIsZero(N0))
3911     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3912
3913   if (N1C) {
3914     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3915     if (NewSRA.getNode())
3916       return NewSRA;
3917   }
3918
3919   return SDValue();
3920 }
3921
3922 SDValue DAGCombiner::visitSRL(SDNode *N) {
3923   SDValue N0 = N->getOperand(0);
3924   SDValue N1 = N->getOperand(1);
3925   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3926   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3927   EVT VT = N0.getValueType();
3928   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3929
3930   // fold (srl c1, c2) -> c1 >>u c2
3931   if (N0C && N1C)
3932     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3933   // fold (srl 0, x) -> 0
3934   if (N0C && N0C->isNullValue())
3935     return N0;
3936   // fold (srl x, c >= size(x)) -> undef
3937   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3938     return DAG.getUNDEF(VT);
3939   // fold (srl x, 0) -> x
3940   if (N1C && N1C->isNullValue())
3941     return N0;
3942   // if (srl x, c) is known to be zero, return 0
3943   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3944                                    APInt::getAllOnesValue(OpSizeInBits)))
3945     return DAG.getConstant(0, VT);
3946
3947   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3948   if (N1C && N0.getOpcode() == ISD::SRL &&
3949       N0.getOperand(1).getOpcode() == ISD::Constant) {
3950     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3951     uint64_t c2 = N1C->getZExtValue();
3952     if (c1 + c2 >= OpSizeInBits)
3953       return DAG.getConstant(0, VT);
3954     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3955                        DAG.getConstant(c1 + c2, N1.getValueType()));
3956   }
3957
3958   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3959   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3960       N0.getOperand(0).getOpcode() == ISD::SRL &&
3961       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3962     uint64_t c1 =
3963       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3964     uint64_t c2 = N1C->getZExtValue();
3965     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3966     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3967     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3968     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3969     if (c1 + OpSizeInBits == InnerShiftSize) {
3970       if (c1 + c2 >= InnerShiftSize)
3971         return DAG.getConstant(0, VT);
3972       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3973                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3974                                      N0.getOperand(0)->getOperand(0),
3975                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3976     }
3977   }
3978
3979   // fold (srl (shl x, c), c) -> (and x, cst2)
3980   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3981       N0.getValueSizeInBits() <= 64) {
3982     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3983     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3984                        DAG.getConstant(~0ULL >> ShAmt, VT));
3985   }
3986
3987   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3988   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3989     // Shifting in all undef bits?
3990     EVT SmallVT = N0.getOperand(0).getValueType();
3991     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3992       return DAG.getUNDEF(VT);
3993
3994     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3995       uint64_t ShiftAmt = N1C->getZExtValue();
3996       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
3997                                        N0.getOperand(0),
3998                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3999       AddToWorkList(SmallShift.getNode());
4000       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4001       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4002                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4003                          DAG.getConstant(Mask, VT));
4004     }
4005   }
4006
4007   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4008   // bit, which is unmodified by sra.
4009   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4010     if (N0.getOpcode() == ISD::SRA)
4011       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4012   }
4013
4014   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4015   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4016       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4017     APInt KnownZero, KnownOne;
4018     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4019
4020     // If any of the input bits are KnownOne, then the input couldn't be all
4021     // zeros, thus the result of the srl will always be zero.
4022     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4023
4024     // If all of the bits input the to ctlz node are known to be zero, then
4025     // the result of the ctlz is "32" and the result of the shift is one.
4026     APInt UnknownBits = ~KnownZero;
4027     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4028
4029     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4030     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4031       // Okay, we know that only that the single bit specified by UnknownBits
4032       // could be set on input to the CTLZ node. If this bit is set, the SRL
4033       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4034       // to an SRL/XOR pair, which is likely to simplify more.
4035       unsigned ShAmt = UnknownBits.countTrailingZeros();
4036       SDValue Op = N0.getOperand(0);
4037
4038       if (ShAmt) {
4039         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4040                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4041         AddToWorkList(Op.getNode());
4042       }
4043
4044       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4045                          Op, DAG.getConstant(1, VT));
4046     }
4047   }
4048
4049   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4050   if (N1.getOpcode() == ISD::TRUNCATE &&
4051       N1.getOperand(0).getOpcode() == ISD::AND &&
4052       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4053     SDValue N101 = N1.getOperand(0).getOperand(1);
4054     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4055       EVT TruncVT = N1.getValueType();
4056       SDValue N100 = N1.getOperand(0).getOperand(0);
4057       APInt TruncC = N101C->getAPIntValue();
4058       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4059       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4060                          DAG.getNode(ISD::AND, SDLoc(N),
4061                                      TruncVT,
4062                                      DAG.getNode(ISD::TRUNCATE,
4063                                                  SDLoc(N),
4064                                                  TruncVT, N100),
4065                                      DAG.getConstant(TruncC, TruncVT)));
4066     }
4067   }
4068
4069   // fold operands of srl based on knowledge that the low bits are not
4070   // demanded.
4071   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4072     return SDValue(N, 0);
4073
4074   if (N1C) {
4075     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4076     if (NewSRL.getNode())
4077       return NewSRL;
4078   }
4079
4080   // Attempt to convert a srl of a load into a narrower zero-extending load.
4081   SDValue NarrowLoad = ReduceLoadWidth(N);
4082   if (NarrowLoad.getNode())
4083     return NarrowLoad;
4084
4085   // Here is a common situation. We want to optimize:
4086   //
4087   //   %a = ...
4088   //   %b = and i32 %a, 2
4089   //   %c = srl i32 %b, 1
4090   //   brcond i32 %c ...
4091   //
4092   // into
4093   //
4094   //   %a = ...
4095   //   %b = and %a, 2
4096   //   %c = setcc eq %b, 0
4097   //   brcond %c ...
4098   //
4099   // However when after the source operand of SRL is optimized into AND, the SRL
4100   // itself may not be optimized further. Look for it and add the BRCOND into
4101   // the worklist.
4102   if (N->hasOneUse()) {
4103     SDNode *Use = *N->use_begin();
4104     if (Use->getOpcode() == ISD::BRCOND)
4105       AddToWorkList(Use);
4106     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4107       // Also look pass the truncate.
4108       Use = *Use->use_begin();
4109       if (Use->getOpcode() == ISD::BRCOND)
4110         AddToWorkList(Use);
4111     }
4112   }
4113
4114   return SDValue();
4115 }
4116
4117 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4118   SDValue N0 = N->getOperand(0);
4119   EVT VT = N->getValueType(0);
4120
4121   // fold (ctlz c1) -> c2
4122   if (isa<ConstantSDNode>(N0))
4123     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4124   return SDValue();
4125 }
4126
4127 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4128   SDValue N0 = N->getOperand(0);
4129   EVT VT = N->getValueType(0);
4130
4131   // fold (ctlz_zero_undef c1) -> c2
4132   if (isa<ConstantSDNode>(N0))
4133     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4134   return SDValue();
4135 }
4136
4137 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4138   SDValue N0 = N->getOperand(0);
4139   EVT VT = N->getValueType(0);
4140
4141   // fold (cttz c1) -> c2
4142   if (isa<ConstantSDNode>(N0))
4143     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4144   return SDValue();
4145 }
4146
4147 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4148   SDValue N0 = N->getOperand(0);
4149   EVT VT = N->getValueType(0);
4150
4151   // fold (cttz_zero_undef c1) -> c2
4152   if (isa<ConstantSDNode>(N0))
4153     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4154   return SDValue();
4155 }
4156
4157 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4158   SDValue N0 = N->getOperand(0);
4159   EVT VT = N->getValueType(0);
4160
4161   // fold (ctpop c1) -> c2
4162   if (isa<ConstantSDNode>(N0))
4163     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4164   return SDValue();
4165 }
4166
4167 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4168   SDValue N0 = N->getOperand(0);
4169   SDValue N1 = N->getOperand(1);
4170   SDValue N2 = N->getOperand(2);
4171   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4172   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4173   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4174   EVT VT = N->getValueType(0);
4175   EVT VT0 = N0.getValueType();
4176
4177   // fold (select C, X, X) -> X
4178   if (N1 == N2)
4179     return N1;
4180   // fold (select true, X, Y) -> X
4181   if (N0C && !N0C->isNullValue())
4182     return N1;
4183   // fold (select false, X, Y) -> Y
4184   if (N0C && N0C->isNullValue())
4185     return N2;
4186   // fold (select C, 1, X) -> (or C, X)
4187   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4188     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4189   // fold (select C, 0, 1) -> (xor C, 1)
4190   if (VT.isInteger() &&
4191       (VT0 == MVT::i1 ||
4192        (VT0.isInteger() &&
4193         TLI.getBooleanContents(false) ==
4194         TargetLowering::ZeroOrOneBooleanContent)) &&
4195       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4196     SDValue XORNode;
4197     if (VT == VT0)
4198       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4199                          N0, DAG.getConstant(1, VT0));
4200     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4201                           N0, DAG.getConstant(1, VT0));
4202     AddToWorkList(XORNode.getNode());
4203     if (VT.bitsGT(VT0))
4204       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4205     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4206   }
4207   // fold (select C, 0, X) -> (and (not C), X)
4208   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4209     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4210     AddToWorkList(NOTNode.getNode());
4211     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4212   }
4213   // fold (select C, X, 1) -> (or (not C), X)
4214   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4215     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4216     AddToWorkList(NOTNode.getNode());
4217     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4218   }
4219   // fold (select C, X, 0) -> (and C, X)
4220   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4221     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4222   // fold (select X, X, Y) -> (or X, Y)
4223   // fold (select X, 1, Y) -> (or X, Y)
4224   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4225     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4226   // fold (select X, Y, X) -> (and X, Y)
4227   // fold (select X, Y, 0) -> (and X, Y)
4228   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4229     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4230
4231   // If we can fold this based on the true/false value, do so.
4232   if (SimplifySelectOps(N, N1, N2))
4233     return SDValue(N, 0);  // Don't revisit N.
4234
4235   // fold selects based on a setcc into other things, such as min/max/abs
4236   if (N0.getOpcode() == ISD::SETCC) {
4237     // FIXME:
4238     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4239     // having to say they don't support SELECT_CC on every type the DAG knows
4240     // about, since there is no way to mark an opcode illegal at all value types
4241     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4242         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4243       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4244                          N0.getOperand(0), N0.getOperand(1),
4245                          N1, N2, N0.getOperand(2));
4246     return SimplifySelect(SDLoc(N), N0, N1, N2);
4247   }
4248
4249   return SDValue();
4250 }
4251
4252 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4253   SDValue N0 = N->getOperand(0);
4254   SDValue N1 = N->getOperand(1);
4255   SDValue N2 = N->getOperand(2);
4256   SDLoc DL(N);
4257
4258   // Canonicalize integer abs.
4259   // vselect (setg[te] X,  0),  X, -X ->
4260   // vselect (setgt    X, -1),  X, -X ->
4261   // vselect (setl[te] X,  0), -X,  X ->
4262   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4263   if (N0.getOpcode() == ISD::SETCC) {
4264     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4265     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4266     bool isAbs = false;
4267     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4268
4269     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4270          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4271         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4272       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4273     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4274              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4275       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4276
4277     if (isAbs) {
4278       EVT VT = LHS.getValueType();
4279       SDValue Shift = DAG.getNode(
4280           ISD::SRA, DL, VT, LHS,
4281           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4282       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4283       AddToWorkList(Shift.getNode());
4284       AddToWorkList(Add.getNode());
4285       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4286     }
4287   }
4288
4289   return SDValue();
4290 }
4291
4292 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4293   SDValue N0 = N->getOperand(0);
4294   SDValue N1 = N->getOperand(1);
4295   SDValue N2 = N->getOperand(2);
4296   SDValue N3 = N->getOperand(3);
4297   SDValue N4 = N->getOperand(4);
4298   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4299
4300   // fold select_cc lhs, rhs, x, x, cc -> x
4301   if (N2 == N3)
4302     return N2;
4303
4304   // Determine if the condition we're dealing with is constant
4305   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4306                               N0, N1, CC, SDLoc(N), false);
4307   if (SCC.getNode()) {
4308     AddToWorkList(SCC.getNode());
4309
4310     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4311       if (!SCCC->isNullValue())
4312         return N2;    // cond always true -> true val
4313       else
4314         return N3;    // cond always false -> false val
4315     }
4316
4317     // Fold to a simpler select_cc
4318     if (SCC.getOpcode() == ISD::SETCC)
4319       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4320                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4321                          SCC.getOperand(2));
4322   }
4323
4324   // If we can fold this based on the true/false value, do so.
4325   if (SimplifySelectOps(N, N2, N3))
4326     return SDValue(N, 0);  // Don't revisit N.
4327
4328   // fold select_cc into other things, such as min/max/abs
4329   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4330 }
4331
4332 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4333   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4334                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4335                        SDLoc(N));
4336 }
4337
4338 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4339 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4340 // transformation. Returns true if extension are possible and the above
4341 // mentioned transformation is profitable.
4342 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4343                                     unsigned ExtOpc,
4344                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4345                                     const TargetLowering &TLI) {
4346   bool HasCopyToRegUses = false;
4347   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4348   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4349                             UE = N0.getNode()->use_end();
4350        UI != UE; ++UI) {
4351     SDNode *User = *UI;
4352     if (User == N)
4353       continue;
4354     if (UI.getUse().getResNo() != N0.getResNo())
4355       continue;
4356     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4357     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4358       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4359       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4360         // Sign bits will be lost after a zext.
4361         return false;
4362       bool Add = false;
4363       for (unsigned i = 0; i != 2; ++i) {
4364         SDValue UseOp = User->getOperand(i);
4365         if (UseOp == N0)
4366           continue;
4367         if (!isa<ConstantSDNode>(UseOp))
4368           return false;
4369         Add = true;
4370       }
4371       if (Add)
4372         ExtendNodes.push_back(User);
4373       continue;
4374     }
4375     // If truncates aren't free and there are users we can't
4376     // extend, it isn't worthwhile.
4377     if (!isTruncFree)
4378       return false;
4379     // Remember if this value is live-out.
4380     if (User->getOpcode() == ISD::CopyToReg)
4381       HasCopyToRegUses = true;
4382   }
4383
4384   if (HasCopyToRegUses) {
4385     bool BothLiveOut = false;
4386     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4387          UI != UE; ++UI) {
4388       SDUse &Use = UI.getUse();
4389       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4390         BothLiveOut = true;
4391         break;
4392       }
4393     }
4394     if (BothLiveOut)
4395       // Both unextended and extended values are live out. There had better be
4396       // a good reason for the transformation.
4397       return ExtendNodes.size();
4398   }
4399   return true;
4400 }
4401
4402 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4403                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4404                                   ISD::NodeType ExtType) {
4405   // Extend SetCC uses if necessary.
4406   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4407     SDNode *SetCC = SetCCs[i];
4408     SmallVector<SDValue, 4> Ops;
4409
4410     for (unsigned j = 0; j != 2; ++j) {
4411       SDValue SOp = SetCC->getOperand(j);
4412       if (SOp == Trunc)
4413         Ops.push_back(ExtLoad);
4414       else
4415         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4416     }
4417
4418     Ops.push_back(SetCC->getOperand(2));
4419     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4420                                  &Ops[0], Ops.size()));
4421   }
4422 }
4423
4424 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4425   SDValue N0 = N->getOperand(0);
4426   EVT VT = N->getValueType(0);
4427
4428   // fold (sext c1) -> c1
4429   if (isa<ConstantSDNode>(N0))
4430     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4431
4432   // fold (sext (sext x)) -> (sext x)
4433   // fold (sext (aext x)) -> (sext x)
4434   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4435     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4436                        N0.getOperand(0));
4437
4438   if (N0.getOpcode() == ISD::TRUNCATE) {
4439     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4440     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4441     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4442     if (NarrowLoad.getNode()) {
4443       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4444       if (NarrowLoad.getNode() != N0.getNode()) {
4445         CombineTo(N0.getNode(), NarrowLoad);
4446         // CombineTo deleted the truncate, if needed, but not what's under it.
4447         AddToWorkList(oye);
4448       }
4449       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4450     }
4451
4452     // See if the value being truncated is already sign extended.  If so, just
4453     // eliminate the trunc/sext pair.
4454     SDValue Op = N0.getOperand(0);
4455     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4456     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4457     unsigned DestBits = VT.getScalarType().getSizeInBits();
4458     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4459
4460     if (OpBits == DestBits) {
4461       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4462       // bits, it is already ready.
4463       if (NumSignBits > DestBits-MidBits)
4464         return Op;
4465     } else if (OpBits < DestBits) {
4466       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4467       // bits, just sext from i32.
4468       if (NumSignBits > OpBits-MidBits)
4469         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4470     } else {
4471       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4472       // bits, just truncate to i32.
4473       if (NumSignBits > OpBits-MidBits)
4474         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4475     }
4476
4477     // fold (sext (truncate x)) -> (sextinreg x).
4478     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4479                                                  N0.getValueType())) {
4480       if (OpBits < DestBits)
4481         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4482       else if (OpBits > DestBits)
4483         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4484       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4485                          DAG.getValueType(N0.getValueType()));
4486     }
4487   }
4488
4489   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4490   // None of the supported targets knows how to perform load and sign extend
4491   // on vectors in one instruction.  We only perform this transformation on
4492   // scalars.
4493   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4494       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4495        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4496     bool DoXform = true;
4497     SmallVector<SDNode*, 4> SetCCs;
4498     if (!N0.hasOneUse())
4499       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4500     if (DoXform) {
4501       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4502       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4503                                        LN0->getChain(),
4504                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4505                                        N0.getValueType(),
4506                                        LN0->isVolatile(), LN0->isNonTemporal(),
4507                                        LN0->getAlignment());
4508       CombineTo(N, ExtLoad);
4509       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4510                                   N0.getValueType(), ExtLoad);
4511       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4512       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4513                       ISD::SIGN_EXTEND);
4514       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4515     }
4516   }
4517
4518   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4519   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4520   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4521       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4522     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4523     EVT MemVT = LN0->getMemoryVT();
4524     if ((!LegalOperations && !LN0->isVolatile()) ||
4525         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4526       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4527                                        LN0->getChain(),
4528                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4529                                        MemVT,
4530                                        LN0->isVolatile(), LN0->isNonTemporal(),
4531                                        LN0->getAlignment());
4532       CombineTo(N, ExtLoad);
4533       CombineTo(N0.getNode(),
4534                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4535                             N0.getValueType(), ExtLoad),
4536                 ExtLoad.getValue(1));
4537       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4538     }
4539   }
4540
4541   // fold (sext (and/or/xor (load x), cst)) ->
4542   //      (and/or/xor (sextload x), (sext cst))
4543   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4544        N0.getOpcode() == ISD::XOR) &&
4545       isa<LoadSDNode>(N0.getOperand(0)) &&
4546       N0.getOperand(1).getOpcode() == ISD::Constant &&
4547       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4548       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4549     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4550     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4551       bool DoXform = true;
4552       SmallVector<SDNode*, 4> SetCCs;
4553       if (!N0.hasOneUse())
4554         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4555                                           SetCCs, TLI);
4556       if (DoXform) {
4557         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4558                                          LN0->getChain(), LN0->getBasePtr(),
4559                                          LN0->getPointerInfo(),
4560                                          LN0->getMemoryVT(),
4561                                          LN0->isVolatile(),
4562                                          LN0->isNonTemporal(),
4563                                          LN0->getAlignment());
4564         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4565         Mask = Mask.sext(VT.getSizeInBits());
4566         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4567                                   ExtLoad, DAG.getConstant(Mask, VT));
4568         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4569                                     SDLoc(N0.getOperand(0)),
4570                                     N0.getOperand(0).getValueType(), ExtLoad);
4571         CombineTo(N, And);
4572         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4573         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4574                         ISD::SIGN_EXTEND);
4575         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4576       }
4577     }
4578   }
4579
4580   if (N0.getOpcode() == ISD::SETCC) {
4581     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4582     // Only do this before legalize for now.
4583     if (VT.isVector() && !LegalOperations &&
4584         TLI.getBooleanContents(true) ==
4585           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4586       EVT N0VT = N0.getOperand(0).getValueType();
4587       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4588       // of the same size as the compared operands. Only optimize sext(setcc())
4589       // if this is the case.
4590       EVT SVT = getSetCCResultType(N0VT);
4591
4592       // We know that the # elements of the results is the same as the
4593       // # elements of the compare (and the # elements of the compare result
4594       // for that matter).  Check to see that they are the same size.  If so,
4595       // we know that the element size of the sext'd result matches the
4596       // element size of the compare operands.
4597       if (VT.getSizeInBits() == SVT.getSizeInBits())
4598         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4599                              N0.getOperand(1),
4600                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4601
4602       // If the desired elements are smaller or larger than the source
4603       // elements we can use a matching integer vector type and then
4604       // truncate/sign extend
4605       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4606       if (SVT == MatchingVectorType) {
4607         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4608                                N0.getOperand(0), N0.getOperand(1),
4609                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4610         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4611       }
4612     }
4613
4614     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4615     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4616     SDValue NegOne =
4617       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4618     SDValue SCC =
4619       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4620                        NegOne, DAG.getConstant(0, VT),
4621                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4622     if (SCC.getNode()) return SCC;
4623     if (!VT.isVector() &&
4624         (!LegalOperations ||
4625          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4626       return DAG.getSelect(SDLoc(N), VT,
4627                            DAG.getSetCC(SDLoc(N),
4628                                         getSetCCResultType(VT),
4629                                         N0.getOperand(0), N0.getOperand(1),
4630                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4631                            NegOne, DAG.getConstant(0, VT));
4632     }
4633   }
4634
4635   // fold (sext x) -> (zext x) if the sign bit is known zero.
4636   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4637       DAG.SignBitIsZero(N0))
4638     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4639
4640   return SDValue();
4641 }
4642
4643 // isTruncateOf - If N is a truncate of some other value, return true, record
4644 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4645 // This function computes KnownZero to avoid a duplicated call to
4646 // ComputeMaskedBits in the caller.
4647 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4648                          APInt &KnownZero) {
4649   APInt KnownOne;
4650   if (N->getOpcode() == ISD::TRUNCATE) {
4651     Op = N->getOperand(0);
4652     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4653     return true;
4654   }
4655
4656   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4657       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4658     return false;
4659
4660   SDValue Op0 = N->getOperand(0);
4661   SDValue Op1 = N->getOperand(1);
4662   assert(Op0.getValueType() == Op1.getValueType());
4663
4664   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4665   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4666   if (COp0 && COp0->isNullValue())
4667     Op = Op1;
4668   else if (COp1 && COp1->isNullValue())
4669     Op = Op0;
4670   else
4671     return false;
4672
4673   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4674
4675   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4676     return false;
4677
4678   return true;
4679 }
4680
4681 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4682   SDValue N0 = N->getOperand(0);
4683   EVT VT = N->getValueType(0);
4684
4685   // fold (zext c1) -> c1
4686   if (isa<ConstantSDNode>(N0))
4687     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4688   // fold (zext (zext x)) -> (zext x)
4689   // fold (zext (aext x)) -> (zext x)
4690   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4691     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4692                        N0.getOperand(0));
4693
4694   // fold (zext (truncate x)) -> (zext x) or
4695   //      (zext (truncate x)) -> (truncate x)
4696   // This is valid when the truncated bits of x are already zero.
4697   // FIXME: We should extend this to work for vectors too.
4698   SDValue Op;
4699   APInt KnownZero;
4700   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4701     APInt TruncatedBits =
4702       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4703       APInt(Op.getValueSizeInBits(), 0) :
4704       APInt::getBitsSet(Op.getValueSizeInBits(),
4705                         N0.getValueSizeInBits(),
4706                         std::min(Op.getValueSizeInBits(),
4707                                  VT.getSizeInBits()));
4708     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4709       if (VT.bitsGT(Op.getValueType()))
4710         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4711       if (VT.bitsLT(Op.getValueType()))
4712         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4713
4714       return Op;
4715     }
4716   }
4717
4718   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4719   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4720   if (N0.getOpcode() == ISD::TRUNCATE) {
4721     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4722     if (NarrowLoad.getNode()) {
4723       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4724       if (NarrowLoad.getNode() != N0.getNode()) {
4725         CombineTo(N0.getNode(), NarrowLoad);
4726         // CombineTo deleted the truncate, if needed, but not what's under it.
4727         AddToWorkList(oye);
4728       }
4729       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4730     }
4731   }
4732
4733   // fold (zext (truncate x)) -> (and x, mask)
4734   if (N0.getOpcode() == ISD::TRUNCATE &&
4735       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4736
4737     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4738     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4739     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4740     if (NarrowLoad.getNode()) {
4741       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4742       if (NarrowLoad.getNode() != N0.getNode()) {
4743         CombineTo(N0.getNode(), NarrowLoad);
4744         // CombineTo deleted the truncate, if needed, but not what's under it.
4745         AddToWorkList(oye);
4746       }
4747       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4748     }
4749
4750     SDValue Op = N0.getOperand(0);
4751     if (Op.getValueType().bitsLT(VT)) {
4752       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4753       AddToWorkList(Op.getNode());
4754     } else if (Op.getValueType().bitsGT(VT)) {
4755       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4756       AddToWorkList(Op.getNode());
4757     }
4758     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4759                                   N0.getValueType().getScalarType());
4760   }
4761
4762   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4763   // if either of the casts is not free.
4764   if (N0.getOpcode() == ISD::AND &&
4765       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4766       N0.getOperand(1).getOpcode() == ISD::Constant &&
4767       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4768                            N0.getValueType()) ||
4769        !TLI.isZExtFree(N0.getValueType(), VT))) {
4770     SDValue X = N0.getOperand(0).getOperand(0);
4771     if (X.getValueType().bitsLT(VT)) {
4772       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4773     } else if (X.getValueType().bitsGT(VT)) {
4774       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4775     }
4776     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4777     Mask = Mask.zext(VT.getSizeInBits());
4778     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4779                        X, DAG.getConstant(Mask, VT));
4780   }
4781
4782   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4783   // None of the supported targets knows how to perform load and vector_zext
4784   // on vectors in one instruction.  We only perform this transformation on
4785   // scalars.
4786   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4787       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4788        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4789     bool DoXform = true;
4790     SmallVector<SDNode*, 4> SetCCs;
4791     if (!N0.hasOneUse())
4792       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4793     if (DoXform) {
4794       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4795       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4796                                        LN0->getChain(),
4797                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4798                                        N0.getValueType(),
4799                                        LN0->isVolatile(), LN0->isNonTemporal(),
4800                                        LN0->getAlignment());
4801       CombineTo(N, ExtLoad);
4802       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4803                                   N0.getValueType(), ExtLoad);
4804       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4805
4806       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4807                       ISD::ZERO_EXTEND);
4808       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4809     }
4810   }
4811
4812   // fold (zext (and/or/xor (load x), cst)) ->
4813   //      (and/or/xor (zextload x), (zext cst))
4814   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4815        N0.getOpcode() == ISD::XOR) &&
4816       isa<LoadSDNode>(N0.getOperand(0)) &&
4817       N0.getOperand(1).getOpcode() == ISD::Constant &&
4818       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4819       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4820     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4821     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4822       bool DoXform = true;
4823       SmallVector<SDNode*, 4> SetCCs;
4824       if (!N0.hasOneUse())
4825         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4826                                           SetCCs, TLI);
4827       if (DoXform) {
4828         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4829                                          LN0->getChain(), LN0->getBasePtr(),
4830                                          LN0->getPointerInfo(),
4831                                          LN0->getMemoryVT(),
4832                                          LN0->isVolatile(),
4833                                          LN0->isNonTemporal(),
4834                                          LN0->getAlignment());
4835         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4836         Mask = Mask.zext(VT.getSizeInBits());
4837         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4838                                   ExtLoad, DAG.getConstant(Mask, VT));
4839         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4840                                     SDLoc(N0.getOperand(0)),
4841                                     N0.getOperand(0).getValueType(), ExtLoad);
4842         CombineTo(N, And);
4843         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4844         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4845                         ISD::ZERO_EXTEND);
4846         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4847       }
4848     }
4849   }
4850
4851   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4852   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4853   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4854       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4855     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4856     EVT MemVT = LN0->getMemoryVT();
4857     if ((!LegalOperations && !LN0->isVolatile()) ||
4858         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4859       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4860                                        LN0->getChain(),
4861                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4862                                        MemVT,
4863                                        LN0->isVolatile(), LN0->isNonTemporal(),
4864                                        LN0->getAlignment());
4865       CombineTo(N, ExtLoad);
4866       CombineTo(N0.getNode(),
4867                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4868                             ExtLoad),
4869                 ExtLoad.getValue(1));
4870       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4871     }
4872   }
4873
4874   if (N0.getOpcode() == ISD::SETCC) {
4875     if (!LegalOperations && VT.isVector()) {
4876       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4877       // Only do this before legalize for now.
4878       EVT N0VT = N0.getOperand(0).getValueType();
4879       EVT EltVT = VT.getVectorElementType();
4880       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4881                                     DAG.getConstant(1, EltVT));
4882       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4883         // We know that the # elements of the results is the same as the
4884         // # elements of the compare (and the # elements of the compare result
4885         // for that matter).  Check to see that they are the same size.  If so,
4886         // we know that the element size of the sext'd result matches the
4887         // element size of the compare operands.
4888         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4889                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4890                                          N0.getOperand(1),
4891                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4892                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4893                                        &OneOps[0], OneOps.size()));
4894
4895       // If the desired elements are smaller or larger than the source
4896       // elements we can use a matching integer vector type and then
4897       // truncate/sign extend
4898       EVT MatchingElementType =
4899         EVT::getIntegerVT(*DAG.getContext(),
4900                           N0VT.getScalarType().getSizeInBits());
4901       EVT MatchingVectorType =
4902         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4903                          N0VT.getVectorNumElements());
4904       SDValue VsetCC =
4905         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4906                       N0.getOperand(1),
4907                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4908       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4909                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4910                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4911                                      &OneOps[0], OneOps.size()));
4912     }
4913
4914     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4915     SDValue SCC =
4916       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4917                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4918                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4919     if (SCC.getNode()) return SCC;
4920   }
4921
4922   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4923   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4924       isa<ConstantSDNode>(N0.getOperand(1)) &&
4925       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4926       N0.hasOneUse()) {
4927     SDValue ShAmt = N0.getOperand(1);
4928     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4929     if (N0.getOpcode() == ISD::SHL) {
4930       SDValue InnerZExt = N0.getOperand(0);
4931       // If the original shl may be shifting out bits, do not perform this
4932       // transformation.
4933       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4934         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4935       if (ShAmtVal > KnownZeroBits)
4936         return SDValue();
4937     }
4938
4939     SDLoc DL(N);
4940
4941     // Ensure that the shift amount is wide enough for the shifted value.
4942     if (VT.getSizeInBits() >= 256)
4943       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4944
4945     return DAG.getNode(N0.getOpcode(), DL, VT,
4946                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4947                        ShAmt);
4948   }
4949
4950   return SDValue();
4951 }
4952
4953 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4954   SDValue N0 = N->getOperand(0);
4955   EVT VT = N->getValueType(0);
4956
4957   // fold (aext c1) -> c1
4958   if (isa<ConstantSDNode>(N0))
4959     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4960   // fold (aext (aext x)) -> (aext x)
4961   // fold (aext (zext x)) -> (zext x)
4962   // fold (aext (sext x)) -> (sext x)
4963   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4964       N0.getOpcode() == ISD::ZERO_EXTEND ||
4965       N0.getOpcode() == ISD::SIGN_EXTEND)
4966     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4967
4968   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4969   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4970   if (N0.getOpcode() == ISD::TRUNCATE) {
4971     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4972     if (NarrowLoad.getNode()) {
4973       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4974       if (NarrowLoad.getNode() != N0.getNode()) {
4975         CombineTo(N0.getNode(), NarrowLoad);
4976         // CombineTo deleted the truncate, if needed, but not what's under it.
4977         AddToWorkList(oye);
4978       }
4979       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4980     }
4981   }
4982
4983   // fold (aext (truncate x))
4984   if (N0.getOpcode() == ISD::TRUNCATE) {
4985     SDValue TruncOp = N0.getOperand(0);
4986     if (TruncOp.getValueType() == VT)
4987       return TruncOp; // x iff x size == zext size.
4988     if (TruncOp.getValueType().bitsGT(VT))
4989       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4990     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4991   }
4992
4993   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4994   // if the trunc is not free.
4995   if (N0.getOpcode() == ISD::AND &&
4996       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4997       N0.getOperand(1).getOpcode() == ISD::Constant &&
4998       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4999                           N0.getValueType())) {
5000     SDValue X = N0.getOperand(0).getOperand(0);
5001     if (X.getValueType().bitsLT(VT)) {
5002       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5003     } else if (X.getValueType().bitsGT(VT)) {
5004       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5005     }
5006     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5007     Mask = Mask.zext(VT.getSizeInBits());
5008     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5009                        X, DAG.getConstant(Mask, VT));
5010   }
5011
5012   // fold (aext (load x)) -> (aext (truncate (extload x)))
5013   // None of the supported targets knows how to perform load and any_ext
5014   // on vectors in one instruction.  We only perform this transformation on
5015   // scalars.
5016   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5017       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5018        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5019     bool DoXform = true;
5020     SmallVector<SDNode*, 4> SetCCs;
5021     if (!N0.hasOneUse())
5022       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5023     if (DoXform) {
5024       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5025       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5026                                        LN0->getChain(),
5027                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5028                                        N0.getValueType(),
5029                                        LN0->isVolatile(), LN0->isNonTemporal(),
5030                                        LN0->getAlignment());
5031       CombineTo(N, ExtLoad);
5032       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5033                                   N0.getValueType(), ExtLoad);
5034       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5035       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5036                       ISD::ANY_EXTEND);
5037       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5038     }
5039   }
5040
5041   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5042   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5043   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5044   if (N0.getOpcode() == ISD::LOAD &&
5045       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5046       N0.hasOneUse()) {
5047     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5048     EVT MemVT = LN0->getMemoryVT();
5049     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5050                                      VT, LN0->getChain(), LN0->getBasePtr(),
5051                                      LN0->getPointerInfo(), MemVT,
5052                                      LN0->isVolatile(), LN0->isNonTemporal(),
5053                                      LN0->getAlignment());
5054     CombineTo(N, ExtLoad);
5055     CombineTo(N0.getNode(),
5056               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5057                           N0.getValueType(), ExtLoad),
5058               ExtLoad.getValue(1));
5059     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5060   }
5061
5062   if (N0.getOpcode() == ISD::SETCC) {
5063     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5064     // Only do this before legalize for now.
5065     if (VT.isVector() && !LegalOperations) {
5066       EVT N0VT = N0.getOperand(0).getValueType();
5067         // We know that the # elements of the results is the same as the
5068         // # elements of the compare (and the # elements of the compare result
5069         // for that matter).  Check to see that they are the same size.  If so,
5070         // we know that the element size of the sext'd result matches the
5071         // element size of the compare operands.
5072       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5073         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5074                              N0.getOperand(1),
5075                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5076       // If the desired elements are smaller or larger than the source
5077       // elements we can use a matching integer vector type and then
5078       // truncate/sign extend
5079       else {
5080         EVT MatchingElementType =
5081           EVT::getIntegerVT(*DAG.getContext(),
5082                             N0VT.getScalarType().getSizeInBits());
5083         EVT MatchingVectorType =
5084           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5085                            N0VT.getVectorNumElements());
5086         SDValue VsetCC =
5087           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5088                         N0.getOperand(1),
5089                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5090         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5091       }
5092     }
5093
5094     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5095     SDValue SCC =
5096       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5097                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5098                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5099     if (SCC.getNode())
5100       return SCC;
5101   }
5102
5103   return SDValue();
5104 }
5105
5106 /// GetDemandedBits - See if the specified operand can be simplified with the
5107 /// knowledge that only the bits specified by Mask are used.  If so, return the
5108 /// simpler operand, otherwise return a null SDValue.
5109 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5110   switch (V.getOpcode()) {
5111   default: break;
5112   case ISD::Constant: {
5113     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5114     assert(CV != 0 && "Const value should be ConstSDNode.");
5115     const APInt &CVal = CV->getAPIntValue();
5116     APInt NewVal = CVal & Mask;
5117     if (NewVal != CVal)
5118       return DAG.getConstant(NewVal, V.getValueType());
5119     break;
5120   }
5121   case ISD::OR:
5122   case ISD::XOR:
5123     // If the LHS or RHS don't contribute bits to the or, drop them.
5124     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5125       return V.getOperand(1);
5126     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5127       return V.getOperand(0);
5128     break;
5129   case ISD::SRL:
5130     // Only look at single-use SRLs.
5131     if (!V.getNode()->hasOneUse())
5132       break;
5133     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5134       // See if we can recursively simplify the LHS.
5135       unsigned Amt = RHSC->getZExtValue();
5136
5137       // Watch out for shift count overflow though.
5138       if (Amt >= Mask.getBitWidth()) break;
5139       APInt NewMask = Mask << Amt;
5140       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5141       if (SimplifyLHS.getNode())
5142         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5143                            SimplifyLHS, V.getOperand(1));
5144     }
5145   }
5146   return SDValue();
5147 }
5148
5149 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5150 /// bits and then truncated to a narrower type and where N is a multiple
5151 /// of number of bits of the narrower type, transform it to a narrower load
5152 /// from address + N / num of bits of new type. If the result is to be
5153 /// extended, also fold the extension to form a extending load.
5154 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5155   unsigned Opc = N->getOpcode();
5156
5157   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5158   SDValue N0 = N->getOperand(0);
5159   EVT VT = N->getValueType(0);
5160   EVT ExtVT = VT;
5161
5162   // This transformation isn't valid for vector loads.
5163   if (VT.isVector())
5164     return SDValue();
5165
5166   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5167   // extended to VT.
5168   if (Opc == ISD::SIGN_EXTEND_INREG) {
5169     ExtType = ISD::SEXTLOAD;
5170     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5171   } else if (Opc == ISD::SRL) {
5172     // Another special-case: SRL is basically zero-extending a narrower value.
5173     ExtType = ISD::ZEXTLOAD;
5174     N0 = SDValue(N, 0);
5175     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5176     if (!N01) return SDValue();
5177     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5178                               VT.getSizeInBits() - N01->getZExtValue());
5179   }
5180   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5181     return SDValue();
5182
5183   unsigned EVTBits = ExtVT.getSizeInBits();
5184
5185   // Do not generate loads of non-round integer types since these can
5186   // be expensive (and would be wrong if the type is not byte sized).
5187   if (!ExtVT.isRound())
5188     return SDValue();
5189
5190   unsigned ShAmt = 0;
5191   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5192     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5193       ShAmt = N01->getZExtValue();
5194       // Is the shift amount a multiple of size of VT?
5195       if ((ShAmt & (EVTBits-1)) == 0) {
5196         N0 = N0.getOperand(0);
5197         // Is the load width a multiple of size of VT?
5198         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5199           return SDValue();
5200       }
5201
5202       // At this point, we must have a load or else we can't do the transform.
5203       if (!isa<LoadSDNode>(N0)) return SDValue();
5204
5205       // Because a SRL must be assumed to *need* to zero-extend the high bits
5206       // (as opposed to anyext the high bits), we can't combine the zextload
5207       // lowering of SRL and an sextload.
5208       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5209         return SDValue();
5210
5211       // If the shift amount is larger than the input type then we're not
5212       // accessing any of the loaded bytes.  If the load was a zextload/extload
5213       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5214       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5215         return SDValue();
5216     }
5217   }
5218
5219   // If the load is shifted left (and the result isn't shifted back right),
5220   // we can fold the truncate through the shift.
5221   unsigned ShLeftAmt = 0;
5222   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5223       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5224     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5225       ShLeftAmt = N01->getZExtValue();
5226       N0 = N0.getOperand(0);
5227     }
5228   }
5229
5230   // If we haven't found a load, we can't narrow it.  Don't transform one with
5231   // multiple uses, this would require adding a new load.
5232   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5233     return SDValue();
5234
5235   // Don't change the width of a volatile load.
5236   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5237   if (LN0->isVolatile())
5238     return SDValue();
5239
5240   // Verify that we are actually reducing a load width here.
5241   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5242     return SDValue();
5243
5244   // For the transform to be legal, the load must produce only two values
5245   // (the value loaded and the chain).  Don't transform a pre-increment
5246   // load, for example, which produces an extra value.  Otherwise the
5247   // transformation is not equivalent, and the downstream logic to replace
5248   // uses gets things wrong.
5249   if (LN0->getNumValues() > 2)
5250     return SDValue();
5251
5252   // If the load that we're shrinking is an extload and we're not just
5253   // discarding the extension we can't simply shrink the load. Bail.
5254   // TODO: It would be possible to merge the extensions in some cases.
5255   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5256       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5257     return SDValue();
5258
5259   EVT PtrType = N0.getOperand(1).getValueType();
5260
5261   if (PtrType == MVT::Untyped || PtrType.isExtended())
5262     // It's not possible to generate a constant of extended or untyped type.
5263     return SDValue();
5264
5265   // For big endian targets, we need to adjust the offset to the pointer to
5266   // load the correct bytes.
5267   if (TLI.isBigEndian()) {
5268     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5269     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5270     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5271   }
5272
5273   uint64_t PtrOff = ShAmt / 8;
5274   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5275   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5276                                PtrType, LN0->getBasePtr(),
5277                                DAG.getConstant(PtrOff, PtrType));
5278   AddToWorkList(NewPtr.getNode());
5279
5280   SDValue Load;
5281   if (ExtType == ISD::NON_EXTLOAD)
5282     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5283                         LN0->getPointerInfo().getWithOffset(PtrOff),
5284                         LN0->isVolatile(), LN0->isNonTemporal(),
5285                         LN0->isInvariant(), NewAlign);
5286   else
5287     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5288                           LN0->getPointerInfo().getWithOffset(PtrOff),
5289                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5290                           NewAlign);
5291
5292   // Replace the old load's chain with the new load's chain.
5293   WorkListRemover DeadNodes(*this);
5294   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5295
5296   // Shift the result left, if we've swallowed a left shift.
5297   SDValue Result = Load;
5298   if (ShLeftAmt != 0) {
5299     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5300     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5301       ShImmTy = VT;
5302     // If the shift amount is as large as the result size (but, presumably,
5303     // no larger than the source) then the useful bits of the result are
5304     // zero; we can't simply return the shortened shift, because the result
5305     // of that operation is undefined.
5306     if (ShLeftAmt >= VT.getSizeInBits())
5307       Result = DAG.getConstant(0, VT);
5308     else
5309       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5310                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5311   }
5312
5313   // Return the new loaded value.
5314   return Result;
5315 }
5316
5317 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5318   SDValue N0 = N->getOperand(0);
5319   SDValue N1 = N->getOperand(1);
5320   EVT VT = N->getValueType(0);
5321   EVT EVT = cast<VTSDNode>(N1)->getVT();
5322   unsigned VTBits = VT.getScalarType().getSizeInBits();
5323   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5324
5325   // fold (sext_in_reg c1) -> c1
5326   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5327     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5328
5329   // If the input is already sign extended, just drop the extension.
5330   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5331     return N0;
5332
5333   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5334   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5335       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5336     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5337                        N0.getOperand(0), N1);
5338
5339   // fold (sext_in_reg (sext x)) -> (sext x)
5340   // fold (sext_in_reg (aext x)) -> (sext x)
5341   // if x is small enough.
5342   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5343     SDValue N00 = N0.getOperand(0);
5344     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5345         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5346       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5347   }
5348
5349   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5350   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5351     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5352
5353   // fold operands of sext_in_reg based on knowledge that the top bits are not
5354   // demanded.
5355   if (SimplifyDemandedBits(SDValue(N, 0)))
5356     return SDValue(N, 0);
5357
5358   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5359   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5360   SDValue NarrowLoad = ReduceLoadWidth(N);
5361   if (NarrowLoad.getNode())
5362     return NarrowLoad;
5363
5364   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5365   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5366   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5367   if (N0.getOpcode() == ISD::SRL) {
5368     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5369       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5370         // We can turn this into an SRA iff the input to the SRL is already sign
5371         // extended enough.
5372         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5373         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5374           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5375                              N0.getOperand(0), N0.getOperand(1));
5376       }
5377   }
5378
5379   // fold (sext_inreg (extload x)) -> (sextload x)
5380   if (ISD::isEXTLoad(N0.getNode()) &&
5381       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5382       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5383       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5384        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5385     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5386     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5387                                      LN0->getChain(),
5388                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5389                                      EVT,
5390                                      LN0->isVolatile(), LN0->isNonTemporal(),
5391                                      LN0->getAlignment());
5392     CombineTo(N, ExtLoad);
5393     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5394     AddToWorkList(ExtLoad.getNode());
5395     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5396   }
5397   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5398   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5399       N0.hasOneUse() &&
5400       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5401       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5402        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5403     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5404     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5405                                      LN0->getChain(),
5406                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5407                                      EVT,
5408                                      LN0->isVolatile(), LN0->isNonTemporal(),
5409                                      LN0->getAlignment());
5410     CombineTo(N, ExtLoad);
5411     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5412     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5413   }
5414
5415   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5416   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5417     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5418                                        N0.getOperand(1), false);
5419     if (BSwap.getNode() != 0)
5420       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5421                          BSwap, N1);
5422   }
5423
5424   return SDValue();
5425 }
5426
5427 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5428   SDValue N0 = N->getOperand(0);
5429   EVT VT = N->getValueType(0);
5430   bool isLE = TLI.isLittleEndian();
5431
5432   // noop truncate
5433   if (N0.getValueType() == N->getValueType(0))
5434     return N0;
5435   // fold (truncate c1) -> c1
5436   if (isa<ConstantSDNode>(N0))
5437     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5438   // fold (truncate (truncate x)) -> (truncate x)
5439   if (N0.getOpcode() == ISD::TRUNCATE)
5440     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5441   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5442   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5443       N0.getOpcode() == ISD::SIGN_EXTEND ||
5444       N0.getOpcode() == ISD::ANY_EXTEND) {
5445     if (N0.getOperand(0).getValueType().bitsLT(VT))
5446       // if the source is smaller than the dest, we still need an extend
5447       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5448                          N0.getOperand(0));
5449     if (N0.getOperand(0).getValueType().bitsGT(VT))
5450       // if the source is larger than the dest, than we just need the truncate
5451       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5452     // if the source and dest are the same type, we can drop both the extend
5453     // and the truncate.
5454     return N0.getOperand(0);
5455   }
5456
5457   // Fold extract-and-trunc into a narrow extract. For example:
5458   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5459   //   i32 y = TRUNCATE(i64 x)
5460   //        -- becomes --
5461   //   v16i8 b = BITCAST (v2i64 val)
5462   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5463   //
5464   // Note: We only run this optimization after type legalization (which often
5465   // creates this pattern) and before operation legalization after which
5466   // we need to be more careful about the vector instructions that we generate.
5467   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5468       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5469
5470     EVT VecTy = N0.getOperand(0).getValueType();
5471     EVT ExTy = N0.getValueType();
5472     EVT TrTy = N->getValueType(0);
5473
5474     unsigned NumElem = VecTy.getVectorNumElements();
5475     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5476
5477     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5478     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5479
5480     SDValue EltNo = N0->getOperand(1);
5481     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5482       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5483       EVT IndexTy = TLI.getVectorIdxTy();
5484       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5485
5486       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5487                               NVT, N0.getOperand(0));
5488
5489       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5490                          SDLoc(N), TrTy, V,
5491                          DAG.getConstant(Index, IndexTy));
5492     }
5493   }
5494
5495   // Fold a series of buildvector, bitcast, and truncate if possible.
5496   // For example fold
5497   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5498   //   (2xi32 (buildvector x, y)).
5499   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5500       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5501       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5502       N0.getOperand(0).hasOneUse()) {
5503
5504     SDValue BuildVect = N0.getOperand(0);
5505     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5506     EVT TruncVecEltTy = VT.getVectorElementType();
5507
5508     // Check that the element types match.
5509     if (BuildVectEltTy == TruncVecEltTy) {
5510       // Now we only need to compute the offset of the truncated elements.
5511       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5512       unsigned TruncVecNumElts = VT.getVectorNumElements();
5513       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5514
5515       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5516              "Invalid number of elements");
5517
5518       SmallVector<SDValue, 8> Opnds;
5519       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5520         Opnds.push_back(BuildVect.getOperand(i));
5521
5522       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5523                          Opnds.size());
5524     }
5525   }
5526
5527   // See if we can simplify the input to this truncate through knowledge that
5528   // only the low bits are being used.
5529   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5530   // Currently we only perform this optimization on scalars because vectors
5531   // may have different active low bits.
5532   if (!VT.isVector()) {
5533     SDValue Shorter =
5534       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5535                                                VT.getSizeInBits()));
5536     if (Shorter.getNode())
5537       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5538   }
5539   // fold (truncate (load x)) -> (smaller load x)
5540   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5541   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5542     SDValue Reduced = ReduceLoadWidth(N);
5543     if (Reduced.getNode())
5544       return Reduced;
5545   }
5546   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5547   // where ... are all 'undef'.
5548   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5549     SmallVector<EVT, 8> VTs;
5550     SDValue V;
5551     unsigned Idx = 0;
5552     unsigned NumDefs = 0;
5553
5554     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5555       SDValue X = N0.getOperand(i);
5556       if (X.getOpcode() != ISD::UNDEF) {
5557         V = X;
5558         Idx = i;
5559         NumDefs++;
5560       }
5561       // Stop if more than one members are non-undef.
5562       if (NumDefs > 1)
5563         break;
5564       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5565                                      VT.getVectorElementType(),
5566                                      X.getValueType().getVectorNumElements()));
5567     }
5568
5569     if (NumDefs == 0)
5570       return DAG.getUNDEF(VT);
5571
5572     if (NumDefs == 1) {
5573       assert(V.getNode() && "The single defined operand is empty!");
5574       SmallVector<SDValue, 8> Opnds;
5575       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5576         if (i != Idx) {
5577           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5578           continue;
5579         }
5580         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5581         AddToWorkList(NV.getNode());
5582         Opnds.push_back(NV);
5583       }
5584       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5585                          &Opnds[0], Opnds.size());
5586     }
5587   }
5588
5589   // Simplify the operands using demanded-bits information.
5590   if (!VT.isVector() &&
5591       SimplifyDemandedBits(SDValue(N, 0)))
5592     return SDValue(N, 0);
5593
5594   return SDValue();
5595 }
5596
5597 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5598   SDValue Elt = N->getOperand(i);
5599   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5600     return Elt.getNode();
5601   return Elt.getOperand(Elt.getResNo()).getNode();
5602 }
5603
5604 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5605 /// if load locations are consecutive.
5606 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5607   assert(N->getOpcode() == ISD::BUILD_PAIR);
5608
5609   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5610   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5611   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5612       LD1->getPointerInfo().getAddrSpace() !=
5613          LD2->getPointerInfo().getAddrSpace())
5614     return SDValue();
5615   EVT LD1VT = LD1->getValueType(0);
5616
5617   if (ISD::isNON_EXTLoad(LD2) &&
5618       LD2->hasOneUse() &&
5619       // If both are volatile this would reduce the number of volatile loads.
5620       // If one is volatile it might be ok, but play conservative and bail out.
5621       !LD1->isVolatile() &&
5622       !LD2->isVolatile() &&
5623       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5624     unsigned Align = LD1->getAlignment();
5625     unsigned NewAlign = TLI.getDataLayout()->
5626       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5627
5628     if (NewAlign <= Align &&
5629         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5630       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5631                          LD1->getBasePtr(), LD1->getPointerInfo(),
5632                          false, false, false, Align);
5633   }
5634
5635   return SDValue();
5636 }
5637
5638 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5639   SDValue N0 = N->getOperand(0);
5640   EVT VT = N->getValueType(0);
5641
5642   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5643   // Only do this before legalize, since afterward the target may be depending
5644   // on the bitconvert.
5645   // First check to see if this is all constant.
5646   if (!LegalTypes &&
5647       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5648       VT.isVector()) {
5649     bool isSimple = true;
5650     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5651       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5652           N0.getOperand(i).getOpcode() != ISD::Constant &&
5653           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5654         isSimple = false;
5655         break;
5656       }
5657
5658     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5659     assert(!DestEltVT.isVector() &&
5660            "Element type of vector ValueType must not be vector!");
5661     if (isSimple)
5662       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5663   }
5664
5665   // If the input is a constant, let getNode fold it.
5666   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5667     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5668     if (Res.getNode() != N) {
5669       if (!LegalOperations ||
5670           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5671         return Res;
5672
5673       // Folding it resulted in an illegal node, and it's too late to
5674       // do that. Clean up the old node and forego the transformation.
5675       // Ideally this won't happen very often, because instcombine
5676       // and the earlier dagcombine runs (where illegal nodes are
5677       // permitted) should have folded most of them already.
5678       DAG.DeleteNode(Res.getNode());
5679     }
5680   }
5681
5682   // (conv (conv x, t1), t2) -> (conv x, t2)
5683   if (N0.getOpcode() == ISD::BITCAST)
5684     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5685                        N0.getOperand(0));
5686
5687   // fold (conv (load x)) -> (load (conv*)x)
5688   // If the resultant load doesn't need a higher alignment than the original!
5689   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5690       // Do not change the width of a volatile load.
5691       !cast<LoadSDNode>(N0)->isVolatile() &&
5692       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5693     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5694     unsigned Align = TLI.getDataLayout()->
5695       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5696     unsigned OrigAlign = LN0->getAlignment();
5697
5698     if (Align <= OrigAlign) {
5699       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5700                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5701                                  LN0->isVolatile(), LN0->isNonTemporal(),
5702                                  LN0->isInvariant(), OrigAlign);
5703       AddToWorkList(N);
5704       CombineTo(N0.getNode(),
5705                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5706                             N0.getValueType(), Load),
5707                 Load.getValue(1));
5708       return Load;
5709     }
5710   }
5711
5712   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5713   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5714   // This often reduces constant pool loads.
5715   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5716        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5717       N0.getNode()->hasOneUse() && VT.isInteger() &&
5718       !VT.isVector() && !N0.getValueType().isVector()) {
5719     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5720                                   N0.getOperand(0));
5721     AddToWorkList(NewConv.getNode());
5722
5723     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5724     if (N0.getOpcode() == ISD::FNEG)
5725       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5726                          NewConv, DAG.getConstant(SignBit, VT));
5727     assert(N0.getOpcode() == ISD::FABS);
5728     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5729                        NewConv, DAG.getConstant(~SignBit, VT));
5730   }
5731
5732   // fold (bitconvert (fcopysign cst, x)) ->
5733   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5734   // Note that we don't handle (copysign x, cst) because this can always be
5735   // folded to an fneg or fabs.
5736   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5737       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5738       VT.isInteger() && !VT.isVector()) {
5739     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5740     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5741     if (isTypeLegal(IntXVT)) {
5742       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5743                               IntXVT, N0.getOperand(1));
5744       AddToWorkList(X.getNode());
5745
5746       // If X has a different width than the result/lhs, sext it or truncate it.
5747       unsigned VTWidth = VT.getSizeInBits();
5748       if (OrigXWidth < VTWidth) {
5749         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5750         AddToWorkList(X.getNode());
5751       } else if (OrigXWidth > VTWidth) {
5752         // To get the sign bit in the right place, we have to shift it right
5753         // before truncating.
5754         X = DAG.getNode(ISD::SRL, SDLoc(X),
5755                         X.getValueType(), X,
5756                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5757         AddToWorkList(X.getNode());
5758         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5759         AddToWorkList(X.getNode());
5760       }
5761
5762       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5763       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5764                       X, DAG.getConstant(SignBit, VT));
5765       AddToWorkList(X.getNode());
5766
5767       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5768                                 VT, N0.getOperand(0));
5769       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5770                         Cst, DAG.getConstant(~SignBit, VT));
5771       AddToWorkList(Cst.getNode());
5772
5773       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5774     }
5775   }
5776
5777   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5778   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5779     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5780     if (CombineLD.getNode())
5781       return CombineLD;
5782   }
5783
5784   return SDValue();
5785 }
5786
5787 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5788   EVT VT = N->getValueType(0);
5789   return CombineConsecutiveLoads(N, VT);
5790 }
5791
5792 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5793 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5794 /// destination element value type.
5795 SDValue DAGCombiner::
5796 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5797   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5798
5799   // If this is already the right type, we're done.
5800   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5801
5802   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5803   unsigned DstBitSize = DstEltVT.getSizeInBits();
5804
5805   // If this is a conversion of N elements of one type to N elements of another
5806   // type, convert each element.  This handles FP<->INT cases.
5807   if (SrcBitSize == DstBitSize) {
5808     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5809                               BV->getValueType(0).getVectorNumElements());
5810
5811     // Due to the FP element handling below calling this routine recursively,
5812     // we can end up with a scalar-to-vector node here.
5813     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5814       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5815                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5816                                      DstEltVT, BV->getOperand(0)));
5817
5818     SmallVector<SDValue, 8> Ops;
5819     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5820       SDValue Op = BV->getOperand(i);
5821       // If the vector element type is not legal, the BUILD_VECTOR operands
5822       // are promoted and implicitly truncated.  Make that explicit here.
5823       if (Op.getValueType() != SrcEltVT)
5824         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5825       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5826                                 DstEltVT, Op));
5827       AddToWorkList(Ops.back().getNode());
5828     }
5829     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5830                        &Ops[0], Ops.size());
5831   }
5832
5833   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5834   // handle annoying details of growing/shrinking FP values, we convert them to
5835   // int first.
5836   if (SrcEltVT.isFloatingPoint()) {
5837     // Convert the input float vector to a int vector where the elements are the
5838     // same sizes.
5839     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5840     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5841     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5842     SrcEltVT = IntVT;
5843   }
5844
5845   // Now we know the input is an integer vector.  If the output is a FP type,
5846   // convert to integer first, then to FP of the right size.
5847   if (DstEltVT.isFloatingPoint()) {
5848     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5849     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5850     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5851
5852     // Next, convert to FP elements of the same size.
5853     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5854   }
5855
5856   // Okay, we know the src/dst types are both integers of differing types.
5857   // Handling growing first.
5858   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5859   if (SrcBitSize < DstBitSize) {
5860     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5861
5862     SmallVector<SDValue, 8> Ops;
5863     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5864          i += NumInputsPerOutput) {
5865       bool isLE = TLI.isLittleEndian();
5866       APInt NewBits = APInt(DstBitSize, 0);
5867       bool EltIsUndef = true;
5868       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5869         // Shift the previously computed bits over.
5870         NewBits <<= SrcBitSize;
5871         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5872         if (Op.getOpcode() == ISD::UNDEF) continue;
5873         EltIsUndef = false;
5874
5875         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5876                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5877       }
5878
5879       if (EltIsUndef)
5880         Ops.push_back(DAG.getUNDEF(DstEltVT));
5881       else
5882         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5883     }
5884
5885     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5886     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5887                        &Ops[0], Ops.size());
5888   }
5889
5890   // Finally, this must be the case where we are shrinking elements: each input
5891   // turns into multiple outputs.
5892   bool isS2V = ISD::isScalarToVector(BV);
5893   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5894   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5895                             NumOutputsPerInput*BV->getNumOperands());
5896   SmallVector<SDValue, 8> Ops;
5897
5898   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5899     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5900       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5901         Ops.push_back(DAG.getUNDEF(DstEltVT));
5902       continue;
5903     }
5904
5905     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5906                   getAPIntValue().zextOrTrunc(SrcBitSize);
5907
5908     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5909       APInt ThisVal = OpVal.trunc(DstBitSize);
5910       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5911       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5912         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5913         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5914                            Ops[0]);
5915       OpVal = OpVal.lshr(DstBitSize);
5916     }
5917
5918     // For big endian targets, swap the order of the pieces of each element.
5919     if (TLI.isBigEndian())
5920       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5921   }
5922
5923   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5924                      &Ops[0], Ops.size());
5925 }
5926
5927 SDValue DAGCombiner::visitFADD(SDNode *N) {
5928   SDValue N0 = N->getOperand(0);
5929   SDValue N1 = N->getOperand(1);
5930   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5931   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5932   EVT VT = N->getValueType(0);
5933
5934   // fold vector ops
5935   if (VT.isVector()) {
5936     SDValue FoldedVOp = SimplifyVBinOp(N);
5937     if (FoldedVOp.getNode()) return FoldedVOp;
5938   }
5939
5940   // fold (fadd c1, c2) -> c1 + c2
5941   if (N0CFP && N1CFP)
5942     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5943   // canonicalize constant to RHS
5944   if (N0CFP && !N1CFP)
5945     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5946   // fold (fadd A, 0) -> A
5947   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5948       N1CFP->getValueAPF().isZero())
5949     return N0;
5950   // fold (fadd A, (fneg B)) -> (fsub A, B)
5951   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5952     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5953     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5954                        GetNegatedExpression(N1, DAG, LegalOperations));
5955   // fold (fadd (fneg A), B) -> (fsub B, A)
5956   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5957     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5958     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5959                        GetNegatedExpression(N0, DAG, LegalOperations));
5960
5961   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5962   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5963       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5964       isa<ConstantFPSDNode>(N0.getOperand(1)))
5965     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5966                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
5967                                    N0.getOperand(1), N1));
5968
5969   // No FP constant should be created after legalization as Instruction
5970   // Selection pass has hard time in dealing with FP constant.
5971   //
5972   // We don't need test this condition for transformation like following, as
5973   // the DAG being transformed implies it is legal to take FP constant as
5974   // operand.
5975   //
5976   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5977   //
5978   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5979
5980   // If allow, fold (fadd (fneg x), x) -> 0.0
5981   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5982       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
5983     return DAG.getConstantFP(0.0, VT);
5984
5985     // If allow, fold (fadd x, (fneg x)) -> 0.0
5986   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5987       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
5988     return DAG.getConstantFP(0.0, VT);
5989
5990   // In unsafe math mode, we can fold chains of FADD's of the same value
5991   // into multiplications.  This transform is not safe in general because
5992   // we are reducing the number of rounding steps.
5993   if (DAG.getTarget().Options.UnsafeFPMath &&
5994       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5995       !N0CFP && !N1CFP) {
5996     if (N0.getOpcode() == ISD::FMUL) {
5997       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5998       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5999
6000       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6001       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6002         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6003                                      SDValue(CFP00, 0),
6004                                      DAG.getConstantFP(1.0, VT));
6005         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6006                            N1, NewCFP);
6007       }
6008
6009       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6010       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6011         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6012                                      SDValue(CFP01, 0),
6013                                      DAG.getConstantFP(1.0, VT));
6014         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6015                            N1, NewCFP);
6016       }
6017
6018       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6019       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6020           N1.getOperand(0) == N1.getOperand(1) &&
6021           N0.getOperand(1) == N1.getOperand(0)) {
6022         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6023                                      SDValue(CFP00, 0),
6024                                      DAG.getConstantFP(2.0, VT));
6025         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6026                            N0.getOperand(1), NewCFP);
6027       }
6028
6029       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6030       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6031           N1.getOperand(0) == N1.getOperand(1) &&
6032           N0.getOperand(0) == N1.getOperand(0)) {
6033         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6034                                      SDValue(CFP01, 0),
6035                                      DAG.getConstantFP(2.0, VT));
6036         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6037                            N0.getOperand(0), NewCFP);
6038       }
6039     }
6040
6041     if (N1.getOpcode() == ISD::FMUL) {
6042       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6043       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6044
6045       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6046       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6047         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6048                                      SDValue(CFP10, 0),
6049                                      DAG.getConstantFP(1.0, VT));
6050         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6051                            N0, NewCFP);
6052       }
6053
6054       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6055       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6056         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6057                                      SDValue(CFP11, 0),
6058                                      DAG.getConstantFP(1.0, VT));
6059         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6060                            N0, NewCFP);
6061       }
6062
6063
6064       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6065       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6066           N0.getOperand(0) == N0.getOperand(1) &&
6067           N1.getOperand(1) == N0.getOperand(0)) {
6068         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6069                                      SDValue(CFP10, 0),
6070                                      DAG.getConstantFP(2.0, VT));
6071         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6072                            N1.getOperand(1), NewCFP);
6073       }
6074
6075       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6076       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6077           N0.getOperand(0) == N0.getOperand(1) &&
6078           N1.getOperand(0) == N0.getOperand(0)) {
6079         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6080                                      SDValue(CFP11, 0),
6081                                      DAG.getConstantFP(2.0, VT));
6082         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6083                            N1.getOperand(0), NewCFP);
6084       }
6085     }
6086
6087     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6088       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6089       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6090       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6091           (N0.getOperand(0) == N1))
6092         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6093                            N1, DAG.getConstantFP(3.0, VT));
6094     }
6095
6096     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6097       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6098       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6099       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6100           N1.getOperand(0) == N0)
6101         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6102                            N0, DAG.getConstantFP(3.0, VT));
6103     }
6104
6105     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6106     if (AllowNewFpConst &&
6107         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6108         N0.getOperand(0) == N0.getOperand(1) &&
6109         N1.getOperand(0) == N1.getOperand(1) &&
6110         N0.getOperand(0) == N1.getOperand(0))
6111       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6112                          N0.getOperand(0),
6113                          DAG.getConstantFP(4.0, VT));
6114   }
6115
6116   // FADD -> FMA combines:
6117   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6118        DAG.getTarget().Options.UnsafeFPMath) &&
6119       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6120       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6121
6122     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6123     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6124       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6125                          N0.getOperand(0), N0.getOperand(1), N1);
6126
6127     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6128     // Note: Commutes FADD operands.
6129     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6130       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6131                          N1.getOperand(0), N1.getOperand(1), N0);
6132   }
6133
6134   return SDValue();
6135 }
6136
6137 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6138   SDValue N0 = N->getOperand(0);
6139   SDValue N1 = N->getOperand(1);
6140   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6141   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6142   EVT VT = N->getValueType(0);
6143   SDLoc dl(N);
6144
6145   // fold vector ops
6146   if (VT.isVector()) {
6147     SDValue FoldedVOp = SimplifyVBinOp(N);
6148     if (FoldedVOp.getNode()) return FoldedVOp;
6149   }
6150
6151   // fold (fsub c1, c2) -> c1-c2
6152   if (N0CFP && N1CFP)
6153     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6154   // fold (fsub A, 0) -> A
6155   if (DAG.getTarget().Options.UnsafeFPMath &&
6156       N1CFP && N1CFP->getValueAPF().isZero())
6157     return N0;
6158   // fold (fsub 0, B) -> -B
6159   if (DAG.getTarget().Options.UnsafeFPMath &&
6160       N0CFP && N0CFP->getValueAPF().isZero()) {
6161     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6162       return GetNegatedExpression(N1, DAG, LegalOperations);
6163     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6164       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6165   }
6166   // fold (fsub A, (fneg B)) -> (fadd A, B)
6167   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6168     return DAG.getNode(ISD::FADD, dl, VT, N0,
6169                        GetNegatedExpression(N1, DAG, LegalOperations));
6170
6171   // If 'unsafe math' is enabled, fold
6172   //    (fsub x, x) -> 0.0 &
6173   //    (fsub x, (fadd x, y)) -> (fneg y) &
6174   //    (fsub x, (fadd y, x)) -> (fneg y)
6175   if (DAG.getTarget().Options.UnsafeFPMath) {
6176     if (N0 == N1)
6177       return DAG.getConstantFP(0.0f, VT);
6178
6179     if (N1.getOpcode() == ISD::FADD) {
6180       SDValue N10 = N1->getOperand(0);
6181       SDValue N11 = N1->getOperand(1);
6182
6183       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6184                                           &DAG.getTarget().Options))
6185         return GetNegatedExpression(N11, DAG, LegalOperations);
6186
6187       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6188                                           &DAG.getTarget().Options))
6189         return GetNegatedExpression(N10, DAG, LegalOperations);
6190     }
6191   }
6192
6193   // FSUB -> FMA combines:
6194   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6195        DAG.getTarget().Options.UnsafeFPMath) &&
6196       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6197       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6198
6199     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6200     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6201       return DAG.getNode(ISD::FMA, dl, VT,
6202                          N0.getOperand(0), N0.getOperand(1),
6203                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6204
6205     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6206     // Note: Commutes FSUB operands.
6207     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6208       return DAG.getNode(ISD::FMA, dl, VT,
6209                          DAG.getNode(ISD::FNEG, dl, VT,
6210                          N1.getOperand(0)),
6211                          N1.getOperand(1), N0);
6212
6213     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6214     if (N0.getOpcode() == ISD::FNEG &&
6215         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6216         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6217       SDValue N00 = N0.getOperand(0).getOperand(0);
6218       SDValue N01 = N0.getOperand(0).getOperand(1);
6219       return DAG.getNode(ISD::FMA, dl, VT,
6220                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6221                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6222     }
6223   }
6224
6225   return SDValue();
6226 }
6227
6228 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6229   SDValue N0 = N->getOperand(0);
6230   SDValue N1 = N->getOperand(1);
6231   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6232   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6233   EVT VT = N->getValueType(0);
6234   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6235
6236   // fold vector ops
6237   if (VT.isVector()) {
6238     SDValue FoldedVOp = SimplifyVBinOp(N);
6239     if (FoldedVOp.getNode()) return FoldedVOp;
6240   }
6241
6242   // fold (fmul c1, c2) -> c1*c2
6243   if (N0CFP && N1CFP)
6244     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6245   // canonicalize constant to RHS
6246   if (N0CFP && !N1CFP)
6247     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6248   // fold (fmul A, 0) -> 0
6249   if (DAG.getTarget().Options.UnsafeFPMath &&
6250       N1CFP && N1CFP->getValueAPF().isZero())
6251     return N1;
6252   // fold (fmul A, 0) -> 0, vector edition.
6253   if (DAG.getTarget().Options.UnsafeFPMath &&
6254       ISD::isBuildVectorAllZeros(N1.getNode()))
6255     return N1;
6256   // fold (fmul A, 1.0) -> A
6257   if (N1CFP && N1CFP->isExactlyValue(1.0))
6258     return N0;
6259   // fold (fmul X, 2.0) -> (fadd X, X)
6260   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6261     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6262   // fold (fmul X, -1.0) -> (fneg X)
6263   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6264     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6265       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6266
6267   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6268   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6269                                        &DAG.getTarget().Options)) {
6270     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6271                                          &DAG.getTarget().Options)) {
6272       // Both can be negated for free, check to see if at least one is cheaper
6273       // negated.
6274       if (LHSNeg == 2 || RHSNeg == 2)
6275         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6276                            GetNegatedExpression(N0, DAG, LegalOperations),
6277                            GetNegatedExpression(N1, DAG, LegalOperations));
6278     }
6279   }
6280
6281   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6282   if (DAG.getTarget().Options.UnsafeFPMath &&
6283       N1CFP && N0.getOpcode() == ISD::FMUL &&
6284       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6285     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6286                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6287                                    N0.getOperand(1), N1));
6288
6289   return SDValue();
6290 }
6291
6292 SDValue DAGCombiner::visitFMA(SDNode *N) {
6293   SDValue N0 = N->getOperand(0);
6294   SDValue N1 = N->getOperand(1);
6295   SDValue N2 = N->getOperand(2);
6296   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6297   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6298   EVT VT = N->getValueType(0);
6299   SDLoc dl(N);
6300
6301   if (DAG.getTarget().Options.UnsafeFPMath) {
6302     if (N0CFP && N0CFP->isZero())
6303       return N2;
6304     if (N1CFP && N1CFP->isZero())
6305       return N2;
6306   }
6307   if (N0CFP && N0CFP->isExactlyValue(1.0))
6308     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6309   if (N1CFP && N1CFP->isExactlyValue(1.0))
6310     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6311
6312   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6313   if (N0CFP && !N1CFP)
6314     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6315
6316   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6317   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6318       N2.getOpcode() == ISD::FMUL &&
6319       N0 == N2.getOperand(0) &&
6320       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6321     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6322                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6323   }
6324
6325
6326   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6327   if (DAG.getTarget().Options.UnsafeFPMath &&
6328       N0.getOpcode() == ISD::FMUL && N1CFP &&
6329       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6330     return DAG.getNode(ISD::FMA, dl, VT,
6331                        N0.getOperand(0),
6332                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6333                        N2);
6334   }
6335
6336   // (fma x, 1, y) -> (fadd x, y)
6337   // (fma x, -1, y) -> (fadd (fneg x), y)
6338   if (N1CFP) {
6339     if (N1CFP->isExactlyValue(1.0))
6340       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6341
6342     if (N1CFP->isExactlyValue(-1.0) &&
6343         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6344       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6345       AddToWorkList(RHSNeg.getNode());
6346       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6347     }
6348   }
6349
6350   // (fma x, c, x) -> (fmul x, (c+1))
6351   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6352     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6353                        DAG.getNode(ISD::FADD, dl, VT,
6354                                    N1, DAG.getConstantFP(1.0, VT)));
6355
6356   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6357   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6358       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6359     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6360                        DAG.getNode(ISD::FADD, dl, VT,
6361                                    N1, DAG.getConstantFP(-1.0, VT)));
6362
6363
6364   return SDValue();
6365 }
6366
6367 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6368   SDValue N0 = N->getOperand(0);
6369   SDValue N1 = N->getOperand(1);
6370   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6371   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6372   EVT VT = N->getValueType(0);
6373   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6374
6375   // fold vector ops
6376   if (VT.isVector()) {
6377     SDValue FoldedVOp = SimplifyVBinOp(N);
6378     if (FoldedVOp.getNode()) return FoldedVOp;
6379   }
6380
6381   // fold (fdiv c1, c2) -> c1/c2
6382   if (N0CFP && N1CFP)
6383     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6384
6385   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6386   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6387     // Compute the reciprocal 1.0 / c2.
6388     APFloat N1APF = N1CFP->getValueAPF();
6389     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6390     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6391     // Only do the transform if the reciprocal is a legal fp immediate that
6392     // isn't too nasty (eg NaN, denormal, ...).
6393     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6394         (!LegalOperations ||
6395          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6396          // backend)... we should handle this gracefully after Legalize.
6397          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6398          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6399          TLI.isFPImmLegal(Recip, VT)))
6400       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6401                          DAG.getConstantFP(Recip, VT));
6402   }
6403
6404   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6405   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6406                                        &DAG.getTarget().Options)) {
6407     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6408                                          &DAG.getTarget().Options)) {
6409       // Both can be negated for free, check to see if at least one is cheaper
6410       // negated.
6411       if (LHSNeg == 2 || RHSNeg == 2)
6412         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6413                            GetNegatedExpression(N0, DAG, LegalOperations),
6414                            GetNegatedExpression(N1, DAG, LegalOperations));
6415     }
6416   }
6417
6418   return SDValue();
6419 }
6420
6421 SDValue DAGCombiner::visitFREM(SDNode *N) {
6422   SDValue N0 = N->getOperand(0);
6423   SDValue N1 = N->getOperand(1);
6424   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6425   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6426   EVT VT = N->getValueType(0);
6427
6428   // fold (frem c1, c2) -> fmod(c1,c2)
6429   if (N0CFP && N1CFP)
6430     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6431
6432   return SDValue();
6433 }
6434
6435 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6436   SDValue N0 = N->getOperand(0);
6437   SDValue N1 = N->getOperand(1);
6438   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6439   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6440   EVT VT = N->getValueType(0);
6441
6442   if (N0CFP && N1CFP)  // Constant fold
6443     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6444
6445   if (N1CFP) {
6446     const APFloat& V = N1CFP->getValueAPF();
6447     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6448     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6449     if (!V.isNegative()) {
6450       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6451         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6452     } else {
6453       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6454         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6455                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6456     }
6457   }
6458
6459   // copysign(fabs(x), y) -> copysign(x, y)
6460   // copysign(fneg(x), y) -> copysign(x, y)
6461   // copysign(copysign(x,z), y) -> copysign(x, y)
6462   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6463       N0.getOpcode() == ISD::FCOPYSIGN)
6464     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6465                        N0.getOperand(0), N1);
6466
6467   // copysign(x, abs(y)) -> abs(x)
6468   if (N1.getOpcode() == ISD::FABS)
6469     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6470
6471   // copysign(x, copysign(y,z)) -> copysign(x, z)
6472   if (N1.getOpcode() == ISD::FCOPYSIGN)
6473     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6474                        N0, N1.getOperand(1));
6475
6476   // copysign(x, fp_extend(y)) -> copysign(x, y)
6477   // copysign(x, fp_round(y)) -> copysign(x, y)
6478   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6479     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6480                        N0, N1.getOperand(0));
6481
6482   return SDValue();
6483 }
6484
6485 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6486   SDValue N0 = N->getOperand(0);
6487   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6488   EVT VT = N->getValueType(0);
6489   EVT OpVT = N0.getValueType();
6490
6491   // fold (sint_to_fp c1) -> c1fp
6492   if (N0C &&
6493       // ...but only if the target supports immediate floating-point values
6494       (!LegalOperations ||
6495        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6496     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6497
6498   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6499   // but UINT_TO_FP is legal on this target, try to convert.
6500   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6501       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6502     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6503     if (DAG.SignBitIsZero(N0))
6504       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6505   }
6506
6507   // The next optimizations are desireable only if SELECT_CC can be lowered.
6508   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6509   // having to say they don't support SELECT_CC on every type the DAG knows
6510   // about, since there is no way to mark an opcode illegal at all value types
6511   // (See also visitSELECT)
6512   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6513     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6514     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6515         !VT.isVector() &&
6516         (!LegalOperations ||
6517          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6518       SDValue Ops[] =
6519         { N0.getOperand(0), N0.getOperand(1),
6520           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6521           N0.getOperand(2) };
6522       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6523     }
6524
6525     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6526     //      (select_cc x, y, 1.0, 0.0,, cc)
6527     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6528         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6529         (!LegalOperations ||
6530          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6531       SDValue Ops[] =
6532         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6533           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6534           N0.getOperand(0).getOperand(2) };
6535       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6536     }
6537   }
6538
6539   return SDValue();
6540 }
6541
6542 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6543   SDValue N0 = N->getOperand(0);
6544   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6545   EVT VT = N->getValueType(0);
6546   EVT OpVT = N0.getValueType();
6547
6548   // fold (uint_to_fp c1) -> c1fp
6549   if (N0C &&
6550       // ...but only if the target supports immediate floating-point values
6551       (!LegalOperations ||
6552        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6553     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6554
6555   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6556   // but SINT_TO_FP is legal on this target, try to convert.
6557   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6558       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6559     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6560     if (DAG.SignBitIsZero(N0))
6561       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6562   }
6563
6564   // The next optimizations are desireable only if SELECT_CC can be lowered.
6565   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6566   // having to say they don't support SELECT_CC on every type the DAG knows
6567   // about, since there is no way to mark an opcode illegal at all value types
6568   // (See also visitSELECT)
6569   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6570     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6571
6572     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6573         (!LegalOperations ||
6574          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6575       SDValue Ops[] =
6576         { N0.getOperand(0), N0.getOperand(1),
6577           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6578           N0.getOperand(2) };
6579       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6580     }
6581   }
6582
6583   return SDValue();
6584 }
6585
6586 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6587   SDValue N0 = N->getOperand(0);
6588   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6589   EVT VT = N->getValueType(0);
6590
6591   // fold (fp_to_sint c1fp) -> c1
6592   if (N0CFP)
6593     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6594
6595   return SDValue();
6596 }
6597
6598 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6599   SDValue N0 = N->getOperand(0);
6600   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6601   EVT VT = N->getValueType(0);
6602
6603   // fold (fp_to_uint c1fp) -> c1
6604   if (N0CFP)
6605     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6606
6607   return SDValue();
6608 }
6609
6610 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6611   SDValue N0 = N->getOperand(0);
6612   SDValue N1 = N->getOperand(1);
6613   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6614   EVT VT = N->getValueType(0);
6615
6616   // fold (fp_round c1fp) -> c1fp
6617   if (N0CFP)
6618     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6619
6620   // fold (fp_round (fp_extend x)) -> x
6621   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6622     return N0.getOperand(0);
6623
6624   // fold (fp_round (fp_round x)) -> (fp_round x)
6625   if (N0.getOpcode() == ISD::FP_ROUND) {
6626     // This is a value preserving truncation if both round's are.
6627     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6628                    N0.getNode()->getConstantOperandVal(1) == 1;
6629     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6630                        DAG.getIntPtrConstant(IsTrunc));
6631   }
6632
6633   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6634   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6635     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6636                               N0.getOperand(0), N1);
6637     AddToWorkList(Tmp.getNode());
6638     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6639                        Tmp, N0.getOperand(1));
6640   }
6641
6642   return SDValue();
6643 }
6644
6645 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6646   SDValue N0 = N->getOperand(0);
6647   EVT VT = N->getValueType(0);
6648   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6649   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6650
6651   // fold (fp_round_inreg c1fp) -> c1fp
6652   if (N0CFP && isTypeLegal(EVT)) {
6653     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6654     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6655   }
6656
6657   return SDValue();
6658 }
6659
6660 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6661   SDValue N0 = N->getOperand(0);
6662   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6663   EVT VT = N->getValueType(0);
6664
6665   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6666   if (N->hasOneUse() &&
6667       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6668     return SDValue();
6669
6670   // fold (fp_extend c1fp) -> c1fp
6671   if (N0CFP)
6672     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6673
6674   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6675   // value of X.
6676   if (N0.getOpcode() == ISD::FP_ROUND
6677       && N0.getNode()->getConstantOperandVal(1) == 1) {
6678     SDValue In = N0.getOperand(0);
6679     if (In.getValueType() == VT) return In;
6680     if (VT.bitsLT(In.getValueType()))
6681       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6682                          In, N0.getOperand(1));
6683     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6684   }
6685
6686   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6687   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6688       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6689        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6690     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6691     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6692                                      LN0->getChain(),
6693                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6694                                      N0.getValueType(),
6695                                      LN0->isVolatile(), LN0->isNonTemporal(),
6696                                      LN0->getAlignment());
6697     CombineTo(N, ExtLoad);
6698     CombineTo(N0.getNode(),
6699               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6700                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6701               ExtLoad.getValue(1));
6702     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6703   }
6704
6705   return SDValue();
6706 }
6707
6708 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6709   SDValue N0 = N->getOperand(0);
6710   EVT VT = N->getValueType(0);
6711
6712   if (VT.isVector()) {
6713     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6714     if (FoldedVOp.getNode()) return FoldedVOp;
6715   }
6716
6717   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6718                          &DAG.getTarget().Options))
6719     return GetNegatedExpression(N0, DAG, LegalOperations);
6720
6721   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6722   // constant pool values.
6723   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6724       !VT.isVector() &&
6725       N0.getNode()->hasOneUse() &&
6726       N0.getOperand(0).getValueType().isInteger()) {
6727     SDValue Int = N0.getOperand(0);
6728     EVT IntVT = Int.getValueType();
6729     if (IntVT.isInteger() && !IntVT.isVector()) {
6730       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6731               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6732       AddToWorkList(Int.getNode());
6733       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6734                          VT, Int);
6735     }
6736   }
6737
6738   // (fneg (fmul c, x)) -> (fmul -c, x)
6739   if (N0.getOpcode() == ISD::FMUL) {
6740     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6741     if (CFP1)
6742       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6743                          N0.getOperand(0),
6744                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6745                                      N0.getOperand(1)));
6746   }
6747
6748   return SDValue();
6749 }
6750
6751 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6752   SDValue N0 = N->getOperand(0);
6753   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6754   EVT VT = N->getValueType(0);
6755
6756   // fold (fceil c1) -> fceil(c1)
6757   if (N0CFP)
6758     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6759
6760   return SDValue();
6761 }
6762
6763 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6764   SDValue N0 = N->getOperand(0);
6765   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6766   EVT VT = N->getValueType(0);
6767
6768   // fold (ftrunc c1) -> ftrunc(c1)
6769   if (N0CFP)
6770     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6771
6772   return SDValue();
6773 }
6774
6775 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6776   SDValue N0 = N->getOperand(0);
6777   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6778   EVT VT = N->getValueType(0);
6779
6780   // fold (ffloor c1) -> ffloor(c1)
6781   if (N0CFP)
6782     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6783
6784   return SDValue();
6785 }
6786
6787 SDValue DAGCombiner::visitFABS(SDNode *N) {
6788   SDValue N0 = N->getOperand(0);
6789   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6790   EVT VT = N->getValueType(0);
6791
6792   if (VT.isVector()) {
6793     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6794     if (FoldedVOp.getNode()) return FoldedVOp;
6795   }
6796
6797   // fold (fabs c1) -> fabs(c1)
6798   if (N0CFP)
6799     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6800   // fold (fabs (fabs x)) -> (fabs x)
6801   if (N0.getOpcode() == ISD::FABS)
6802     return N->getOperand(0);
6803   // fold (fabs (fneg x)) -> (fabs x)
6804   // fold (fabs (fcopysign x, y)) -> (fabs x)
6805   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6806     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6807
6808   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6809   // constant pool values.
6810   if (!TLI.isFAbsFree(VT) &&
6811       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6812       N0.getOperand(0).getValueType().isInteger() &&
6813       !N0.getOperand(0).getValueType().isVector()) {
6814     SDValue Int = N0.getOperand(0);
6815     EVT IntVT = Int.getValueType();
6816     if (IntVT.isInteger() && !IntVT.isVector()) {
6817       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6818              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6819       AddToWorkList(Int.getNode());
6820       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6821                          N->getValueType(0), Int);
6822     }
6823   }
6824
6825   return SDValue();
6826 }
6827
6828 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6829   SDValue Chain = N->getOperand(0);
6830   SDValue N1 = N->getOperand(1);
6831   SDValue N2 = N->getOperand(2);
6832
6833   // If N is a constant we could fold this into a fallthrough or unconditional
6834   // branch. However that doesn't happen very often in normal code, because
6835   // Instcombine/SimplifyCFG should have handled the available opportunities.
6836   // If we did this folding here, it would be necessary to update the
6837   // MachineBasicBlock CFG, which is awkward.
6838
6839   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6840   // on the target.
6841   if (N1.getOpcode() == ISD::SETCC &&
6842       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6843                                    N1.getOperand(0).getValueType())) {
6844     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6845                        Chain, N1.getOperand(2),
6846                        N1.getOperand(0), N1.getOperand(1), N2);
6847   }
6848
6849   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6850       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6851        (N1.getOperand(0).hasOneUse() &&
6852         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6853     SDNode *Trunc = 0;
6854     if (N1.getOpcode() == ISD::TRUNCATE) {
6855       // Look pass the truncate.
6856       Trunc = N1.getNode();
6857       N1 = N1.getOperand(0);
6858     }
6859
6860     // Match this pattern so that we can generate simpler code:
6861     //
6862     //   %a = ...
6863     //   %b = and i32 %a, 2
6864     //   %c = srl i32 %b, 1
6865     //   brcond i32 %c ...
6866     //
6867     // into
6868     //
6869     //   %a = ...
6870     //   %b = and i32 %a, 2
6871     //   %c = setcc eq %b, 0
6872     //   brcond %c ...
6873     //
6874     // This applies only when the AND constant value has one bit set and the
6875     // SRL constant is equal to the log2 of the AND constant. The back-end is
6876     // smart enough to convert the result into a TEST/JMP sequence.
6877     SDValue Op0 = N1.getOperand(0);
6878     SDValue Op1 = N1.getOperand(1);
6879
6880     if (Op0.getOpcode() == ISD::AND &&
6881         Op1.getOpcode() == ISD::Constant) {
6882       SDValue AndOp1 = Op0.getOperand(1);
6883
6884       if (AndOp1.getOpcode() == ISD::Constant) {
6885         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6886
6887         if (AndConst.isPowerOf2() &&
6888             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6889           SDValue SetCC =
6890             DAG.getSetCC(SDLoc(N),
6891                          getSetCCResultType(Op0.getValueType()),
6892                          Op0, DAG.getConstant(0, Op0.getValueType()),
6893                          ISD::SETNE);
6894
6895           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6896                                           MVT::Other, Chain, SetCC, N2);
6897           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6898           // will convert it back to (X & C1) >> C2.
6899           CombineTo(N, NewBRCond, false);
6900           // Truncate is dead.
6901           if (Trunc) {
6902             removeFromWorkList(Trunc);
6903             DAG.DeleteNode(Trunc);
6904           }
6905           // Replace the uses of SRL with SETCC
6906           WorkListRemover DeadNodes(*this);
6907           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6908           removeFromWorkList(N1.getNode());
6909           DAG.DeleteNode(N1.getNode());
6910           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6911         }
6912       }
6913     }
6914
6915     if (Trunc)
6916       // Restore N1 if the above transformation doesn't match.
6917       N1 = N->getOperand(1);
6918   }
6919
6920   // Transform br(xor(x, y)) -> br(x != y)
6921   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6922   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6923     SDNode *TheXor = N1.getNode();
6924     SDValue Op0 = TheXor->getOperand(0);
6925     SDValue Op1 = TheXor->getOperand(1);
6926     if (Op0.getOpcode() == Op1.getOpcode()) {
6927       // Avoid missing important xor optimizations.
6928       SDValue Tmp = visitXOR(TheXor);
6929       if (Tmp.getNode()) {
6930         if (Tmp.getNode() != TheXor) {
6931           DEBUG(dbgs() << "\nReplacing.8 ";
6932                 TheXor->dump(&DAG);
6933                 dbgs() << "\nWith: ";
6934                 Tmp.getNode()->dump(&DAG);
6935                 dbgs() << '\n');
6936           WorkListRemover DeadNodes(*this);
6937           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6938           removeFromWorkList(TheXor);
6939           DAG.DeleteNode(TheXor);
6940           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6941                              MVT::Other, Chain, Tmp, N2);
6942         }
6943
6944         // visitXOR has changed XOR's operands or replaced the XOR completely,
6945         // bail out.
6946         return SDValue(N, 0);
6947       }
6948     }
6949
6950     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6951       bool Equal = false;
6952       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6953         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6954             Op0.getOpcode() == ISD::XOR) {
6955           TheXor = Op0.getNode();
6956           Equal = true;
6957         }
6958
6959       EVT SetCCVT = N1.getValueType();
6960       if (LegalTypes)
6961         SetCCVT = getSetCCResultType(SetCCVT);
6962       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6963                                    SetCCVT,
6964                                    Op0, Op1,
6965                                    Equal ? ISD::SETEQ : ISD::SETNE);
6966       // Replace the uses of XOR with SETCC
6967       WorkListRemover DeadNodes(*this);
6968       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6969       removeFromWorkList(N1.getNode());
6970       DAG.DeleteNode(N1.getNode());
6971       return DAG.getNode(ISD::BRCOND, SDLoc(N),
6972                          MVT::Other, Chain, SetCC, N2);
6973     }
6974   }
6975
6976   return SDValue();
6977 }
6978
6979 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6980 //
6981 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6982   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6983   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6984
6985   // If N is a constant we could fold this into a fallthrough or unconditional
6986   // branch. However that doesn't happen very often in normal code, because
6987   // Instcombine/SimplifyCFG should have handled the available opportunities.
6988   // If we did this folding here, it would be necessary to update the
6989   // MachineBasicBlock CFG, which is awkward.
6990
6991   // Use SimplifySetCC to simplify SETCC's.
6992   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6993                                CondLHS, CondRHS, CC->get(), SDLoc(N),
6994                                false);
6995   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6996
6997   // fold to a simpler setcc
6998   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6999     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7000                        N->getOperand(0), Simp.getOperand(2),
7001                        Simp.getOperand(0), Simp.getOperand(1),
7002                        N->getOperand(4));
7003
7004   return SDValue();
7005 }
7006
7007 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7008 /// uses N as its base pointer and that N may be folded in the load / store
7009 /// addressing mode.
7010 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7011                                     SelectionDAG &DAG,
7012                                     const TargetLowering &TLI) {
7013   EVT VT;
7014   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7015     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7016       return false;
7017     VT = Use->getValueType(0);
7018   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7019     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7020       return false;
7021     VT = ST->getValue().getValueType();
7022   } else
7023     return false;
7024
7025   TargetLowering::AddrMode AM;
7026   if (N->getOpcode() == ISD::ADD) {
7027     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7028     if (Offset)
7029       // [reg +/- imm]
7030       AM.BaseOffs = Offset->getSExtValue();
7031     else
7032       // [reg +/- reg]
7033       AM.Scale = 1;
7034   } else if (N->getOpcode() == ISD::SUB) {
7035     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7036     if (Offset)
7037       // [reg +/- imm]
7038       AM.BaseOffs = -Offset->getSExtValue();
7039     else
7040       // [reg +/- reg]
7041       AM.Scale = 1;
7042   } else
7043     return false;
7044
7045   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7046 }
7047
7048 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7049 /// pre-indexed load / store when the base pointer is an add or subtract
7050 /// and it has other uses besides the load / store. After the
7051 /// transformation, the new indexed load / store has effectively folded
7052 /// the add / subtract in and all of its other uses are redirected to the
7053 /// new load / store.
7054 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7055   if (Level < AfterLegalizeDAG)
7056     return false;
7057
7058   bool isLoad = true;
7059   SDValue Ptr;
7060   EVT VT;
7061   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7062     if (LD->isIndexed())
7063       return false;
7064     VT = LD->getMemoryVT();
7065     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7066         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7067       return false;
7068     Ptr = LD->getBasePtr();
7069   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7070     if (ST->isIndexed())
7071       return false;
7072     VT = ST->getMemoryVT();
7073     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7074         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7075       return false;
7076     Ptr = ST->getBasePtr();
7077     isLoad = false;
7078   } else {
7079     return false;
7080   }
7081
7082   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7083   // out.  There is no reason to make this a preinc/predec.
7084   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7085       Ptr.getNode()->hasOneUse())
7086     return false;
7087
7088   // Ask the target to do addressing mode selection.
7089   SDValue BasePtr;
7090   SDValue Offset;
7091   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7092   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7093     return false;
7094
7095   // Backends without true r+i pre-indexed forms may need to pass a
7096   // constant base with a variable offset so that constant coercion
7097   // will work with the patterns in canonical form.
7098   bool Swapped = false;
7099   if (isa<ConstantSDNode>(BasePtr)) {
7100     std::swap(BasePtr, Offset);
7101     Swapped = true;
7102   }
7103
7104   // Don't create a indexed load / store with zero offset.
7105   if (isa<ConstantSDNode>(Offset) &&
7106       cast<ConstantSDNode>(Offset)->isNullValue())
7107     return false;
7108
7109   // Try turning it into a pre-indexed load / store except when:
7110   // 1) The new base ptr is a frame index.
7111   // 2) If N is a store and the new base ptr is either the same as or is a
7112   //    predecessor of the value being stored.
7113   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7114   //    that would create a cycle.
7115   // 4) All uses are load / store ops that use it as old base ptr.
7116
7117   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7118   // (plus the implicit offset) to a register to preinc anyway.
7119   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7120     return false;
7121
7122   // Check #2.
7123   if (!isLoad) {
7124     SDValue Val = cast<StoreSDNode>(N)->getValue();
7125     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7126       return false;
7127   }
7128
7129   // If the offset is a constant, there may be other adds of constants that
7130   // can be folded with this one. We should do this to avoid having to keep
7131   // a copy of the original base pointer.
7132   SmallVector<SDNode *, 16> OtherUses;
7133   if (isa<ConstantSDNode>(Offset))
7134     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7135          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7136       SDNode *Use = *I;
7137       if (Use == Ptr.getNode())
7138         continue;
7139
7140       if (Use->isPredecessorOf(N))
7141         continue;
7142
7143       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7144         OtherUses.clear();
7145         break;
7146       }
7147
7148       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7149       if (Op1.getNode() == BasePtr.getNode())
7150         std::swap(Op0, Op1);
7151       assert(Op0.getNode() == BasePtr.getNode() &&
7152              "Use of ADD/SUB but not an operand");
7153
7154       if (!isa<ConstantSDNode>(Op1)) {
7155         OtherUses.clear();
7156         break;
7157       }
7158
7159       // FIXME: In some cases, we can be smarter about this.
7160       if (Op1.getValueType() != Offset.getValueType()) {
7161         OtherUses.clear();
7162         break;
7163       }
7164
7165       OtherUses.push_back(Use);
7166     }
7167
7168   if (Swapped)
7169     std::swap(BasePtr, Offset);
7170
7171   // Now check for #3 and #4.
7172   bool RealUse = false;
7173
7174   // Caches for hasPredecessorHelper
7175   SmallPtrSet<const SDNode *, 32> Visited;
7176   SmallVector<const SDNode *, 16> Worklist;
7177
7178   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7179          E = Ptr.getNode()->use_end(); I != E; ++I) {
7180     SDNode *Use = *I;
7181     if (Use == N)
7182       continue;
7183     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7184       return false;
7185
7186     // If Ptr may be folded in addressing mode of other use, then it's
7187     // not profitable to do this transformation.
7188     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7189       RealUse = true;
7190   }
7191
7192   if (!RealUse)
7193     return false;
7194
7195   SDValue Result;
7196   if (isLoad)
7197     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7198                                 BasePtr, Offset, AM);
7199   else
7200     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7201                                  BasePtr, Offset, AM);
7202   ++PreIndexedNodes;
7203   ++NodesCombined;
7204   DEBUG(dbgs() << "\nReplacing.4 ";
7205         N->dump(&DAG);
7206         dbgs() << "\nWith: ";
7207         Result.getNode()->dump(&DAG);
7208         dbgs() << '\n');
7209   WorkListRemover DeadNodes(*this);
7210   if (isLoad) {
7211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7212     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7213   } else {
7214     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7215   }
7216
7217   // Finally, since the node is now dead, remove it from the graph.
7218   DAG.DeleteNode(N);
7219
7220   if (Swapped)
7221     std::swap(BasePtr, Offset);
7222
7223   // Replace other uses of BasePtr that can be updated to use Ptr
7224   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7225     unsigned OffsetIdx = 1;
7226     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7227       OffsetIdx = 0;
7228     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7229            BasePtr.getNode() && "Expected BasePtr operand");
7230
7231     // We need to replace ptr0 in the following expression:
7232     //   x0 * offset0 + y0 * ptr0 = t0
7233     // knowing that
7234     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7235     //
7236     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7237     // indexed load/store and the expresion that needs to be re-written.
7238     //
7239     // Therefore, we have:
7240     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7241
7242     ConstantSDNode *CN =
7243       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7244     int X0, X1, Y0, Y1;
7245     APInt Offset0 = CN->getAPIntValue();
7246     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7247
7248     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7249     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7250     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7251     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7252
7253     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7254
7255     APInt CNV = Offset0;
7256     if (X0 < 0) CNV = -CNV;
7257     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7258     else CNV = CNV - Offset1;
7259
7260     // We can now generate the new expression.
7261     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7262     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7263
7264     SDValue NewUse = DAG.getNode(Opcode,
7265                                  SDLoc(OtherUses[i]),
7266                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7267     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7268     removeFromWorkList(OtherUses[i]);
7269     DAG.DeleteNode(OtherUses[i]);
7270   }
7271
7272   // Replace the uses of Ptr with uses of the updated base value.
7273   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7274   removeFromWorkList(Ptr.getNode());
7275   DAG.DeleteNode(Ptr.getNode());
7276
7277   return true;
7278 }
7279
7280 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7281 /// add / sub of the base pointer node into a post-indexed load / store.
7282 /// The transformation folded the add / subtract into the new indexed
7283 /// load / store effectively and all of its uses are redirected to the
7284 /// new load / store.
7285 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7286   if (Level < AfterLegalizeDAG)
7287     return false;
7288
7289   bool isLoad = true;
7290   SDValue Ptr;
7291   EVT VT;
7292   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7293     if (LD->isIndexed())
7294       return false;
7295     VT = LD->getMemoryVT();
7296     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7297         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7298       return false;
7299     Ptr = LD->getBasePtr();
7300   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7301     if (ST->isIndexed())
7302       return false;
7303     VT = ST->getMemoryVT();
7304     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7305         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7306       return false;
7307     Ptr = ST->getBasePtr();
7308     isLoad = false;
7309   } else {
7310     return false;
7311   }
7312
7313   if (Ptr.getNode()->hasOneUse())
7314     return false;
7315
7316   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7317          E = Ptr.getNode()->use_end(); I != E; ++I) {
7318     SDNode *Op = *I;
7319     if (Op == N ||
7320         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7321       continue;
7322
7323     SDValue BasePtr;
7324     SDValue Offset;
7325     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7326     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7327       // Don't create a indexed load / store with zero offset.
7328       if (isa<ConstantSDNode>(Offset) &&
7329           cast<ConstantSDNode>(Offset)->isNullValue())
7330         continue;
7331
7332       // Try turning it into a post-indexed load / store except when
7333       // 1) All uses are load / store ops that use it as base ptr (and
7334       //    it may be folded as addressing mmode).
7335       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7336       //    nor a successor of N. Otherwise, if Op is folded that would
7337       //    create a cycle.
7338
7339       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7340         continue;
7341
7342       // Check for #1.
7343       bool TryNext = false;
7344       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7345              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7346         SDNode *Use = *II;
7347         if (Use == Ptr.getNode())
7348           continue;
7349
7350         // If all the uses are load / store addresses, then don't do the
7351         // transformation.
7352         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7353           bool RealUse = false;
7354           for (SDNode::use_iterator III = Use->use_begin(),
7355                  EEE = Use->use_end(); III != EEE; ++III) {
7356             SDNode *UseUse = *III;
7357             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7358               RealUse = true;
7359           }
7360
7361           if (!RealUse) {
7362             TryNext = true;
7363             break;
7364           }
7365         }
7366       }
7367
7368       if (TryNext)
7369         continue;
7370
7371       // Check for #2
7372       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7373         SDValue Result = isLoad
7374           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7375                                BasePtr, Offset, AM)
7376           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7377                                 BasePtr, Offset, AM);
7378         ++PostIndexedNodes;
7379         ++NodesCombined;
7380         DEBUG(dbgs() << "\nReplacing.5 ";
7381               N->dump(&DAG);
7382               dbgs() << "\nWith: ";
7383               Result.getNode()->dump(&DAG);
7384               dbgs() << '\n');
7385         WorkListRemover DeadNodes(*this);
7386         if (isLoad) {
7387           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7388           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7389         } else {
7390           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7391         }
7392
7393         // Finally, since the node is now dead, remove it from the graph.
7394         DAG.DeleteNode(N);
7395
7396         // Replace the uses of Use with uses of the updated base value.
7397         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7398                                       Result.getValue(isLoad ? 1 : 0));
7399         removeFromWorkList(Op);
7400         DAG.DeleteNode(Op);
7401         return true;
7402       }
7403     }
7404   }
7405
7406   return false;
7407 }
7408
7409 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7410   LoadSDNode *LD  = cast<LoadSDNode>(N);
7411   SDValue Chain = LD->getChain();
7412   SDValue Ptr   = LD->getBasePtr();
7413
7414   // If load is not volatile and there are no uses of the loaded value (and
7415   // the updated indexed value in case of indexed loads), change uses of the
7416   // chain value into uses of the chain input (i.e. delete the dead load).
7417   if (!LD->isVolatile()) {
7418     if (N->getValueType(1) == MVT::Other) {
7419       // Unindexed loads.
7420       if (!N->hasAnyUseOfValue(0)) {
7421         // It's not safe to use the two value CombineTo variant here. e.g.
7422         // v1, chain2 = load chain1, loc
7423         // v2, chain3 = load chain2, loc
7424         // v3         = add v2, c
7425         // Now we replace use of chain2 with chain1.  This makes the second load
7426         // isomorphic to the one we are deleting, and thus makes this load live.
7427         DEBUG(dbgs() << "\nReplacing.6 ";
7428               N->dump(&DAG);
7429               dbgs() << "\nWith chain: ";
7430               Chain.getNode()->dump(&DAG);
7431               dbgs() << "\n");
7432         WorkListRemover DeadNodes(*this);
7433         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7434
7435         if (N->use_empty()) {
7436           removeFromWorkList(N);
7437           DAG.DeleteNode(N);
7438         }
7439
7440         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7441       }
7442     } else {
7443       // Indexed loads.
7444       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7445       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7446         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7447         DEBUG(dbgs() << "\nReplacing.7 ";
7448               N->dump(&DAG);
7449               dbgs() << "\nWith: ";
7450               Undef.getNode()->dump(&DAG);
7451               dbgs() << " and 2 other values\n");
7452         WorkListRemover DeadNodes(*this);
7453         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7454         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7455                                       DAG.getUNDEF(N->getValueType(1)));
7456         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7457         removeFromWorkList(N);
7458         DAG.DeleteNode(N);
7459         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7460       }
7461     }
7462   }
7463
7464   // If this load is directly stored, replace the load value with the stored
7465   // value.
7466   // TODO: Handle store large -> read small portion.
7467   // TODO: Handle TRUNCSTORE/LOADEXT
7468   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7469     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7470       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7471       if (PrevST->getBasePtr() == Ptr &&
7472           PrevST->getValue().getValueType() == N->getValueType(0))
7473       return CombineTo(N, Chain.getOperand(1), Chain);
7474     }
7475   }
7476
7477   // Try to infer better alignment information than the load already has.
7478   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7479     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7480       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7481         SDValue NewLoad =
7482                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7483                               LD->getValueType(0),
7484                               Chain, Ptr, LD->getPointerInfo(),
7485                               LD->getMemoryVT(),
7486                               LD->isVolatile(), LD->isNonTemporal(), Align);
7487         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7488       }
7489     }
7490   }
7491
7492   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7493     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7494   if (UseAA) {
7495     // Walk up chain skipping non-aliasing memory nodes.
7496     SDValue BetterChain = FindBetterChain(N, Chain);
7497
7498     // If there is a better chain.
7499     if (Chain != BetterChain) {
7500       SDValue ReplLoad;
7501
7502       // Replace the chain to void dependency.
7503       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7504         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7505                                BetterChain, Ptr, LD->getPointerInfo(),
7506                                LD->isVolatile(), LD->isNonTemporal(),
7507                                LD->isInvariant(), LD->getAlignment());
7508       } else {
7509         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7510                                   LD->getValueType(0),
7511                                   BetterChain, Ptr, LD->getPointerInfo(),
7512                                   LD->getMemoryVT(),
7513                                   LD->isVolatile(),
7514                                   LD->isNonTemporal(),
7515                                   LD->getAlignment());
7516       }
7517
7518       // Create token factor to keep old chain connected.
7519       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7520                                   MVT::Other, Chain, ReplLoad.getValue(1));
7521
7522       // Make sure the new and old chains are cleaned up.
7523       AddToWorkList(Token.getNode());
7524
7525       // Replace uses with load result and token factor. Don't add users
7526       // to work list.
7527       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7528     }
7529   }
7530
7531   // Try transforming N to an indexed load.
7532   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7533     return SDValue(N, 0);
7534
7535   return SDValue();
7536 }
7537
7538 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7539 /// load is having specific bytes cleared out.  If so, return the byte size
7540 /// being masked out and the shift amount.
7541 static std::pair<unsigned, unsigned>
7542 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7543   std::pair<unsigned, unsigned> Result(0, 0);
7544
7545   // Check for the structure we're looking for.
7546   if (V->getOpcode() != ISD::AND ||
7547       !isa<ConstantSDNode>(V->getOperand(1)) ||
7548       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7549     return Result;
7550
7551   // Check the chain and pointer.
7552   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7553   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7554
7555   // The store should be chained directly to the load or be an operand of a
7556   // tokenfactor.
7557   if (LD == Chain.getNode())
7558     ; // ok.
7559   else if (Chain->getOpcode() != ISD::TokenFactor)
7560     return Result; // Fail.
7561   else {
7562     bool isOk = false;
7563     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7564       if (Chain->getOperand(i).getNode() == LD) {
7565         isOk = true;
7566         break;
7567       }
7568     if (!isOk) return Result;
7569   }
7570
7571   // This only handles simple types.
7572   if (V.getValueType() != MVT::i16 &&
7573       V.getValueType() != MVT::i32 &&
7574       V.getValueType() != MVT::i64)
7575     return Result;
7576
7577   // Check the constant mask.  Invert it so that the bits being masked out are
7578   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7579   // follow the sign bit for uniformity.
7580   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7581   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7582   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7583   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7584   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7585   if (NotMaskLZ == 64) return Result;  // All zero mask.
7586
7587   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7588   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7589     return Result;
7590
7591   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7592   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7593     NotMaskLZ -= 64-V.getValueSizeInBits();
7594
7595   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7596   switch (MaskedBytes) {
7597   case 1:
7598   case 2:
7599   case 4: break;
7600   default: return Result; // All one mask, or 5-byte mask.
7601   }
7602
7603   // Verify that the first bit starts at a multiple of mask so that the access
7604   // is aligned the same as the access width.
7605   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7606
7607   Result.first = MaskedBytes;
7608   Result.second = NotMaskTZ/8;
7609   return Result;
7610 }
7611
7612
7613 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7614 /// provides a value as specified by MaskInfo.  If so, replace the specified
7615 /// store with a narrower store of truncated IVal.
7616 static SDNode *
7617 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7618                                 SDValue IVal, StoreSDNode *St,
7619                                 DAGCombiner *DC) {
7620   unsigned NumBytes = MaskInfo.first;
7621   unsigned ByteShift = MaskInfo.second;
7622   SelectionDAG &DAG = DC->getDAG();
7623
7624   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7625   // that uses this.  If not, this is not a replacement.
7626   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7627                                   ByteShift*8, (ByteShift+NumBytes)*8);
7628   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7629
7630   // Check that it is legal on the target to do this.  It is legal if the new
7631   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7632   // legalization.
7633   MVT VT = MVT::getIntegerVT(NumBytes*8);
7634   if (!DC->isTypeLegal(VT))
7635     return 0;
7636
7637   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7638   // shifted by ByteShift and truncated down to NumBytes.
7639   if (ByteShift)
7640     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7641                        DAG.getConstant(ByteShift*8,
7642                                     DC->getShiftAmountTy(IVal.getValueType())));
7643
7644   // Figure out the offset for the store and the alignment of the access.
7645   unsigned StOffset;
7646   unsigned NewAlign = St->getAlignment();
7647
7648   if (DAG.getTargetLoweringInfo().isLittleEndian())
7649     StOffset = ByteShift;
7650   else
7651     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7652
7653   SDValue Ptr = St->getBasePtr();
7654   if (StOffset) {
7655     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7656                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7657     NewAlign = MinAlign(NewAlign, StOffset);
7658   }
7659
7660   // Truncate down to the new size.
7661   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7662
7663   ++OpsNarrowed;
7664   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7665                       St->getPointerInfo().getWithOffset(StOffset),
7666                       false, false, NewAlign).getNode();
7667 }
7668
7669
7670 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7671 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7672 /// of the loaded bits, try narrowing the load and store if it would end up
7673 /// being a win for performance or code size.
7674 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7675   StoreSDNode *ST  = cast<StoreSDNode>(N);
7676   if (ST->isVolatile())
7677     return SDValue();
7678
7679   SDValue Chain = ST->getChain();
7680   SDValue Value = ST->getValue();
7681   SDValue Ptr   = ST->getBasePtr();
7682   EVT VT = Value.getValueType();
7683
7684   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7685     return SDValue();
7686
7687   unsigned Opc = Value.getOpcode();
7688
7689   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7690   // is a byte mask indicating a consecutive number of bytes, check to see if
7691   // Y is known to provide just those bytes.  If so, we try to replace the
7692   // load + replace + store sequence with a single (narrower) store, which makes
7693   // the load dead.
7694   if (Opc == ISD::OR) {
7695     std::pair<unsigned, unsigned> MaskedLoad;
7696     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7697     if (MaskedLoad.first)
7698       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7699                                                   Value.getOperand(1), ST,this))
7700         return SDValue(NewST, 0);
7701
7702     // Or is commutative, so try swapping X and Y.
7703     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7704     if (MaskedLoad.first)
7705       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7706                                                   Value.getOperand(0), ST,this))
7707         return SDValue(NewST, 0);
7708   }
7709
7710   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7711       Value.getOperand(1).getOpcode() != ISD::Constant)
7712     return SDValue();
7713
7714   SDValue N0 = Value.getOperand(0);
7715   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7716       Chain == SDValue(N0.getNode(), 1)) {
7717     LoadSDNode *LD = cast<LoadSDNode>(N0);
7718     if (LD->getBasePtr() != Ptr ||
7719         LD->getPointerInfo().getAddrSpace() !=
7720         ST->getPointerInfo().getAddrSpace())
7721       return SDValue();
7722
7723     // Find the type to narrow it the load / op / store to.
7724     SDValue N1 = Value.getOperand(1);
7725     unsigned BitWidth = N1.getValueSizeInBits();
7726     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7727     if (Opc == ISD::AND)
7728       Imm ^= APInt::getAllOnesValue(BitWidth);
7729     if (Imm == 0 || Imm.isAllOnesValue())
7730       return SDValue();
7731     unsigned ShAmt = Imm.countTrailingZeros();
7732     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7733     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7734     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7735     while (NewBW < BitWidth &&
7736            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7737              TLI.isNarrowingProfitable(VT, NewVT))) {
7738       NewBW = NextPowerOf2(NewBW);
7739       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7740     }
7741     if (NewBW >= BitWidth)
7742       return SDValue();
7743
7744     // If the lsb changed does not start at the type bitwidth boundary,
7745     // start at the previous one.
7746     if (ShAmt % NewBW)
7747       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7748     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7749                                    std::min(BitWidth, ShAmt + NewBW));
7750     if ((Imm & Mask) == Imm) {
7751       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7752       if (Opc == ISD::AND)
7753         NewImm ^= APInt::getAllOnesValue(NewBW);
7754       uint64_t PtrOff = ShAmt / 8;
7755       // For big endian targets, we need to adjust the offset to the pointer to
7756       // load the correct bytes.
7757       if (TLI.isBigEndian())
7758         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7759
7760       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7761       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7762       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7763         return SDValue();
7764
7765       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7766                                    Ptr.getValueType(), Ptr,
7767                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7768       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7769                                   LD->getChain(), NewPtr,
7770                                   LD->getPointerInfo().getWithOffset(PtrOff),
7771                                   LD->isVolatile(), LD->isNonTemporal(),
7772                                   LD->isInvariant(), NewAlign);
7773       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7774                                    DAG.getConstant(NewImm, NewVT));
7775       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7776                                    NewVal, NewPtr,
7777                                    ST->getPointerInfo().getWithOffset(PtrOff),
7778                                    false, false, NewAlign);
7779
7780       AddToWorkList(NewPtr.getNode());
7781       AddToWorkList(NewLD.getNode());
7782       AddToWorkList(NewVal.getNode());
7783       WorkListRemover DeadNodes(*this);
7784       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7785       ++OpsNarrowed;
7786       return NewST;
7787     }
7788   }
7789
7790   return SDValue();
7791 }
7792
7793 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7794 /// if the load value isn't used by any other operations, then consider
7795 /// transforming the pair to integer load / store operations if the target
7796 /// deems the transformation profitable.
7797 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7798   StoreSDNode *ST  = cast<StoreSDNode>(N);
7799   SDValue Chain = ST->getChain();
7800   SDValue Value = ST->getValue();
7801   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7802       Value.hasOneUse() &&
7803       Chain == SDValue(Value.getNode(), 1)) {
7804     LoadSDNode *LD = cast<LoadSDNode>(Value);
7805     EVT VT = LD->getMemoryVT();
7806     if (!VT.isFloatingPoint() ||
7807         VT != ST->getMemoryVT() ||
7808         LD->isNonTemporal() ||
7809         ST->isNonTemporal() ||
7810         LD->getPointerInfo().getAddrSpace() != 0 ||
7811         ST->getPointerInfo().getAddrSpace() != 0)
7812       return SDValue();
7813
7814     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7815     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7816         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7817         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7818         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7819       return SDValue();
7820
7821     unsigned LDAlign = LD->getAlignment();
7822     unsigned STAlign = ST->getAlignment();
7823     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7824     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7825     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7826       return SDValue();
7827
7828     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7829                                 LD->getChain(), LD->getBasePtr(),
7830                                 LD->getPointerInfo(),
7831                                 false, false, false, LDAlign);
7832
7833     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7834                                  NewLD, ST->getBasePtr(),
7835                                  ST->getPointerInfo(),
7836                                  false, false, STAlign);
7837
7838     AddToWorkList(NewLD.getNode());
7839     AddToWorkList(NewST.getNode());
7840     WorkListRemover DeadNodes(*this);
7841     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7842     ++LdStFP2Int;
7843     return NewST;
7844   }
7845
7846   return SDValue();
7847 }
7848
7849 /// Helper struct to parse and store a memory address as base + index + offset.
7850 /// We ignore sign extensions when it is safe to do so.
7851 /// The following two expressions are not equivalent. To differentiate we need
7852 /// to store whether there was a sign extension involved in the index
7853 /// computation.
7854 ///  (load (i64 add (i64 copyfromreg %c)
7855 ///                 (i64 signextend (add (i8 load %index)
7856 ///                                      (i8 1))))
7857 /// vs
7858 ///
7859 /// (load (i64 add (i64 copyfromreg %c)
7860 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7861 ///                                         (i32 1)))))
7862 struct BaseIndexOffset {
7863   SDValue Base;
7864   SDValue Index;
7865   int64_t Offset;
7866   bool IsIndexSignExt;
7867
7868   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7869
7870   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7871                   bool IsIndexSignExt) :
7872     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7873
7874   bool equalBaseIndex(const BaseIndexOffset &Other) {
7875     return Other.Base == Base && Other.Index == Index &&
7876       Other.IsIndexSignExt == IsIndexSignExt;
7877   }
7878
7879   /// Parses tree in Ptr for base, index, offset addresses.
7880   static BaseIndexOffset match(SDValue Ptr) {
7881     bool IsIndexSignExt = false;
7882
7883     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7884     // instruction, then it could be just the BASE or everything else we don't
7885     // know how to handle. Just use Ptr as BASE and give up.
7886     if (Ptr->getOpcode() != ISD::ADD)
7887       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7888
7889     // We know that we have at least an ADD instruction. Try to pattern match
7890     // the simple case of BASE + OFFSET.
7891     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7892       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7893       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7894                               IsIndexSignExt);
7895     }
7896
7897     // Inside a loop the current BASE pointer is calculated using an ADD and a
7898     // MUL instruction. In this case Ptr is the actual BASE pointer.
7899     // (i64 add (i64 %array_ptr)
7900     //          (i64 mul (i64 %induction_var)
7901     //                   (i64 %element_size)))
7902     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7903       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7904
7905     // Look at Base + Index + Offset cases.
7906     SDValue Base = Ptr->getOperand(0);
7907     SDValue IndexOffset = Ptr->getOperand(1);
7908
7909     // Skip signextends.
7910     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7911       IndexOffset = IndexOffset->getOperand(0);
7912       IsIndexSignExt = true;
7913     }
7914
7915     // Either the case of Base + Index (no offset) or something else.
7916     if (IndexOffset->getOpcode() != ISD::ADD)
7917       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7918
7919     // Now we have the case of Base + Index + offset.
7920     SDValue Index = IndexOffset->getOperand(0);
7921     SDValue Offset = IndexOffset->getOperand(1);
7922
7923     if (!isa<ConstantSDNode>(Offset))
7924       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7925
7926     // Ignore signextends.
7927     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7928       Index = Index->getOperand(0);
7929       IsIndexSignExt = true;
7930     } else IsIndexSignExt = false;
7931
7932     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7933     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7934   }
7935 };
7936
7937 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7938 /// is located in a sequence of memory operations connected by a chain.
7939 struct MemOpLink {
7940   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7941     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7942   // Ptr to the mem node.
7943   LSBaseSDNode *MemNode;
7944   // Offset from the base ptr.
7945   int64_t OffsetFromBase;
7946   // What is the sequence number of this mem node.
7947   // Lowest mem operand in the DAG starts at zero.
7948   unsigned SequenceNum;
7949 };
7950
7951 /// Sorts store nodes in a link according to their offset from a shared
7952 // base ptr.
7953 struct ConsecutiveMemoryChainSorter {
7954   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7955     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7956   }
7957 };
7958
7959 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7960   EVT MemVT = St->getMemoryVT();
7961   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7962   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7963     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7964
7965   // Don't merge vectors into wider inputs.
7966   if (MemVT.isVector() || !MemVT.isSimple())
7967     return false;
7968
7969   // Perform an early exit check. Do not bother looking at stored values that
7970   // are not constants or loads.
7971   SDValue StoredVal = St->getValue();
7972   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7973   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7974       !IsLoadSrc)
7975     return false;
7976
7977   // Only look at ends of store sequences.
7978   SDValue Chain = SDValue(St, 1);
7979   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7980     return false;
7981
7982   // This holds the base pointer, index, and the offset in bytes from the base
7983   // pointer.
7984   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7985
7986   // We must have a base and an offset.
7987   if (!BasePtr.Base.getNode())
7988     return false;
7989
7990   // Do not handle stores to undef base pointers.
7991   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7992     return false;
7993
7994   // Save the LoadSDNodes that we find in the chain.
7995   // We need to make sure that these nodes do not interfere with
7996   // any of the store nodes.
7997   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7998
7999   // Save the StoreSDNodes that we find in the chain.
8000   SmallVector<MemOpLink, 8> StoreNodes;
8001
8002   // Walk up the chain and look for nodes with offsets from the same
8003   // base pointer. Stop when reaching an instruction with a different kind
8004   // or instruction which has a different base pointer.
8005   unsigned Seq = 0;
8006   StoreSDNode *Index = St;
8007   while (Index) {
8008     // If the chain has more than one use, then we can't reorder the mem ops.
8009     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8010       break;
8011
8012     // Find the base pointer and offset for this memory node.
8013     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8014
8015     // Check that the base pointer is the same as the original one.
8016     if (!Ptr.equalBaseIndex(BasePtr))
8017       break;
8018
8019     // Check that the alignment is the same.
8020     if (Index->getAlignment() != St->getAlignment())
8021       break;
8022
8023     // The memory operands must not be volatile.
8024     if (Index->isVolatile() || Index->isIndexed())
8025       break;
8026
8027     // No truncation.
8028     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8029       if (St->isTruncatingStore())
8030         break;
8031
8032     // The stored memory type must be the same.
8033     if (Index->getMemoryVT() != MemVT)
8034       break;
8035
8036     // We do not allow unaligned stores because we want to prevent overriding
8037     // stores.
8038     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8039       break;
8040
8041     // We found a potential memory operand to merge.
8042     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8043
8044     // Find the next memory operand in the chain. If the next operand in the
8045     // chain is a store then move up and continue the scan with the next
8046     // memory operand. If the next operand is a load save it and use alias
8047     // information to check if it interferes with anything.
8048     SDNode *NextInChain = Index->getChain().getNode();
8049     while (1) {
8050       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8051         // We found a store node. Use it for the next iteration.
8052         Index = STn;
8053         break;
8054       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8055         // Save the load node for later. Continue the scan.
8056         AliasLoadNodes.push_back(Ldn);
8057         NextInChain = Ldn->getChain().getNode();
8058         continue;
8059       } else {
8060         Index = NULL;
8061         break;
8062       }
8063     }
8064   }
8065
8066   // Check if there is anything to merge.
8067   if (StoreNodes.size() < 2)
8068     return false;
8069
8070   // Sort the memory operands according to their distance from the base pointer.
8071   std::sort(StoreNodes.begin(), StoreNodes.end(),
8072             ConsecutiveMemoryChainSorter());
8073
8074   // Scan the memory operations on the chain and find the first non-consecutive
8075   // store memory address.
8076   unsigned LastConsecutiveStore = 0;
8077   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8078   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8079
8080     // Check that the addresses are consecutive starting from the second
8081     // element in the list of stores.
8082     if (i > 0) {
8083       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8084       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8085         break;
8086     }
8087
8088     bool Alias = false;
8089     // Check if this store interferes with any of the loads that we found.
8090     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8091       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8092         Alias = true;
8093         break;
8094       }
8095     // We found a load that alias with this store. Stop the sequence.
8096     if (Alias)
8097       break;
8098
8099     // Mark this node as useful.
8100     LastConsecutiveStore = i;
8101   }
8102
8103   // The node with the lowest store address.
8104   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8105
8106   // Store the constants into memory as one consecutive store.
8107   if (!IsLoadSrc) {
8108     unsigned LastLegalType = 0;
8109     unsigned LastLegalVectorType = 0;
8110     bool NonZero = false;
8111     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8112       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8113       SDValue StoredVal = St->getValue();
8114
8115       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8116         NonZero |= !C->isNullValue();
8117       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8118         NonZero |= !C->getConstantFPValue()->isNullValue();
8119       } else {
8120         // Non constant.
8121         break;
8122       }
8123
8124       // Find a legal type for the constant store.
8125       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8126       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8127       if (TLI.isTypeLegal(StoreTy))
8128         LastLegalType = i+1;
8129       // Or check whether a truncstore is legal.
8130       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8131                TargetLowering::TypePromoteInteger) {
8132         EVT LegalizedStoredValueTy =
8133           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8134         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8135           LastLegalType = i+1;
8136       }
8137
8138       // Find a legal type for the vector store.
8139       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8140       if (TLI.isTypeLegal(Ty))
8141         LastLegalVectorType = i + 1;
8142     }
8143
8144     // We only use vectors if the constant is known to be zero and the
8145     // function is not marked with the noimplicitfloat attribute.
8146     if (NonZero || NoVectors)
8147       LastLegalVectorType = 0;
8148
8149     // Check if we found a legal integer type to store.
8150     if (LastLegalType == 0 && LastLegalVectorType == 0)
8151       return false;
8152
8153     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8154     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8155
8156     // Make sure we have something to merge.
8157     if (NumElem < 2)
8158       return false;
8159
8160     unsigned EarliestNodeUsed = 0;
8161     for (unsigned i=0; i < NumElem; ++i) {
8162       // Find a chain for the new wide-store operand. Notice that some
8163       // of the store nodes that we found may not be selected for inclusion
8164       // in the wide store. The chain we use needs to be the chain of the
8165       // earliest store node which is *used* and replaced by the wide store.
8166       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8167         EarliestNodeUsed = i;
8168     }
8169
8170     // The earliest Node in the DAG.
8171     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8172     SDLoc DL(StoreNodes[0].MemNode);
8173
8174     SDValue StoredVal;
8175     if (UseVector) {
8176       // Find a legal type for the vector store.
8177       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8178       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8179       StoredVal = DAG.getConstant(0, Ty);
8180     } else {
8181       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8182       APInt StoreInt(StoreBW, 0);
8183
8184       // Construct a single integer constant which is made of the smaller
8185       // constant inputs.
8186       bool IsLE = TLI.isLittleEndian();
8187       for (unsigned i = 0; i < NumElem ; ++i) {
8188         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8189         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8190         SDValue Val = St->getValue();
8191         StoreInt<<=ElementSizeBytes*8;
8192         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8193           StoreInt|=C->getAPIntValue().zext(StoreBW);
8194         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8195           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8196         } else {
8197           assert(false && "Invalid constant element type");
8198         }
8199       }
8200
8201       // Create the new Load and Store operations.
8202       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8203       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8204     }
8205
8206     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8207                                     FirstInChain->getBasePtr(),
8208                                     FirstInChain->getPointerInfo(),
8209                                     false, false,
8210                                     FirstInChain->getAlignment());
8211
8212     // Replace the first store with the new store
8213     CombineTo(EarliestOp, NewStore);
8214     // Erase all other stores.
8215     for (unsigned i = 0; i < NumElem ; ++i) {
8216       if (StoreNodes[i].MemNode == EarliestOp)
8217         continue;
8218       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8219       // ReplaceAllUsesWith will replace all uses that existed when it was
8220       // called, but graph optimizations may cause new ones to appear. For
8221       // example, the case in pr14333 looks like
8222       //
8223       //  St's chain -> St -> another store -> X
8224       //
8225       // And the only difference from St to the other store is the chain.
8226       // When we change it's chain to be St's chain they become identical,
8227       // get CSEed and the net result is that X is now a use of St.
8228       // Since we know that St is redundant, just iterate.
8229       while (!St->use_empty())
8230         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8231       removeFromWorkList(St);
8232       DAG.DeleteNode(St);
8233     }
8234
8235     return true;
8236   }
8237
8238   // Below we handle the case of multiple consecutive stores that
8239   // come from multiple consecutive loads. We merge them into a single
8240   // wide load and a single wide store.
8241
8242   // Look for load nodes which are used by the stored values.
8243   SmallVector<MemOpLink, 8> LoadNodes;
8244
8245   // Find acceptable loads. Loads need to have the same chain (token factor),
8246   // must not be zext, volatile, indexed, and they must be consecutive.
8247   BaseIndexOffset LdBasePtr;
8248   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8249     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8250     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8251     if (!Ld) break;
8252
8253     // Loads must only have one use.
8254     if (!Ld->hasNUsesOfValue(1, 0))
8255       break;
8256
8257     // Check that the alignment is the same as the stores.
8258     if (Ld->getAlignment() != St->getAlignment())
8259       break;
8260
8261     // The memory operands must not be volatile.
8262     if (Ld->isVolatile() || Ld->isIndexed())
8263       break;
8264
8265     // We do not accept ext loads.
8266     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8267       break;
8268
8269     // The stored memory type must be the same.
8270     if (Ld->getMemoryVT() != MemVT)
8271       break;
8272
8273     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8274     // If this is not the first ptr that we check.
8275     if (LdBasePtr.Base.getNode()) {
8276       // The base ptr must be the same.
8277       if (!LdPtr.equalBaseIndex(LdBasePtr))
8278         break;
8279     } else {
8280       // Check that all other base pointers are the same as this one.
8281       LdBasePtr = LdPtr;
8282     }
8283
8284     // We found a potential memory operand to merge.
8285     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8286   }
8287
8288   if (LoadNodes.size() < 2)
8289     return false;
8290
8291   // Scan the memory operations on the chain and find the first non-consecutive
8292   // load memory address. These variables hold the index in the store node
8293   // array.
8294   unsigned LastConsecutiveLoad = 0;
8295   // This variable refers to the size and not index in the array.
8296   unsigned LastLegalVectorType = 0;
8297   unsigned LastLegalIntegerType = 0;
8298   StartAddress = LoadNodes[0].OffsetFromBase;
8299   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8300   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8301     // All loads much share the same chain.
8302     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8303       break;
8304
8305     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8306     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8307       break;
8308     LastConsecutiveLoad = i;
8309
8310     // Find a legal type for the vector store.
8311     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8312     if (TLI.isTypeLegal(StoreTy))
8313       LastLegalVectorType = i + 1;
8314
8315     // Find a legal type for the integer store.
8316     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8317     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8318     if (TLI.isTypeLegal(StoreTy))
8319       LastLegalIntegerType = i + 1;
8320     // Or check whether a truncstore and extload is legal.
8321     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8322              TargetLowering::TypePromoteInteger) {
8323       EVT LegalizedStoredValueTy =
8324         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8325       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8326           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8327           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8328           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8329         LastLegalIntegerType = i+1;
8330     }
8331   }
8332
8333   // Only use vector types if the vector type is larger than the integer type.
8334   // If they are the same, use integers.
8335   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8336   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8337
8338   // We add +1 here because the LastXXX variables refer to location while
8339   // the NumElem refers to array/index size.
8340   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8341   NumElem = std::min(LastLegalType, NumElem);
8342
8343   if (NumElem < 2)
8344     return false;
8345
8346   // The earliest Node in the DAG.
8347   unsigned EarliestNodeUsed = 0;
8348   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8349   for (unsigned i=1; i<NumElem; ++i) {
8350     // Find a chain for the new wide-store operand. Notice that some
8351     // of the store nodes that we found may not be selected for inclusion
8352     // in the wide store. The chain we use needs to be the chain of the
8353     // earliest store node which is *used* and replaced by the wide store.
8354     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8355       EarliestNodeUsed = i;
8356   }
8357
8358   // Find if it is better to use vectors or integers to load and store
8359   // to memory.
8360   EVT JointMemOpVT;
8361   if (UseVectorTy) {
8362     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8363   } else {
8364     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8365     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8366   }
8367
8368   SDLoc LoadDL(LoadNodes[0].MemNode);
8369   SDLoc StoreDL(StoreNodes[0].MemNode);
8370
8371   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8372   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8373                                 FirstLoad->getChain(),
8374                                 FirstLoad->getBasePtr(),
8375                                 FirstLoad->getPointerInfo(),
8376                                 false, false, false,
8377                                 FirstLoad->getAlignment());
8378
8379   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8380                                   FirstInChain->getBasePtr(),
8381                                   FirstInChain->getPointerInfo(), false, false,
8382                                   FirstInChain->getAlignment());
8383
8384   // Replace one of the loads with the new load.
8385   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8386   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8387                                 SDValue(NewLoad.getNode(), 1));
8388
8389   // Remove the rest of the load chains.
8390   for (unsigned i = 1; i < NumElem ; ++i) {
8391     // Replace all chain users of the old load nodes with the chain of the new
8392     // load node.
8393     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8394     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8395   }
8396
8397   // Replace the first store with the new store.
8398   CombineTo(EarliestOp, NewStore);
8399   // Erase all other stores.
8400   for (unsigned i = 0; i < NumElem ; ++i) {
8401     // Remove all Store nodes.
8402     if (StoreNodes[i].MemNode == EarliestOp)
8403       continue;
8404     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8405     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8406     removeFromWorkList(St);
8407     DAG.DeleteNode(St);
8408   }
8409
8410   return true;
8411 }
8412
8413 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8414   StoreSDNode *ST  = cast<StoreSDNode>(N);
8415   SDValue Chain = ST->getChain();
8416   SDValue Value = ST->getValue();
8417   SDValue Ptr   = ST->getBasePtr();
8418
8419   // If this is a store of a bit convert, store the input value if the
8420   // resultant store does not need a higher alignment than the original.
8421   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8422       ST->isUnindexed()) {
8423     unsigned OrigAlign = ST->getAlignment();
8424     EVT SVT = Value.getOperand(0).getValueType();
8425     unsigned Align = TLI.getDataLayout()->
8426       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8427     if (Align <= OrigAlign &&
8428         ((!LegalOperations && !ST->isVolatile()) ||
8429          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8430       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8431                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8432                           ST->isNonTemporal(), OrigAlign);
8433   }
8434
8435   // Turn 'store undef, Ptr' -> nothing.
8436   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8437     return Chain;
8438
8439   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8440   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8441     // NOTE: If the original store is volatile, this transform must not increase
8442     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8443     // processor operation but an i64 (which is not legal) requires two.  So the
8444     // transform should not be done in this case.
8445     if (Value.getOpcode() != ISD::TargetConstantFP) {
8446       SDValue Tmp;
8447       switch (CFP->getSimpleValueType(0).SimpleTy) {
8448       default: llvm_unreachable("Unknown FP type");
8449       case MVT::f16:    // We don't do this for these yet.
8450       case MVT::f80:
8451       case MVT::f128:
8452       case MVT::ppcf128:
8453         break;
8454       case MVT::f32:
8455         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8456             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8457           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8458                               bitcastToAPInt().getZExtValue(), MVT::i32);
8459           return DAG.getStore(Chain, SDLoc(N), Tmp,
8460                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8461                               ST->isNonTemporal(), ST->getAlignment());
8462         }
8463         break;
8464       case MVT::f64:
8465         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8466              !ST->isVolatile()) ||
8467             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8468           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8469                                 getZExtValue(), MVT::i64);
8470           return DAG.getStore(Chain, SDLoc(N), Tmp,
8471                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8472                               ST->isNonTemporal(), ST->getAlignment());
8473         }
8474
8475         if (!ST->isVolatile() &&
8476             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8477           // Many FP stores are not made apparent until after legalize, e.g. for
8478           // argument passing.  Since this is so common, custom legalize the
8479           // 64-bit integer store into two 32-bit stores.
8480           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8481           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8482           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8483           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8484
8485           unsigned Alignment = ST->getAlignment();
8486           bool isVolatile = ST->isVolatile();
8487           bool isNonTemporal = ST->isNonTemporal();
8488
8489           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8490                                      Ptr, ST->getPointerInfo(),
8491                                      isVolatile, isNonTemporal,
8492                                      ST->getAlignment());
8493           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8494                             DAG.getConstant(4, Ptr.getValueType()));
8495           Alignment = MinAlign(Alignment, 4U);
8496           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8497                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8498                                      isVolatile, isNonTemporal,
8499                                      Alignment);
8500           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8501                              St0, St1);
8502         }
8503
8504         break;
8505       }
8506     }
8507   }
8508
8509   // Try to infer better alignment information than the store already has.
8510   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8511     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8512       if (Align > ST->getAlignment())
8513         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8514                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8515                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8516     }
8517   }
8518
8519   // Try transforming a pair floating point load / store ops to integer
8520   // load / store ops.
8521   SDValue NewST = TransformFPLoadStorePair(N);
8522   if (NewST.getNode())
8523     return NewST;
8524
8525   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8526     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8527   if (UseAA) {
8528     // Walk up chain skipping non-aliasing memory nodes.
8529     SDValue BetterChain = FindBetterChain(N, Chain);
8530
8531     // If there is a better chain.
8532     if (Chain != BetterChain) {
8533       SDValue ReplStore;
8534
8535       // Replace the chain to avoid dependency.
8536       if (ST->isTruncatingStore()) {
8537         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8538                                       ST->getPointerInfo(),
8539                                       ST->getMemoryVT(), ST->isVolatile(),
8540                                       ST->isNonTemporal(), ST->getAlignment());
8541       } else {
8542         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8543                                  ST->getPointerInfo(),
8544                                  ST->isVolatile(), ST->isNonTemporal(),
8545                                  ST->getAlignment());
8546       }
8547
8548       // Create token to keep both nodes around.
8549       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8550                                   MVT::Other, Chain, ReplStore);
8551
8552       // Make sure the new and old chains are cleaned up.
8553       AddToWorkList(Token.getNode());
8554
8555       // Don't add users to work list.
8556       return CombineTo(N, Token, false);
8557     }
8558   }
8559
8560   // Try transforming N to an indexed store.
8561   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8562     return SDValue(N, 0);
8563
8564   // FIXME: is there such a thing as a truncating indexed store?
8565   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8566       Value.getValueType().isInteger()) {
8567     // See if we can simplify the input to this truncstore with knowledge that
8568     // only the low bits are being used.  For example:
8569     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8570     SDValue Shorter =
8571       GetDemandedBits(Value,
8572                       APInt::getLowBitsSet(
8573                         Value.getValueType().getScalarType().getSizeInBits(),
8574                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8575     AddToWorkList(Value.getNode());
8576     if (Shorter.getNode())
8577       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8578                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8579                                ST->isVolatile(), ST->isNonTemporal(),
8580                                ST->getAlignment());
8581
8582     // Otherwise, see if we can simplify the operation with
8583     // SimplifyDemandedBits, which only works if the value has a single use.
8584     if (SimplifyDemandedBits(Value,
8585                         APInt::getLowBitsSet(
8586                           Value.getValueType().getScalarType().getSizeInBits(),
8587                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8588       return SDValue(N, 0);
8589   }
8590
8591   // If this is a load followed by a store to the same location, then the store
8592   // is dead/noop.
8593   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8594     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8595         ST->isUnindexed() && !ST->isVolatile() &&
8596         // There can't be any side effects between the load and store, such as
8597         // a call or store.
8598         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8599       // The store is dead, remove it.
8600       return Chain;
8601     }
8602   }
8603
8604   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8605   // truncating store.  We can do this even if this is already a truncstore.
8606   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8607       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8608       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8609                             ST->getMemoryVT())) {
8610     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8611                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8612                              ST->isVolatile(), ST->isNonTemporal(),
8613                              ST->getAlignment());
8614   }
8615
8616   // Only perform this optimization before the types are legal, because we
8617   // don't want to perform this optimization on every DAGCombine invocation.
8618   if (!LegalTypes) {
8619     bool EverChanged = false;
8620
8621     do {
8622       // There can be multiple store sequences on the same chain.
8623       // Keep trying to merge store sequences until we are unable to do so
8624       // or until we merge the last store on the chain.
8625       bool Changed = MergeConsecutiveStores(ST);
8626       EverChanged |= Changed;
8627       if (!Changed) break;
8628     } while (ST->getOpcode() != ISD::DELETED_NODE);
8629
8630     if (EverChanged)
8631       return SDValue(N, 0);
8632   }
8633
8634   return ReduceLoadOpStoreWidth(N);
8635 }
8636
8637 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8638   SDValue InVec = N->getOperand(0);
8639   SDValue InVal = N->getOperand(1);
8640   SDValue EltNo = N->getOperand(2);
8641   SDLoc dl(N);
8642
8643   // If the inserted element is an UNDEF, just use the input vector.
8644   if (InVal.getOpcode() == ISD::UNDEF)
8645     return InVec;
8646
8647   EVT VT = InVec.getValueType();
8648
8649   // If we can't generate a legal BUILD_VECTOR, exit
8650   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8651     return SDValue();
8652
8653   // Check that we know which element is being inserted
8654   if (!isa<ConstantSDNode>(EltNo))
8655     return SDValue();
8656   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8657
8658   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8659   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8660   // vector elements.
8661   SmallVector<SDValue, 8> Ops;
8662   // Do not combine these two vectors if the output vector will not replace
8663   // the input vector.
8664   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8665     Ops.append(InVec.getNode()->op_begin(),
8666                InVec.getNode()->op_end());
8667   } else if (InVec.getOpcode() == ISD::UNDEF) {
8668     unsigned NElts = VT.getVectorNumElements();
8669     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8670   } else {
8671     return SDValue();
8672   }
8673
8674   // Insert the element
8675   if (Elt < Ops.size()) {
8676     // All the operands of BUILD_VECTOR must have the same type;
8677     // we enforce that here.
8678     EVT OpVT = Ops[0].getValueType();
8679     if (InVal.getValueType() != OpVT)
8680       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8681                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8682                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8683     Ops[Elt] = InVal;
8684   }
8685
8686   // Return the new vector
8687   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8688                      VT, &Ops[0], Ops.size());
8689 }
8690
8691 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8692   // (vextract (scalar_to_vector val, 0) -> val
8693   SDValue InVec = N->getOperand(0);
8694   EVT VT = InVec.getValueType();
8695   EVT NVT = N->getValueType(0);
8696
8697   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8698     // Check if the result type doesn't match the inserted element type. A
8699     // SCALAR_TO_VECTOR may truncate the inserted element and the
8700     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8701     SDValue InOp = InVec.getOperand(0);
8702     if (InOp.getValueType() != NVT) {
8703       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8704       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8705     }
8706     return InOp;
8707   }
8708
8709   SDValue EltNo = N->getOperand(1);
8710   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8711
8712   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8713   // We only perform this optimization before the op legalization phase because
8714   // we may introduce new vector instructions which are not backed by TD
8715   // patterns. For example on AVX, extracting elements from a wide vector
8716   // without using extract_subvector.
8717   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8718       && ConstEltNo && !LegalOperations) {
8719     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8720     int NumElem = VT.getVectorNumElements();
8721     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8722     // Find the new index to extract from.
8723     int OrigElt = SVOp->getMaskElt(Elt);
8724
8725     // Extracting an undef index is undef.
8726     if (OrigElt == -1)
8727       return DAG.getUNDEF(NVT);
8728
8729     // Select the right vector half to extract from.
8730     if (OrigElt < NumElem) {
8731       InVec = InVec->getOperand(0);
8732     } else {
8733       InVec = InVec->getOperand(1);
8734       OrigElt -= NumElem;
8735     }
8736
8737     EVT IndexTy = TLI.getVectorIdxTy();
8738     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8739                        InVec, DAG.getConstant(OrigElt, IndexTy));
8740   }
8741
8742   // Perform only after legalization to ensure build_vector / vector_shuffle
8743   // optimizations have already been done.
8744   if (!LegalOperations) return SDValue();
8745
8746   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8747   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8748   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8749
8750   if (ConstEltNo) {
8751     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8752     bool NewLoad = false;
8753     bool BCNumEltsChanged = false;
8754     EVT ExtVT = VT.getVectorElementType();
8755     EVT LVT = ExtVT;
8756
8757     // If the result of load has to be truncated, then it's not necessarily
8758     // profitable.
8759     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8760       return SDValue();
8761
8762     if (InVec.getOpcode() == ISD::BITCAST) {
8763       // Don't duplicate a load with other uses.
8764       if (!InVec.hasOneUse())
8765         return SDValue();
8766
8767       EVT BCVT = InVec.getOperand(0).getValueType();
8768       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8769         return SDValue();
8770       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8771         BCNumEltsChanged = true;
8772       InVec = InVec.getOperand(0);
8773       ExtVT = BCVT.getVectorElementType();
8774       NewLoad = true;
8775     }
8776
8777     LoadSDNode *LN0 = NULL;
8778     const ShuffleVectorSDNode *SVN = NULL;
8779     if (ISD::isNormalLoad(InVec.getNode())) {
8780       LN0 = cast<LoadSDNode>(InVec);
8781     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8782                InVec.getOperand(0).getValueType() == ExtVT &&
8783                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8784       // Don't duplicate a load with other uses.
8785       if (!InVec.hasOneUse())
8786         return SDValue();
8787
8788       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8789     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8790       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8791       // =>
8792       // (load $addr+1*size)
8793
8794       // Don't duplicate a load with other uses.
8795       if (!InVec.hasOneUse())
8796         return SDValue();
8797
8798       // If the bit convert changed the number of elements, it is unsafe
8799       // to examine the mask.
8800       if (BCNumEltsChanged)
8801         return SDValue();
8802
8803       // Select the input vector, guarding against out of range extract vector.
8804       unsigned NumElems = VT.getVectorNumElements();
8805       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8806       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8807
8808       if (InVec.getOpcode() == ISD::BITCAST) {
8809         // Don't duplicate a load with other uses.
8810         if (!InVec.hasOneUse())
8811           return SDValue();
8812
8813         InVec = InVec.getOperand(0);
8814       }
8815       if (ISD::isNormalLoad(InVec.getNode())) {
8816         LN0 = cast<LoadSDNode>(InVec);
8817         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8818       }
8819     }
8820
8821     // Make sure we found a non-volatile load and the extractelement is
8822     // the only use.
8823     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8824       return SDValue();
8825
8826     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8827     if (Elt == -1)
8828       return DAG.getUNDEF(LVT);
8829
8830     unsigned Align = LN0->getAlignment();
8831     if (NewLoad) {
8832       // Check the resultant load doesn't need a higher alignment than the
8833       // original load.
8834       unsigned NewAlign =
8835         TLI.getDataLayout()
8836             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8837
8838       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8839         return SDValue();
8840
8841       Align = NewAlign;
8842     }
8843
8844     SDValue NewPtr = LN0->getBasePtr();
8845     unsigned PtrOff = 0;
8846
8847     if (Elt) {
8848       PtrOff = LVT.getSizeInBits() * Elt / 8;
8849       EVT PtrType = NewPtr.getValueType();
8850       if (TLI.isBigEndian())
8851         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8852       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8853                            DAG.getConstant(PtrOff, PtrType));
8854     }
8855
8856     // The replacement we need to do here is a little tricky: we need to
8857     // replace an extractelement of a load with a load.
8858     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8859     // Note that this replacement assumes that the extractvalue is the only
8860     // use of the load; that's okay because we don't want to perform this
8861     // transformation in other cases anyway.
8862     SDValue Load;
8863     SDValue Chain;
8864     if (NVT.bitsGT(LVT)) {
8865       // If the result type of vextract is wider than the load, then issue an
8866       // extending load instead.
8867       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8868         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8869       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8870                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8871                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8872       Chain = Load.getValue(1);
8873     } else {
8874       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8875                          LN0->getPointerInfo().getWithOffset(PtrOff),
8876                          LN0->isVolatile(), LN0->isNonTemporal(),
8877                          LN0->isInvariant(), Align);
8878       Chain = Load.getValue(1);
8879       if (NVT.bitsLT(LVT))
8880         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8881       else
8882         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8883     }
8884     WorkListRemover DeadNodes(*this);
8885     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8886     SDValue To[] = { Load, Chain };
8887     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8888     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8889     // worklist explicitly as well.
8890     AddToWorkList(Load.getNode());
8891     AddUsersToWorkList(Load.getNode()); // Add users too
8892     // Make sure to revisit this node to clean it up; it will usually be dead.
8893     AddToWorkList(N);
8894     return SDValue(N, 0);
8895   }
8896
8897   return SDValue();
8898 }
8899
8900 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8901 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8902   // We perform this optimization post type-legalization because
8903   // the type-legalizer often scalarizes integer-promoted vectors.
8904   // Performing this optimization before may create bit-casts which
8905   // will be type-legalized to complex code sequences.
8906   // We perform this optimization only before the operation legalizer because we
8907   // may introduce illegal operations.
8908   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8909     return SDValue();
8910
8911   unsigned NumInScalars = N->getNumOperands();
8912   SDLoc dl(N);
8913   EVT VT = N->getValueType(0);
8914
8915   // Check to see if this is a BUILD_VECTOR of a bunch of values
8916   // which come from any_extend or zero_extend nodes. If so, we can create
8917   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8918   // optimizations. We do not handle sign-extend because we can't fill the sign
8919   // using shuffles.
8920   EVT SourceType = MVT::Other;
8921   bool AllAnyExt = true;
8922
8923   for (unsigned i = 0; i != NumInScalars; ++i) {
8924     SDValue In = N->getOperand(i);
8925     // Ignore undef inputs.
8926     if (In.getOpcode() == ISD::UNDEF) continue;
8927
8928     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8929     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8930
8931     // Abort if the element is not an extension.
8932     if (!ZeroExt && !AnyExt) {
8933       SourceType = MVT::Other;
8934       break;
8935     }
8936
8937     // The input is a ZeroExt or AnyExt. Check the original type.
8938     EVT InTy = In.getOperand(0).getValueType();
8939
8940     // Check that all of the widened source types are the same.
8941     if (SourceType == MVT::Other)
8942       // First time.
8943       SourceType = InTy;
8944     else if (InTy != SourceType) {
8945       // Multiple income types. Abort.
8946       SourceType = MVT::Other;
8947       break;
8948     }
8949
8950     // Check if all of the extends are ANY_EXTENDs.
8951     AllAnyExt &= AnyExt;
8952   }
8953
8954   // In order to have valid types, all of the inputs must be extended from the
8955   // same source type and all of the inputs must be any or zero extend.
8956   // Scalar sizes must be a power of two.
8957   EVT OutScalarTy = VT.getScalarType();
8958   bool ValidTypes = SourceType != MVT::Other &&
8959                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8960                  isPowerOf2_32(SourceType.getSizeInBits());
8961
8962   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8963   // turn into a single shuffle instruction.
8964   if (!ValidTypes)
8965     return SDValue();
8966
8967   bool isLE = TLI.isLittleEndian();
8968   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8969   assert(ElemRatio > 1 && "Invalid element size ratio");
8970   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8971                                DAG.getConstant(0, SourceType);
8972
8973   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8974   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8975
8976   // Populate the new build_vector
8977   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8978     SDValue Cast = N->getOperand(i);
8979     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8980             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8981             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8982     SDValue In;
8983     if (Cast.getOpcode() == ISD::UNDEF)
8984       In = DAG.getUNDEF(SourceType);
8985     else
8986       In = Cast->getOperand(0);
8987     unsigned Index = isLE ? (i * ElemRatio) :
8988                             (i * ElemRatio + (ElemRatio - 1));
8989
8990     assert(Index < Ops.size() && "Invalid index");
8991     Ops[Index] = In;
8992   }
8993
8994   // The type of the new BUILD_VECTOR node.
8995   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8996   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8997          "Invalid vector size");
8998   // Check if the new vector type is legal.
8999   if (!isTypeLegal(VecVT)) return SDValue();
9000
9001   // Make the new BUILD_VECTOR.
9002   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9003
9004   // The new BUILD_VECTOR node has the potential to be further optimized.
9005   AddToWorkList(BV.getNode());
9006   // Bitcast to the desired type.
9007   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9008 }
9009
9010 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9011   EVT VT = N->getValueType(0);
9012
9013   unsigned NumInScalars = N->getNumOperands();
9014   SDLoc dl(N);
9015
9016   EVT SrcVT = MVT::Other;
9017   unsigned Opcode = ISD::DELETED_NODE;
9018   unsigned NumDefs = 0;
9019
9020   for (unsigned i = 0; i != NumInScalars; ++i) {
9021     SDValue In = N->getOperand(i);
9022     unsigned Opc = In.getOpcode();
9023
9024     if (Opc == ISD::UNDEF)
9025       continue;
9026
9027     // If all scalar values are floats and converted from integers.
9028     if (Opcode == ISD::DELETED_NODE &&
9029         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9030       Opcode = Opc;
9031     }
9032
9033     if (Opc != Opcode)
9034       return SDValue();
9035
9036     EVT InVT = In.getOperand(0).getValueType();
9037
9038     // If all scalar values are typed differently, bail out. It's chosen to
9039     // simplify BUILD_VECTOR of integer types.
9040     if (SrcVT == MVT::Other)
9041       SrcVT = InVT;
9042     if (SrcVT != InVT)
9043       return SDValue();
9044     NumDefs++;
9045   }
9046
9047   // If the vector has just one element defined, it's not worth to fold it into
9048   // a vectorized one.
9049   if (NumDefs < 2)
9050     return SDValue();
9051
9052   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9053          && "Should only handle conversion from integer to float.");
9054   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9055
9056   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9057
9058   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9059     return SDValue();
9060
9061   SmallVector<SDValue, 8> Opnds;
9062   for (unsigned i = 0; i != NumInScalars; ++i) {
9063     SDValue In = N->getOperand(i);
9064
9065     if (In.getOpcode() == ISD::UNDEF)
9066       Opnds.push_back(DAG.getUNDEF(SrcVT));
9067     else
9068       Opnds.push_back(In.getOperand(0));
9069   }
9070   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9071                            &Opnds[0], Opnds.size());
9072   AddToWorkList(BV.getNode());
9073
9074   return DAG.getNode(Opcode, dl, VT, BV);
9075 }
9076
9077 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9078   unsigned NumInScalars = N->getNumOperands();
9079   SDLoc dl(N);
9080   EVT VT = N->getValueType(0);
9081
9082   // A vector built entirely of undefs is undef.
9083   if (ISD::allOperandsUndef(N))
9084     return DAG.getUNDEF(VT);
9085
9086   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9087   if (V.getNode())
9088     return V;
9089
9090   V = reduceBuildVecConvertToConvertBuildVec(N);
9091   if (V.getNode())
9092     return V;
9093
9094   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9095   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9096   // at most two distinct vectors, turn this into a shuffle node.
9097
9098   // May only combine to shuffle after legalize if shuffle is legal.
9099   if (LegalOperations &&
9100       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9101     return SDValue();
9102
9103   SDValue VecIn1, VecIn2;
9104   for (unsigned i = 0; i != NumInScalars; ++i) {
9105     // Ignore undef inputs.
9106     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9107
9108     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9109     // constant index, bail out.
9110     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9111         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9112       VecIn1 = VecIn2 = SDValue(0, 0);
9113       break;
9114     }
9115
9116     // We allow up to two distinct input vectors.
9117     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9118     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9119       continue;
9120
9121     if (VecIn1.getNode() == 0) {
9122       VecIn1 = ExtractedFromVec;
9123     } else if (VecIn2.getNode() == 0) {
9124       VecIn2 = ExtractedFromVec;
9125     } else {
9126       // Too many inputs.
9127       VecIn1 = VecIn2 = SDValue(0, 0);
9128       break;
9129     }
9130   }
9131
9132     // If everything is good, we can make a shuffle operation.
9133   if (VecIn1.getNode()) {
9134     SmallVector<int, 8> Mask;
9135     for (unsigned i = 0; i != NumInScalars; ++i) {
9136       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9137         Mask.push_back(-1);
9138         continue;
9139       }
9140
9141       // If extracting from the first vector, just use the index directly.
9142       SDValue Extract = N->getOperand(i);
9143       SDValue ExtVal = Extract.getOperand(1);
9144       if (Extract.getOperand(0) == VecIn1) {
9145         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9146         if (ExtIndex > VT.getVectorNumElements())
9147           return SDValue();
9148
9149         Mask.push_back(ExtIndex);
9150         continue;
9151       }
9152
9153       // Otherwise, use InIdx + VecSize
9154       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9155       Mask.push_back(Idx+NumInScalars);
9156     }
9157
9158     // We can't generate a shuffle node with mismatched input and output types.
9159     // Attempt to transform a single input vector to the correct type.
9160     if ((VT != VecIn1.getValueType())) {
9161       // We don't support shuffeling between TWO values of different types.
9162       if (VecIn2.getNode() != 0)
9163         return SDValue();
9164
9165       // We only support widening of vectors which are half the size of the
9166       // output registers. For example XMM->YMM widening on X86 with AVX.
9167       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9168         return SDValue();
9169
9170       // If the input vector type has a different base type to the output
9171       // vector type, bail out.
9172       if (VecIn1.getValueType().getVectorElementType() !=
9173           VT.getVectorElementType())
9174         return SDValue();
9175
9176       // Widen the input vector by adding undef values.
9177       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9178                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9179     }
9180
9181     // If VecIn2 is unused then change it to undef.
9182     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9183
9184     // Check that we were able to transform all incoming values to the same
9185     // type.
9186     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9187         VecIn1.getValueType() != VT)
9188           return SDValue();
9189
9190     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9191     if (!isTypeLegal(VT))
9192       return SDValue();
9193
9194     // Return the new VECTOR_SHUFFLE node.
9195     SDValue Ops[2];
9196     Ops[0] = VecIn1;
9197     Ops[1] = VecIn2;
9198     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9199   }
9200
9201   return SDValue();
9202 }
9203
9204 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9205   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9206   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9207   // inputs come from at most two distinct vectors, turn this into a shuffle
9208   // node.
9209
9210   // If we only have one input vector, we don't need to do any concatenation.
9211   if (N->getNumOperands() == 1)
9212     return N->getOperand(0);
9213
9214   // Check if all of the operands are undefs.
9215   if (ISD::allOperandsUndef(N))
9216     return DAG.getUNDEF(N->getValueType(0));
9217
9218   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9219   // nodes often generate nop CONCAT_VECTOR nodes.
9220   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9221   // place the incoming vectors at the exact same location.
9222   SDValue SingleSource = SDValue();
9223   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9224
9225   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9226     SDValue Op = N->getOperand(i);
9227
9228     if (Op.getOpcode() == ISD::UNDEF)
9229       continue;
9230
9231     // Check if this is the identity extract:
9232     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9233       return SDValue();
9234
9235     // Find the single incoming vector for the extract_subvector.
9236     if (SingleSource.getNode()) {
9237       if (Op.getOperand(0) != SingleSource)
9238         return SDValue();
9239     } else {
9240       SingleSource = Op.getOperand(0);
9241
9242       // Check the source type is the same as the type of the result.
9243       // If not, this concat may extend the vector, so we can not
9244       // optimize it away.
9245       if (SingleSource.getValueType() != N->getValueType(0))
9246         return SDValue();
9247     }
9248
9249     unsigned IdentityIndex = i * PartNumElem;
9250     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9251     // The extract index must be constant.
9252     if (!CS)
9253       return SDValue();
9254
9255     // Check that we are reading from the identity index.
9256     if (CS->getZExtValue() != IdentityIndex)
9257       return SDValue();
9258   }
9259
9260   if (SingleSource.getNode())
9261     return SingleSource;
9262
9263   return SDValue();
9264 }
9265
9266 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9267   EVT NVT = N->getValueType(0);
9268   SDValue V = N->getOperand(0);
9269
9270   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9271     // Combine:
9272     //    (extract_subvec (concat V1, V2, ...), i)
9273     // Into:
9274     //    Vi if possible
9275     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9276     if (V->getOperand(0).getValueType() != NVT)
9277       return SDValue();
9278     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9279     unsigned NumElems = NVT.getVectorNumElements();
9280     assert((Idx % NumElems) == 0 &&
9281            "IDX in concat is not a multiple of the result vector length.");
9282     return V->getOperand(Idx / NumElems);
9283   }
9284
9285   // Skip bitcasting
9286   if (V->getOpcode() == ISD::BITCAST)
9287     V = V.getOperand(0);
9288
9289   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9290     SDLoc dl(N);
9291     // Handle only simple case where vector being inserted and vector
9292     // being extracted are of same type, and are half size of larger vectors.
9293     EVT BigVT = V->getOperand(0).getValueType();
9294     EVT SmallVT = V->getOperand(1).getValueType();
9295     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9296       return SDValue();
9297
9298     // Only handle cases where both indexes are constants with the same type.
9299     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9300     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9301
9302     if (InsIdx && ExtIdx &&
9303         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9304         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9305       // Combine:
9306       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9307       // Into:
9308       //    indices are equal or bit offsets are equal => V1
9309       //    otherwise => (extract_subvec V1, ExtIdx)
9310       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9311           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9312         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9313       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9314                          DAG.getNode(ISD::BITCAST, dl,
9315                                      N->getOperand(0).getValueType(),
9316                                      V->getOperand(0)), N->getOperand(1));
9317     }
9318   }
9319
9320   return SDValue();
9321 }
9322
9323 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9324 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9325   EVT VT = N->getValueType(0);
9326   unsigned NumElts = VT.getVectorNumElements();
9327
9328   SDValue N0 = N->getOperand(0);
9329   SDValue N1 = N->getOperand(1);
9330   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9331
9332   SmallVector<SDValue, 4> Ops;
9333   EVT ConcatVT = N0.getOperand(0).getValueType();
9334   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9335   unsigned NumConcats = NumElts / NumElemsPerConcat;
9336
9337   // Look at every vector that's inserted. We're looking for exact
9338   // subvector-sized copies from a concatenated vector
9339   for (unsigned I = 0; I != NumConcats; ++I) {
9340     // Make sure we're dealing with a copy.
9341     unsigned Begin = I * NumElemsPerConcat;
9342     bool AllUndef = true, NoUndef = true;
9343     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9344       if (SVN->getMaskElt(J) >= 0)
9345         AllUndef = false;
9346       else
9347         NoUndef = false;
9348     }
9349
9350     if (NoUndef) {
9351       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9352         return SDValue();
9353
9354       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9355         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9356           return SDValue();
9357
9358       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9359       if (FirstElt < N0.getNumOperands())
9360         Ops.push_back(N0.getOperand(FirstElt));
9361       else
9362         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9363
9364     } else if (AllUndef) {
9365       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9366     } else { // Mixed with general masks and undefs, can't do optimization.
9367       return SDValue();
9368     }
9369   }
9370
9371   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9372                      Ops.size());
9373 }
9374
9375 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9376   EVT VT = N->getValueType(0);
9377   unsigned NumElts = VT.getVectorNumElements();
9378
9379   SDValue N0 = N->getOperand(0);
9380   SDValue N1 = N->getOperand(1);
9381
9382   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9383
9384   // Canonicalize shuffle undef, undef -> undef
9385   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9386     return DAG.getUNDEF(VT);
9387
9388   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9389
9390   // Canonicalize shuffle v, v -> v, undef
9391   if (N0 == N1) {
9392     SmallVector<int, 8> NewMask;
9393     for (unsigned i = 0; i != NumElts; ++i) {
9394       int Idx = SVN->getMaskElt(i);
9395       if (Idx >= (int)NumElts) Idx -= NumElts;
9396       NewMask.push_back(Idx);
9397     }
9398     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9399                                 &NewMask[0]);
9400   }
9401
9402   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9403   if (N0.getOpcode() == ISD::UNDEF) {
9404     SmallVector<int, 8> NewMask;
9405     for (unsigned i = 0; i != NumElts; ++i) {
9406       int Idx = SVN->getMaskElt(i);
9407       if (Idx >= 0) {
9408         if (Idx >= (int)NumElts)
9409           Idx -= NumElts;
9410         else
9411           Idx = -1; // remove reference to lhs
9412       }
9413       NewMask.push_back(Idx);
9414     }
9415     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9416                                 &NewMask[0]);
9417   }
9418
9419   // Remove references to rhs if it is undef
9420   if (N1.getOpcode() == ISD::UNDEF) {
9421     bool Changed = false;
9422     SmallVector<int, 8> NewMask;
9423     for (unsigned i = 0; i != NumElts; ++i) {
9424       int Idx = SVN->getMaskElt(i);
9425       if (Idx >= (int)NumElts) {
9426         Idx = -1;
9427         Changed = true;
9428       }
9429       NewMask.push_back(Idx);
9430     }
9431     if (Changed)
9432       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9433   }
9434
9435   // If it is a splat, check if the argument vector is another splat or a
9436   // build_vector with all scalar elements the same.
9437   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9438     SDNode *V = N0.getNode();
9439
9440     // If this is a bit convert that changes the element type of the vector but
9441     // not the number of vector elements, look through it.  Be careful not to
9442     // look though conversions that change things like v4f32 to v2f64.
9443     if (V->getOpcode() == ISD::BITCAST) {
9444       SDValue ConvInput = V->getOperand(0);
9445       if (ConvInput.getValueType().isVector() &&
9446           ConvInput.getValueType().getVectorNumElements() == NumElts)
9447         V = ConvInput.getNode();
9448     }
9449
9450     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9451       assert(V->getNumOperands() == NumElts &&
9452              "BUILD_VECTOR has wrong number of operands");
9453       SDValue Base;
9454       bool AllSame = true;
9455       for (unsigned i = 0; i != NumElts; ++i) {
9456         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9457           Base = V->getOperand(i);
9458           break;
9459         }
9460       }
9461       // Splat of <u, u, u, u>, return <u, u, u, u>
9462       if (!Base.getNode())
9463         return N0;
9464       for (unsigned i = 0; i != NumElts; ++i) {
9465         if (V->getOperand(i) != Base) {
9466           AllSame = false;
9467           break;
9468         }
9469       }
9470       // Splat of <x, x, x, x>, return <x, x, x, x>
9471       if (AllSame)
9472         return N0;
9473     }
9474   }
9475
9476   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9477       Level < AfterLegalizeVectorOps &&
9478       (N1.getOpcode() == ISD::UNDEF ||
9479       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9480        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9481     SDValue V = partitionShuffleOfConcats(N, DAG);
9482
9483     if (V.getNode())
9484       return V;
9485   }
9486
9487   // If this shuffle node is simply a swizzle of another shuffle node,
9488   // and it reverses the swizzle of the previous shuffle then we can
9489   // optimize shuffle(shuffle(x, undef), undef) -> x.
9490   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9491       N1.getOpcode() == ISD::UNDEF) {
9492
9493     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9494
9495     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9496     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9497       return SDValue();
9498
9499     // The incoming shuffle must be of the same type as the result of the
9500     // current shuffle.
9501     assert(OtherSV->getOperand(0).getValueType() == VT &&
9502            "Shuffle types don't match");
9503
9504     for (unsigned i = 0; i != NumElts; ++i) {
9505       int Idx = SVN->getMaskElt(i);
9506       assert(Idx < (int)NumElts && "Index references undef operand");
9507       // Next, this index comes from the first value, which is the incoming
9508       // shuffle. Adopt the incoming index.
9509       if (Idx >= 0)
9510         Idx = OtherSV->getMaskElt(Idx);
9511
9512       // The combined shuffle must map each index to itself.
9513       if (Idx >= 0 && (unsigned)Idx != i)
9514         return SDValue();
9515     }
9516
9517     return OtherSV->getOperand(0);
9518   }
9519
9520   return SDValue();
9521 }
9522
9523 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9524 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9525 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9526 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9527 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9528   EVT VT = N->getValueType(0);
9529   SDLoc dl(N);
9530   SDValue LHS = N->getOperand(0);
9531   SDValue RHS = N->getOperand(1);
9532   if (N->getOpcode() == ISD::AND) {
9533     if (RHS.getOpcode() == ISD::BITCAST)
9534       RHS = RHS.getOperand(0);
9535     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9536       SmallVector<int, 8> Indices;
9537       unsigned NumElts = RHS.getNumOperands();
9538       for (unsigned i = 0; i != NumElts; ++i) {
9539         SDValue Elt = RHS.getOperand(i);
9540         if (!isa<ConstantSDNode>(Elt))
9541           return SDValue();
9542
9543         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9544           Indices.push_back(i);
9545         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9546           Indices.push_back(NumElts);
9547         else
9548           return SDValue();
9549       }
9550
9551       // Let's see if the target supports this vector_shuffle.
9552       EVT RVT = RHS.getValueType();
9553       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9554         return SDValue();
9555
9556       // Return the new VECTOR_SHUFFLE node.
9557       EVT EltVT = RVT.getVectorElementType();
9558       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9559                                      DAG.getConstant(0, EltVT));
9560       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9561                                  RVT, &ZeroOps[0], ZeroOps.size());
9562       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9563       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9564       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9565     }
9566   }
9567
9568   return SDValue();
9569 }
9570
9571 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9572 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9573   assert(N->getValueType(0).isVector() &&
9574          "SimplifyVBinOp only works on vectors!");
9575
9576   SDValue LHS = N->getOperand(0);
9577   SDValue RHS = N->getOperand(1);
9578   SDValue Shuffle = XformToShuffleWithZero(N);
9579   if (Shuffle.getNode()) return Shuffle;
9580
9581   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9582   // this operation.
9583   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9584       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9585     SmallVector<SDValue, 8> Ops;
9586     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9587       SDValue LHSOp = LHS.getOperand(i);
9588       SDValue RHSOp = RHS.getOperand(i);
9589       // If these two elements can't be folded, bail out.
9590       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9591            LHSOp.getOpcode() != ISD::Constant &&
9592            LHSOp.getOpcode() != ISD::ConstantFP) ||
9593           (RHSOp.getOpcode() != ISD::UNDEF &&
9594            RHSOp.getOpcode() != ISD::Constant &&
9595            RHSOp.getOpcode() != ISD::ConstantFP))
9596         break;
9597
9598       // Can't fold divide by zero.
9599       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9600           N->getOpcode() == ISD::FDIV) {
9601         if ((RHSOp.getOpcode() == ISD::Constant &&
9602              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9603             (RHSOp.getOpcode() == ISD::ConstantFP &&
9604              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9605           break;
9606       }
9607
9608       EVT VT = LHSOp.getValueType();
9609       EVT RVT = RHSOp.getValueType();
9610       if (RVT != VT) {
9611         // Integer BUILD_VECTOR operands may have types larger than the element
9612         // size (e.g., when the element type is not legal).  Prior to type
9613         // legalization, the types may not match between the two BUILD_VECTORS.
9614         // Truncate one of the operands to make them match.
9615         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9616           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9617         } else {
9618           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9619           VT = RVT;
9620         }
9621       }
9622       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9623                                    LHSOp, RHSOp);
9624       if (FoldOp.getOpcode() != ISD::UNDEF &&
9625           FoldOp.getOpcode() != ISD::Constant &&
9626           FoldOp.getOpcode() != ISD::ConstantFP)
9627         break;
9628       Ops.push_back(FoldOp);
9629       AddToWorkList(FoldOp.getNode());
9630     }
9631
9632     if (Ops.size() == LHS.getNumOperands())
9633       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9634                          LHS.getValueType(), &Ops[0], Ops.size());
9635   }
9636
9637   return SDValue();
9638 }
9639
9640 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9641 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9642   assert(N->getValueType(0).isVector() &&
9643          "SimplifyVUnaryOp only works on vectors!");
9644
9645   SDValue N0 = N->getOperand(0);
9646
9647   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9648     return SDValue();
9649
9650   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9651   SmallVector<SDValue, 8> Ops;
9652   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9653     SDValue Op = N0.getOperand(i);
9654     if (Op.getOpcode() != ISD::UNDEF &&
9655         Op.getOpcode() != ISD::ConstantFP)
9656       break;
9657     EVT EltVT = Op.getValueType();
9658     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9659     if (FoldOp.getOpcode() != ISD::UNDEF &&
9660         FoldOp.getOpcode() != ISD::ConstantFP)
9661       break;
9662     Ops.push_back(FoldOp);
9663     AddToWorkList(FoldOp.getNode());
9664   }
9665
9666   if (Ops.size() != N0.getNumOperands())
9667     return SDValue();
9668
9669   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9670                      N0.getValueType(), &Ops[0], Ops.size());
9671 }
9672
9673 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9674                                     SDValue N1, SDValue N2){
9675   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9676
9677   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9678                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9679
9680   // If we got a simplified select_cc node back from SimplifySelectCC, then
9681   // break it down into a new SETCC node, and a new SELECT node, and then return
9682   // the SELECT node, since we were called with a SELECT node.
9683   if (SCC.getNode()) {
9684     // Check to see if we got a select_cc back (to turn into setcc/select).
9685     // Otherwise, just return whatever node we got back, like fabs.
9686     if (SCC.getOpcode() == ISD::SELECT_CC) {
9687       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9688                                   N0.getValueType(),
9689                                   SCC.getOperand(0), SCC.getOperand(1),
9690                                   SCC.getOperand(4));
9691       AddToWorkList(SETCC.getNode());
9692       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9693                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9694     }
9695
9696     return SCC;
9697   }
9698   return SDValue();
9699 }
9700
9701 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9702 /// are the two values being selected between, see if we can simplify the
9703 /// select.  Callers of this should assume that TheSelect is deleted if this
9704 /// returns true.  As such, they should return the appropriate thing (e.g. the
9705 /// node) back to the top-level of the DAG combiner loop to avoid it being
9706 /// looked at.
9707 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9708                                     SDValue RHS) {
9709
9710   // Cannot simplify select with vector condition
9711   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9712
9713   // If this is a select from two identical things, try to pull the operation
9714   // through the select.
9715   if (LHS.getOpcode() != RHS.getOpcode() ||
9716       !LHS.hasOneUse() || !RHS.hasOneUse())
9717     return false;
9718
9719   // If this is a load and the token chain is identical, replace the select
9720   // of two loads with a load through a select of the address to load from.
9721   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9722   // constants have been dropped into the constant pool.
9723   if (LHS.getOpcode() == ISD::LOAD) {
9724     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9725     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9726
9727     // Token chains must be identical.
9728     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9729         // Do not let this transformation reduce the number of volatile loads.
9730         LLD->isVolatile() || RLD->isVolatile() ||
9731         // If this is an EXTLOAD, the VT's must match.
9732         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9733         // If this is an EXTLOAD, the kind of extension must match.
9734         (LLD->getExtensionType() != RLD->getExtensionType() &&
9735          // The only exception is if one of the extensions is anyext.
9736          LLD->getExtensionType() != ISD::EXTLOAD &&
9737          RLD->getExtensionType() != ISD::EXTLOAD) ||
9738         // FIXME: this discards src value information.  This is
9739         // over-conservative. It would be beneficial to be able to remember
9740         // both potential memory locations.  Since we are discarding
9741         // src value info, don't do the transformation if the memory
9742         // locations are not in the default address space.
9743         LLD->getPointerInfo().getAddrSpace() != 0 ||
9744         RLD->getPointerInfo().getAddrSpace() != 0 ||
9745         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9746                                       LLD->getBasePtr().getValueType()))
9747       return false;
9748
9749     // Check that the select condition doesn't reach either load.  If so,
9750     // folding this will induce a cycle into the DAG.  If not, this is safe to
9751     // xform, so create a select of the addresses.
9752     SDValue Addr;
9753     if (TheSelect->getOpcode() == ISD::SELECT) {
9754       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9755       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9756           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9757         return false;
9758       // The loads must not depend on one another.
9759       if (LLD->isPredecessorOf(RLD) ||
9760           RLD->isPredecessorOf(LLD))
9761         return false;
9762       Addr = DAG.getSelect(SDLoc(TheSelect),
9763                            LLD->getBasePtr().getValueType(),
9764                            TheSelect->getOperand(0), LLD->getBasePtr(),
9765                            RLD->getBasePtr());
9766     } else {  // Otherwise SELECT_CC
9767       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9768       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9769
9770       if ((LLD->hasAnyUseOfValue(1) &&
9771            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9772           (RLD->hasAnyUseOfValue(1) &&
9773            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9774         return false;
9775
9776       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9777                          LLD->getBasePtr().getValueType(),
9778                          TheSelect->getOperand(0),
9779                          TheSelect->getOperand(1),
9780                          LLD->getBasePtr(), RLD->getBasePtr(),
9781                          TheSelect->getOperand(4));
9782     }
9783
9784     SDValue Load;
9785     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9786       Load = DAG.getLoad(TheSelect->getValueType(0),
9787                          SDLoc(TheSelect),
9788                          // FIXME: Discards pointer info.
9789                          LLD->getChain(), Addr, MachinePointerInfo(),
9790                          LLD->isVolatile(), LLD->isNonTemporal(),
9791                          LLD->isInvariant(), LLD->getAlignment());
9792     } else {
9793       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9794                             RLD->getExtensionType() : LLD->getExtensionType(),
9795                             SDLoc(TheSelect),
9796                             TheSelect->getValueType(0),
9797                             // FIXME: Discards pointer info.
9798                             LLD->getChain(), Addr, MachinePointerInfo(),
9799                             LLD->getMemoryVT(), LLD->isVolatile(),
9800                             LLD->isNonTemporal(), LLD->getAlignment());
9801     }
9802
9803     // Users of the select now use the result of the load.
9804     CombineTo(TheSelect, Load);
9805
9806     // Users of the old loads now use the new load's chain.  We know the
9807     // old-load value is dead now.
9808     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9809     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9810     return true;
9811   }
9812
9813   return false;
9814 }
9815
9816 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9817 /// where 'cond' is the comparison specified by CC.
9818 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9819                                       SDValue N2, SDValue N3,
9820                                       ISD::CondCode CC, bool NotExtCompare) {
9821   // (x ? y : y) -> y.
9822   if (N2 == N3) return N2;
9823
9824   EVT VT = N2.getValueType();
9825   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9826   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9827   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9828
9829   // Determine if the condition we're dealing with is constant
9830   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9831                               N0, N1, CC, DL, false);
9832   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9833   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9834
9835   // fold select_cc true, x, y -> x
9836   if (SCCC && !SCCC->isNullValue())
9837     return N2;
9838   // fold select_cc false, x, y -> y
9839   if (SCCC && SCCC->isNullValue())
9840     return N3;
9841
9842   // Check to see if we can simplify the select into an fabs node
9843   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9844     // Allow either -0.0 or 0.0
9845     if (CFP->getValueAPF().isZero()) {
9846       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9847       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9848           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9849           N2 == N3.getOperand(0))
9850         return DAG.getNode(ISD::FABS, DL, VT, N0);
9851
9852       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9853       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9854           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9855           N2.getOperand(0) == N3)
9856         return DAG.getNode(ISD::FABS, DL, VT, N3);
9857     }
9858   }
9859
9860   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9861   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9862   // in it.  This is a win when the constant is not otherwise available because
9863   // it replaces two constant pool loads with one.  We only do this if the FP
9864   // type is known to be legal, because if it isn't, then we are before legalize
9865   // types an we want the other legalization to happen first (e.g. to avoid
9866   // messing with soft float) and if the ConstantFP is not legal, because if
9867   // it is legal, we may not need to store the FP constant in a constant pool.
9868   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9869     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9870       if (TLI.isTypeLegal(N2.getValueType()) &&
9871           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9872            TargetLowering::Legal) &&
9873           // If both constants have multiple uses, then we won't need to do an
9874           // extra load, they are likely around in registers for other users.
9875           (TV->hasOneUse() || FV->hasOneUse())) {
9876         Constant *Elts[] = {
9877           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9878           const_cast<ConstantFP*>(TV->getConstantFPValue())
9879         };
9880         Type *FPTy = Elts[0]->getType();
9881         const DataLayout &TD = *TLI.getDataLayout();
9882
9883         // Create a ConstantArray of the two constants.
9884         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9885         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9886                                             TD.getPrefTypeAlignment(FPTy));
9887         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9888
9889         // Get the offsets to the 0 and 1 element of the array so that we can
9890         // select between them.
9891         SDValue Zero = DAG.getIntPtrConstant(0);
9892         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9893         SDValue One = DAG.getIntPtrConstant(EltSize);
9894
9895         SDValue Cond = DAG.getSetCC(DL,
9896                                     getSetCCResultType(N0.getValueType()),
9897                                     N0, N1, CC);
9898         AddToWorkList(Cond.getNode());
9899         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9900                                           Cond, One, Zero);
9901         AddToWorkList(CstOffset.getNode());
9902         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9903                             CstOffset);
9904         AddToWorkList(CPIdx.getNode());
9905         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9906                            MachinePointerInfo::getConstantPool(), false,
9907                            false, false, Alignment);
9908
9909       }
9910     }
9911
9912   // Check to see if we can perform the "gzip trick", transforming
9913   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9914   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9915       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9916        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9917     EVT XType = N0.getValueType();
9918     EVT AType = N2.getValueType();
9919     if (XType.bitsGE(AType)) {
9920       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9921       // single-bit constant.
9922       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9923         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9924         ShCtV = XType.getSizeInBits()-ShCtV-1;
9925         SDValue ShCt = DAG.getConstant(ShCtV,
9926                                        getShiftAmountTy(N0.getValueType()));
9927         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9928                                     XType, N0, ShCt);
9929         AddToWorkList(Shift.getNode());
9930
9931         if (XType.bitsGT(AType)) {
9932           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9933           AddToWorkList(Shift.getNode());
9934         }
9935
9936         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9937       }
9938
9939       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9940                                   XType, N0,
9941                                   DAG.getConstant(XType.getSizeInBits()-1,
9942                                          getShiftAmountTy(N0.getValueType())));
9943       AddToWorkList(Shift.getNode());
9944
9945       if (XType.bitsGT(AType)) {
9946         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9947         AddToWorkList(Shift.getNode());
9948       }
9949
9950       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9951     }
9952   }
9953
9954   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9955   // where y is has a single bit set.
9956   // A plaintext description would be, we can turn the SELECT_CC into an AND
9957   // when the condition can be materialized as an all-ones register.  Any
9958   // single bit-test can be materialized as an all-ones register with
9959   // shift-left and shift-right-arith.
9960   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9961       N0->getValueType(0) == VT &&
9962       N1C && N1C->isNullValue() &&
9963       N2C && N2C->isNullValue()) {
9964     SDValue AndLHS = N0->getOperand(0);
9965     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9966     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9967       // Shift the tested bit over the sign bit.
9968       APInt AndMask = ConstAndRHS->getAPIntValue();
9969       SDValue ShlAmt =
9970         DAG.getConstant(AndMask.countLeadingZeros(),
9971                         getShiftAmountTy(AndLHS.getValueType()));
9972       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9973
9974       // Now arithmetic right shift it all the way over, so the result is either
9975       // all-ones, or zero.
9976       SDValue ShrAmt =
9977         DAG.getConstant(AndMask.getBitWidth()-1,
9978                         getShiftAmountTy(Shl.getValueType()));
9979       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9980
9981       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9982     }
9983   }
9984
9985   // fold select C, 16, 0 -> shl C, 4
9986   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9987     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9988       TargetLowering::ZeroOrOneBooleanContent) {
9989
9990     // If the caller doesn't want us to simplify this into a zext of a compare,
9991     // don't do it.
9992     if (NotExtCompare && N2C->getAPIntValue() == 1)
9993       return SDValue();
9994
9995     // Get a SetCC of the condition
9996     // NOTE: Don't create a SETCC if it's not legal on this target.
9997     if (!LegalOperations ||
9998         TLI.isOperationLegal(ISD::SETCC,
9999           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10000       SDValue Temp, SCC;
10001       // cast from setcc result type to select result type
10002       if (LegalTypes) {
10003         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10004                             N0, N1, CC);
10005         if (N2.getValueType().bitsLT(SCC.getValueType()))
10006           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10007                                         N2.getValueType());
10008         else
10009           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10010                              N2.getValueType(), SCC);
10011       } else {
10012         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10013         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10014                            N2.getValueType(), SCC);
10015       }
10016
10017       AddToWorkList(SCC.getNode());
10018       AddToWorkList(Temp.getNode());
10019
10020       if (N2C->getAPIntValue() == 1)
10021         return Temp;
10022
10023       // shl setcc result by log2 n2c
10024       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10025                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10026                                          getShiftAmountTy(Temp.getValueType())));
10027     }
10028   }
10029
10030   // Check to see if this is the equivalent of setcc
10031   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10032   // otherwise, go ahead with the folds.
10033   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10034     EVT XType = N0.getValueType();
10035     if (!LegalOperations ||
10036         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10037       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10038       if (Res.getValueType() != VT)
10039         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10040       return Res;
10041     }
10042
10043     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10044     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10045         (!LegalOperations ||
10046          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10047       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10048       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10049                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10050                                        getShiftAmountTy(Ctlz.getValueType())));
10051     }
10052     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10053     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10054       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10055                                   XType, DAG.getConstant(0, XType), N0);
10056       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10057       return DAG.getNode(ISD::SRL, DL, XType,
10058                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10059                          DAG.getConstant(XType.getSizeInBits()-1,
10060                                          getShiftAmountTy(XType)));
10061     }
10062     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10063     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10064       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10065                                  DAG.getConstant(XType.getSizeInBits()-1,
10066                                          getShiftAmountTy(N0.getValueType())));
10067       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10068     }
10069   }
10070
10071   // Check to see if this is an integer abs.
10072   // select_cc setg[te] X,  0,  X, -X ->
10073   // select_cc setgt    X, -1,  X, -X ->
10074   // select_cc setl[te] X,  0, -X,  X ->
10075   // select_cc setlt    X,  1, -X,  X ->
10076   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10077   if (N1C) {
10078     ConstantSDNode *SubC = NULL;
10079     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10080          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10081         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10082       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10083     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10084               (N1C->isOne() && CC == ISD::SETLT)) &&
10085              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10086       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10087
10088     EVT XType = N0.getValueType();
10089     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10090       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10091                                   N0,
10092                                   DAG.getConstant(XType.getSizeInBits()-1,
10093                                          getShiftAmountTy(N0.getValueType())));
10094       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10095                                 XType, N0, Shift);
10096       AddToWorkList(Shift.getNode());
10097       AddToWorkList(Add.getNode());
10098       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10099     }
10100   }
10101
10102   return SDValue();
10103 }
10104
10105 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10106 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10107                                    SDValue N1, ISD::CondCode Cond,
10108                                    SDLoc DL, bool foldBooleans) {
10109   TargetLowering::DAGCombinerInfo
10110     DagCombineInfo(DAG, Level, false, this);
10111   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10112 }
10113
10114 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10115 /// return a DAG expression to select that will generate the same value by
10116 /// multiplying by a magic number.  See:
10117 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10118 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10119   std::vector<SDNode*> Built;
10120   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10121
10122   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10123        ii != ee; ++ii)
10124     AddToWorkList(*ii);
10125   return S;
10126 }
10127
10128 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10129 /// return a DAG expression to select that will generate the same value by
10130 /// multiplying by a magic number.  See:
10131 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10132 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10133   std::vector<SDNode*> Built;
10134   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10135
10136   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10137        ii != ee; ++ii)
10138     AddToWorkList(*ii);
10139   return S;
10140 }
10141
10142 /// FindBaseOffset - Return true if base is a frame index, which is known not
10143 // to alias with anything but itself.  Provides base object and offset as
10144 // results.
10145 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10146                            const GlobalValue *&GV, const void *&CV) {
10147   // Assume it is a primitive operation.
10148   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10149
10150   // If it's an adding a simple constant then integrate the offset.
10151   if (Base.getOpcode() == ISD::ADD) {
10152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10153       Base = Base.getOperand(0);
10154       Offset += C->getZExtValue();
10155     }
10156   }
10157
10158   // Return the underlying GlobalValue, and update the Offset.  Return false
10159   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10160   // by multiple nodes with different offsets.
10161   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10162     GV = G->getGlobal();
10163     Offset += G->getOffset();
10164     return false;
10165   }
10166
10167   // Return the underlying Constant value, and update the Offset.  Return false
10168   // for ConstantSDNodes since the same constant pool entry may be represented
10169   // by multiple nodes with different offsets.
10170   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10171     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10172                                          : (const void *)C->getConstVal();
10173     Offset += C->getOffset();
10174     return false;
10175   }
10176   // If it's any of the following then it can't alias with anything but itself.
10177   return isa<FrameIndexSDNode>(Base);
10178 }
10179
10180 /// isAlias - Return true if there is any possibility that the two addresses
10181 /// overlap.
10182 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10183                           const Value *SrcValue1, int SrcValueOffset1,
10184                           unsigned SrcValueAlign1,
10185                           const MDNode *TBAAInfo1,
10186                           SDValue Ptr2, int64_t Size2,
10187                           const Value *SrcValue2, int SrcValueOffset2,
10188                           unsigned SrcValueAlign2,
10189                           const MDNode *TBAAInfo2) const {
10190   // If they are the same then they must be aliases.
10191   if (Ptr1 == Ptr2) return true;
10192
10193   // Gather base node and offset information.
10194   SDValue Base1, Base2;
10195   int64_t Offset1, Offset2;
10196   const GlobalValue *GV1, *GV2;
10197   const void *CV1, *CV2;
10198   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10199   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10200
10201   // If they have a same base address then check to see if they overlap.
10202   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10203     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10204
10205   // It is possible for different frame indices to alias each other, mostly
10206   // when tail call optimization reuses return address slots for arguments.
10207   // To catch this case, look up the actual index of frame indices to compute
10208   // the real alias relationship.
10209   if (isFrameIndex1 && isFrameIndex2) {
10210     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10211     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10212     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10213     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10214   }
10215
10216   // Otherwise, if we know what the bases are, and they aren't identical, then
10217   // we know they cannot alias.
10218   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10219     return false;
10220
10221   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10222   // compared to the size and offset of the access, we may be able to prove they
10223   // do not alias.  This check is conservative for now to catch cases created by
10224   // splitting vector types.
10225   if ((SrcValueAlign1 == SrcValueAlign2) &&
10226       (SrcValueOffset1 != SrcValueOffset2) &&
10227       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10228     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10229     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10230
10231     // There is no overlap between these relatively aligned accesses of similar
10232     // size, return no alias.
10233     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10234       return false;
10235   }
10236
10237   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10238     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10239   if (UseAA && SrcValue1 && SrcValue2) {
10240     // Use alias analysis information.
10241     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10242     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10243     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10244     AliasAnalysis::AliasResult AAResult =
10245       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10246                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10247     if (AAResult == AliasAnalysis::NoAlias)
10248       return false;
10249   }
10250
10251   // Otherwise we have to assume they alias.
10252   return true;
10253 }
10254
10255 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10256   SDValue Ptr0, Ptr1;
10257   int64_t Size0, Size1;
10258   const Value *SrcValue0, *SrcValue1;
10259   int SrcValueOffset0, SrcValueOffset1;
10260   unsigned SrcValueAlign0, SrcValueAlign1;
10261   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10262   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10263                 SrcValueAlign0, SrcTBAAInfo0);
10264   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10265                 SrcValueAlign1, SrcTBAAInfo1);
10266   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10267                  SrcValueAlign0, SrcTBAAInfo0,
10268                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10269                  SrcValueAlign1, SrcTBAAInfo1);
10270 }
10271
10272 /// FindAliasInfo - Extracts the relevant alias information from the memory
10273 /// node.  Returns true if the operand was a load.
10274 bool DAGCombiner::FindAliasInfo(SDNode *N,
10275                                 SDValue &Ptr, int64_t &Size,
10276                                 const Value *&SrcValue,
10277                                 int &SrcValueOffset,
10278                                 unsigned &SrcValueAlign,
10279                                 const MDNode *&TBAAInfo) const {
10280   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10281
10282   Ptr = LS->getBasePtr();
10283   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10284   SrcValue = LS->getSrcValue();
10285   SrcValueOffset = LS->getSrcValueOffset();
10286   SrcValueAlign = LS->getOriginalAlignment();
10287   TBAAInfo = LS->getTBAAInfo();
10288   return isa<LoadSDNode>(LS);
10289 }
10290
10291 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10292 /// looking for aliasing nodes and adding them to the Aliases vector.
10293 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10294                                    SmallVectorImpl<SDValue> &Aliases) {
10295   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10296   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10297
10298   // Get alias information for node.
10299   SDValue Ptr;
10300   int64_t Size;
10301   const Value *SrcValue;
10302   int SrcValueOffset;
10303   unsigned SrcValueAlign;
10304   const MDNode *SrcTBAAInfo;
10305   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10306                               SrcValueAlign, SrcTBAAInfo);
10307
10308   // Starting off.
10309   Chains.push_back(OriginalChain);
10310   unsigned Depth = 0;
10311
10312   // Look at each chain and determine if it is an alias.  If so, add it to the
10313   // aliases list.  If not, then continue up the chain looking for the next
10314   // candidate.
10315   while (!Chains.empty()) {
10316     SDValue Chain = Chains.back();
10317     Chains.pop_back();
10318
10319     // For TokenFactor nodes, look at each operand and only continue up the
10320     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10321     // find more and revert to original chain since the xform is unlikely to be
10322     // profitable.
10323     //
10324     // FIXME: The depth check could be made to return the last non-aliasing
10325     // chain we found before we hit a tokenfactor rather than the original
10326     // chain.
10327     if (Depth > 6 || Aliases.size() == 2) {
10328       Aliases.clear();
10329       Aliases.push_back(OriginalChain);
10330       break;
10331     }
10332
10333     // Don't bother if we've been before.
10334     if (!Visited.insert(Chain.getNode()))
10335       continue;
10336
10337     switch (Chain.getOpcode()) {
10338     case ISD::EntryToken:
10339       // Entry token is ideal chain operand, but handled in FindBetterChain.
10340       break;
10341
10342     case ISD::LOAD:
10343     case ISD::STORE: {
10344       // Get alias information for Chain.
10345       SDValue OpPtr;
10346       int64_t OpSize;
10347       const Value *OpSrcValue;
10348       int OpSrcValueOffset;
10349       unsigned OpSrcValueAlign;
10350       const MDNode *OpSrcTBAAInfo;
10351       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10352                                     OpSrcValue, OpSrcValueOffset,
10353                                     OpSrcValueAlign,
10354                                     OpSrcTBAAInfo);
10355
10356       // If chain is alias then stop here.
10357       if (!(IsLoad && IsOpLoad) &&
10358           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10359                   SrcTBAAInfo,
10360                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10361                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10362         Aliases.push_back(Chain);
10363       } else {
10364         // Look further up the chain.
10365         Chains.push_back(Chain.getOperand(0));
10366         ++Depth;
10367       }
10368       break;
10369     }
10370
10371     case ISD::TokenFactor:
10372       // We have to check each of the operands of the token factor for "small"
10373       // token factors, so we queue them up.  Adding the operands to the queue
10374       // (stack) in reverse order maintains the original order and increases the
10375       // likelihood that getNode will find a matching token factor (CSE.)
10376       if (Chain.getNumOperands() > 16) {
10377         Aliases.push_back(Chain);
10378         break;
10379       }
10380       for (unsigned n = Chain.getNumOperands(); n;)
10381         Chains.push_back(Chain.getOperand(--n));
10382       ++Depth;
10383       break;
10384
10385     default:
10386       // For all other instructions we will just have to take what we can get.
10387       Aliases.push_back(Chain);
10388       break;
10389     }
10390   }
10391 }
10392
10393 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10394 /// for a better chain (aliasing node.)
10395 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10396   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10397
10398   // Accumulate all the aliases to this node.
10399   GatherAllAliases(N, OldChain, Aliases);
10400
10401   // If no operands then chain to entry token.
10402   if (Aliases.size() == 0)
10403     return DAG.getEntryNode();
10404
10405   // If a single operand then chain to it.  We don't need to revisit it.
10406   if (Aliases.size() == 1)
10407     return Aliases[0];
10408
10409   // Construct a custom tailored token factor.
10410   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10411                      &Aliases[0], Aliases.size());
10412 }
10413
10414 // SelectionDAG::Combine - This is the entry point for the file.
10415 //
10416 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10417                            CodeGenOpt::Level OptLevel) {
10418   /// run - This is the main entry point to this class.
10419   ///
10420   DAGCombiner(*this, AA, OptLevel).Run(Level);
10421 }