1de11e9b1fa293d3bae3d5b6933947e9fdb195c2
[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 <algorithm>
39 using namespace llvm;
40
41 STATISTIC(NodesCombined   , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
46
47 namespace {
48   static cl::opt<bool>
49     CombinerAA("combiner-alias-analysis", cl::Hidden,
50                cl::desc("Turn on alias analysis during testing"));
51
52   static cl::opt<bool>
53     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54                cl::desc("Include global information in alias analysis"));
55
56 //------------------------------ DAGCombiner ---------------------------------//
57
58   class DAGCombiner {
59     SelectionDAG &DAG;
60     const TargetLowering &TLI;
61     CombineLevel Level;
62     CodeGenOpt::Level OptLevel;
63     bool LegalOperations;
64     bool LegalTypes;
65
66     // Worklist of all of the nodes that need to be simplified.
67     //
68     // This has the semantics that when adding to the worklist,
69     // the item added must be next to be processed. It should
70     // also only appear once. The naive approach to this takes
71     // linear time.
72     //
73     // To reduce the insert/remove time to logarithmic, we use
74     // a set and a vector to maintain our worklist.
75     //
76     // The set contains the items on the worklist, but does not
77     // maintain the order they should be visited.
78     //
79     // The vector maintains the order nodes should be visited, but may
80     // contain duplicate or removed nodes. When choosing a node to
81     // visit, we pop off the order stack until we find an item that is
82     // also in the contents set. All operations are O(log N).
83     SmallPtrSet<SDNode*, 64> WorkListContents;
84     SmallVector<SDNode*, 64> WorkListOrder;
85
86     // AA - Used for DAG load/store alias analysis.
87     AliasAnalysis &AA;
88
89     /// AddUsersToWorkList - When an instruction is simplified, add all users of
90     /// the instruction to the work lists because they might get more simplified
91     /// now.
92     ///
93     void AddUsersToWorkList(SDNode *N) {
94       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
95            UI != UE; ++UI)
96         AddToWorkList(*UI);
97     }
98
99     /// visit - call the node-specific routine that knows how to fold each
100     /// particular type of node.
101     SDValue visit(SDNode *N);
102
103   public:
104     /// AddToWorkList - Add to the work list making sure its instance is at the
105     /// back (next to be processed.)
106     void AddToWorkList(SDNode *N) {
107       WorkListContents.insert(N);
108       WorkListOrder.push_back(N);
109     }
110
111     /// removeFromWorkList - remove all instances of N from the worklist.
112     ///
113     void removeFromWorkList(SDNode *N) {
114       WorkListContents.erase(N);
115     }
116
117     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
118                       bool AddTo = true);
119
120     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
121       return CombineTo(N, &Res, 1, AddTo);
122     }
123
124     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
125                       bool AddTo = true) {
126       SDValue To[] = { Res0, Res1 };
127       return CombineTo(N, To, 2, AddTo);
128     }
129
130     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
131
132   private:
133
134     /// SimplifyDemandedBits - Check the specified integer node value to see if
135     /// it can be simplified or if things it uses can be simplified by bit
136     /// propagation.  If so, return true.
137     bool SimplifyDemandedBits(SDValue Op) {
138       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
139       APInt Demanded = APInt::getAllOnesValue(BitWidth);
140       return SimplifyDemandedBits(Op, Demanded);
141     }
142
143     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
144
145     bool CombineToPreIndexedLoadStore(SDNode *N);
146     bool CombineToPostIndexedLoadStore(SDNode *N);
147
148     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
149     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
150     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
151     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue PromoteIntBinOp(SDValue Op);
153     SDValue PromoteIntShiftOp(SDValue Op);
154     SDValue PromoteExtend(SDValue Op);
155     bool PromoteLoad(SDValue Op);
156
157     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
158                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
159                          ISD::NodeType ExtType);
160
161     /// combine - call the node-specific routine that knows how to fold each
162     /// particular type of node. If that doesn't do anything, try the
163     /// target-specific DAG combines.
164     SDValue combine(SDNode *N);
165
166     // Visitation implementation - Implement dag node combining for different
167     // node types.  The semantics are as follows:
168     // Return Value:
169     //   SDValue.getNode() == 0 - No change was made
170     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
171     //   otherwise              - N should be replaced by the returned Operand.
172     //
173     SDValue visitTokenFactor(SDNode *N);
174     SDValue visitMERGE_VALUES(SDNode *N);
175     SDValue visitADD(SDNode *N);
176     SDValue visitSUB(SDNode *N);
177     SDValue visitADDC(SDNode *N);
178     SDValue visitSUBC(SDNode *N);
179     SDValue visitADDE(SDNode *N);
180     SDValue visitSUBE(SDNode *N);
181     SDValue visitMUL(SDNode *N);
182     SDValue visitSDIV(SDNode *N);
183     SDValue visitUDIV(SDNode *N);
184     SDValue visitSREM(SDNode *N);
185     SDValue visitUREM(SDNode *N);
186     SDValue visitMULHU(SDNode *N);
187     SDValue visitMULHS(SDNode *N);
188     SDValue visitSMUL_LOHI(SDNode *N);
189     SDValue visitUMUL_LOHI(SDNode *N);
190     SDValue visitSMULO(SDNode *N);
191     SDValue visitUMULO(SDNode *N);
192     SDValue visitSDIVREM(SDNode *N);
193     SDValue visitUDIVREM(SDNode *N);
194     SDValue visitAND(SDNode *N);
195     SDValue visitOR(SDNode *N);
196     SDValue visitXOR(SDNode *N);
197     SDValue SimplifyVBinOp(SDNode *N);
198     SDValue SimplifyVUnaryOp(SDNode *N);
199     SDValue visitSHL(SDNode *N);
200     SDValue visitSRA(SDNode *N);
201     SDValue visitSRL(SDNode *N);
202     SDValue visitCTLZ(SDNode *N);
203     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
204     SDValue visitCTTZ(SDNode *N);
205     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
206     SDValue visitCTPOP(SDNode *N);
207     SDValue visitSELECT(SDNode *N);
208     SDValue visitVSELECT(SDNode *N);
209     SDValue visitSELECT_CC(SDNode *N);
210     SDValue visitSETCC(SDNode *N);
211     SDValue visitSIGN_EXTEND(SDNode *N);
212     SDValue visitZERO_EXTEND(SDNode *N);
213     SDValue visitANY_EXTEND(SDNode *N);
214     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
215     SDValue visitTRUNCATE(SDNode *N);
216     SDValue visitBITCAST(SDNode *N);
217     SDValue visitBUILD_PAIR(SDNode *N);
218     SDValue visitFADD(SDNode *N);
219     SDValue visitFSUB(SDNode *N);
220     SDValue visitFMUL(SDNode *N);
221     SDValue visitFMA(SDNode *N);
222     SDValue visitFDIV(SDNode *N);
223     SDValue visitFREM(SDNode *N);
224     SDValue visitFCOPYSIGN(SDNode *N);
225     SDValue visitSINT_TO_FP(SDNode *N);
226     SDValue visitUINT_TO_FP(SDNode *N);
227     SDValue visitFP_TO_SINT(SDNode *N);
228     SDValue visitFP_TO_UINT(SDNode *N);
229     SDValue visitFP_ROUND(SDNode *N);
230     SDValue visitFP_ROUND_INREG(SDNode *N);
231     SDValue visitFP_EXTEND(SDNode *N);
232     SDValue visitFNEG(SDNode *N);
233     SDValue visitFABS(SDNode *N);
234     SDValue visitFCEIL(SDNode *N);
235     SDValue visitFTRUNC(SDNode *N);
236     SDValue visitFFLOOR(SDNode *N);
237     SDValue visitBRCOND(SDNode *N);
238     SDValue visitBR_CC(SDNode *N);
239     SDValue visitLOAD(SDNode *N);
240     SDValue visitSTORE(SDNode *N);
241     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
242     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
243     SDValue visitBUILD_VECTOR(SDNode *N);
244     SDValue visitCONCAT_VECTORS(SDNode *N);
245     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
246     SDValue visitVECTOR_SHUFFLE(SDNode *N);
247
248     SDValue XformToShuffleWithZero(SDNode *N);
249     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
250
251     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
252
253     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
254     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
255     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
256     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
257                              SDValue N3, ISD::CondCode CC,
258                              bool NotExtCompare = false);
259     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
260                           SDLoc DL, bool foldBooleans = true);
261     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
262                                          unsigned HiOp);
263     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
264     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
265     SDValue BuildSDIV(SDNode *N);
266     SDValue BuildUDIV(SDNode *N);
267     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
268                                bool DemandHighBits = true);
269     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
270     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
271     SDValue ReduceLoadWidth(SDNode *N);
272     SDValue ReduceLoadOpStoreWidth(SDNode *N);
273     SDValue TransformFPLoadStorePair(SDNode *N);
274     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
275     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
276
277     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
278
279     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
280     /// looking for aliasing nodes and adding them to the Aliases vector.
281     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
282                           SmallVectorImpl<SDValue> &Aliases);
283
284     /// isAlias - Return true if there is any possibility that the two addresses
285     /// overlap.
286     bool isAlias(SDValue Ptr1, int64_t Size1,
287                  const Value *SrcValue1, int SrcValueOffset1,
288                  unsigned SrcValueAlign1,
289                  const MDNode *TBAAInfo1,
290                  SDValue Ptr2, int64_t Size2,
291                  const Value *SrcValue2, int SrcValueOffset2,
292                  unsigned SrcValueAlign2,
293                  const MDNode *TBAAInfo2) const;
294
295     /// isAlias - Return true if there is any possibility that the two addresses
296     /// overlap.
297     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
298
299     /// FindAliasInfo - Extracts the relevant alias information from the memory
300     /// node.  Returns true if the operand was a load.
301     bool FindAliasInfo(SDNode *N,
302                        SDValue &Ptr, int64_t &Size,
303                        const Value *&SrcValue, int &SrcValueOffset,
304                        unsigned &SrcValueAlignment,
305                        const MDNode *&TBAAInfo) const;
306
307     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308     /// looking for a better chain (aliasing node.)
309     SDValue FindBetterChain(SDNode *N, SDValue Chain);
310
311     /// Merge consecutive store operations into a wide store.
312     /// This optimization uses wide integers or vectors when possible.
313     /// \return True if some memory operations were changed.
314     bool MergeConsecutiveStores(StoreSDNode *N);
315
316   public:
317     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
318       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
319         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
320
321     /// Run - runs the dag combiner on all nodes in the work list
322     void Run(CombineLevel AtLevel);
323
324     SelectionDAG &getDAG() const { return DAG; }
325
326     /// getShiftAmountTy - Returns a type large enough to hold any valid
327     /// shift amount - before type legalization these can be huge.
328     EVT getShiftAmountTy(EVT LHSTy) {
329       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
330       if (LHSTy.isVector())
331         return LHSTy;
332       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
333     }
334
335     /// isTypeLegal - This method returns true if we are running before type
336     /// legalization or if the specified VT is legal.
337     bool isTypeLegal(const EVT &VT) {
338       if (!LegalTypes) return true;
339       return TLI.isTypeLegal(VT);
340     }
341
342     /// getSetCCResultType - Convenience wrapper around
343     /// TargetLowering::getSetCCResultType
344     EVT getSetCCResultType(EVT VT) const {
345       return TLI.getSetCCResultType(*DAG.getContext(), VT);
346     }
347   };
348 }
349
350
351 namespace {
352 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
353 /// nodes from the worklist.
354 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
355   DAGCombiner &DC;
356 public:
357   explicit WorkListRemover(DAGCombiner &dc)
358     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
359
360   virtual void NodeDeleted(SDNode *N, SDNode *E) {
361     DC.removeFromWorkList(N);
362   }
363 };
364 }
365
366 //===----------------------------------------------------------------------===//
367 //  TargetLowering::DAGCombinerInfo implementation
368 //===----------------------------------------------------------------------===//
369
370 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
371   ((DAGCombiner*)DC)->AddToWorkList(N);
372 }
373
374 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
375   ((DAGCombiner*)DC)->removeFromWorkList(N);
376 }
377
378 SDValue TargetLowering::DAGCombinerInfo::
379 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
380   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
381 }
382
383 SDValue TargetLowering::DAGCombinerInfo::
384 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
385   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
386 }
387
388
389 SDValue TargetLowering::DAGCombinerInfo::
390 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
391   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
392 }
393
394 void TargetLowering::DAGCombinerInfo::
395 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
396   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
397 }
398
399 //===----------------------------------------------------------------------===//
400 // Helper Functions
401 //===----------------------------------------------------------------------===//
402
403 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
404 /// specified expression for the same cost as the expression itself, or 2 if we
405 /// can compute the negated form more cheaply than the expression itself.
406 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
407                                const TargetLowering &TLI,
408                                const TargetOptions *Options,
409                                unsigned Depth = 0) {
410   // fneg is removable even if it has multiple uses.
411   if (Op.getOpcode() == ISD::FNEG) return 2;
412
413   // Don't allow anything with multiple uses.
414   if (!Op.hasOneUse()) return 0;
415
416   // Don't recurse exponentially.
417   if (Depth > 6) return 0;
418
419   switch (Op.getOpcode()) {
420   default: return false;
421   case ISD::ConstantFP:
422     // Don't invert constant FP values after legalize.  The negated constant
423     // isn't necessarily legal.
424     return LegalOperations ? 0 : 1;
425   case ISD::FADD:
426     // FIXME: determine better conditions for this xform.
427     if (!Options->UnsafeFPMath) return 0;
428
429     // After operation legalization, it might not be legal to create new FSUBs.
430     if (LegalOperations &&
431         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
432       return 0;
433
434     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
435     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
436                                     Options, Depth + 1))
437       return V;
438     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
439     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
440                               Depth + 1);
441   case ISD::FSUB:
442     // We can't turn -(A-B) into B-A when we honor signed zeros.
443     if (!Options->UnsafeFPMath) return 0;
444
445     // fold (fneg (fsub A, B)) -> (fsub B, A)
446     return 1;
447
448   case ISD::FMUL:
449   case ISD::FDIV:
450     if (Options->HonorSignDependentRoundingFPMath()) return 0;
451
452     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
453     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
454                                     Options, Depth + 1))
455       return V;
456
457     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
458                               Depth + 1);
459
460   case ISD::FP_EXTEND:
461   case ISD::FP_ROUND:
462   case ISD::FSIN:
463     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
464                               Depth + 1);
465   }
466 }
467
468 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
469 /// returns the newly negated expression.
470 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
471                                     bool LegalOperations, unsigned Depth = 0) {
472   // fneg is removable even if it has multiple uses.
473   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
474
475   // Don't allow anything with multiple uses.
476   assert(Op.hasOneUse() && "Unknown reuse!");
477
478   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
479   switch (Op.getOpcode()) {
480   default: llvm_unreachable("Unknown code");
481   case ISD::ConstantFP: {
482     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
483     V.changeSign();
484     return DAG.getConstantFP(V, Op.getValueType());
485   }
486   case ISD::FADD:
487     // FIXME: determine better conditions for this xform.
488     assert(DAG.getTarget().Options.UnsafeFPMath);
489
490     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
491     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
492                            DAG.getTargetLoweringInfo(),
493                            &DAG.getTarget().Options, Depth+1))
494       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
495                          GetNegatedExpression(Op.getOperand(0), DAG,
496                                               LegalOperations, Depth+1),
497                          Op.getOperand(1));
498     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
499     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
500                        GetNegatedExpression(Op.getOperand(1), DAG,
501                                             LegalOperations, Depth+1),
502                        Op.getOperand(0));
503   case ISD::FSUB:
504     // We can't turn -(A-B) into B-A when we honor signed zeros.
505     assert(DAG.getTarget().Options.UnsafeFPMath);
506
507     // fold (fneg (fsub 0, B)) -> B
508     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
509       if (N0CFP->getValueAPF().isZero())
510         return Op.getOperand(1);
511
512     // fold (fneg (fsub A, B)) -> (fsub B, A)
513     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
514                        Op.getOperand(1), Op.getOperand(0));
515
516   case ISD::FMUL:
517   case ISD::FDIV:
518     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
519
520     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
521     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
522                            DAG.getTargetLoweringInfo(),
523                            &DAG.getTarget().Options, Depth+1))
524       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
525                          GetNegatedExpression(Op.getOperand(0), DAG,
526                                               LegalOperations, Depth+1),
527                          Op.getOperand(1));
528
529     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
530     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
531                        Op.getOperand(0),
532                        GetNegatedExpression(Op.getOperand(1), DAG,
533                                             LegalOperations, Depth+1));
534
535   case ISD::FP_EXTEND:
536   case ISD::FSIN:
537     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
538                        GetNegatedExpression(Op.getOperand(0), DAG,
539                                             LegalOperations, Depth+1));
540   case ISD::FP_ROUND:
541       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
542                          GetNegatedExpression(Op.getOperand(0), DAG,
543                                               LegalOperations, Depth+1),
544                          Op.getOperand(1));
545   }
546 }
547
548
549 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
550 // that selects between the values 1 and 0, making it equivalent to a setcc.
551 // Also, set the incoming LHS, RHS, and CC references to the appropriate
552 // nodes based on the type of node we are checking.  This simplifies life a
553 // bit for the callers.
554 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
555                               SDValue &CC) {
556   if (N.getOpcode() == ISD::SETCC) {
557     LHS = N.getOperand(0);
558     RHS = N.getOperand(1);
559     CC  = N.getOperand(2);
560     return true;
561   }
562   if (N.getOpcode() == ISD::SELECT_CC &&
563       N.getOperand(2).getOpcode() == ISD::Constant &&
564       N.getOperand(3).getOpcode() == ISD::Constant &&
565       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
566       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
567     LHS = N.getOperand(0);
568     RHS = N.getOperand(1);
569     CC  = N.getOperand(4);
570     return true;
571   }
572   return false;
573 }
574
575 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
576 // one use.  If this is true, it allows the users to invert the operation for
577 // free when it is profitable to do so.
578 static bool isOneUseSetCC(SDValue N) {
579   SDValue N0, N1, N2;
580   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
581     return true;
582   return false;
583 }
584
585 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
586                                     SDValue N0, SDValue N1) {
587   EVT VT = N0.getValueType();
588   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
589     if (isa<ConstantSDNode>(N1)) {
590       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
591       SDValue OpNode =
592         DAG.FoldConstantArithmetic(Opc, VT,
593                                    cast<ConstantSDNode>(N0.getOperand(1)),
594                                    cast<ConstantSDNode>(N1));
595       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
596     }
597     if (N0.hasOneUse()) {
598       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
599       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
600                                    N0.getOperand(0), N1);
601       AddToWorkList(OpNode.getNode());
602       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
603     }
604   }
605
606   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
607     if (isa<ConstantSDNode>(N0)) {
608       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
609       SDValue OpNode =
610         DAG.FoldConstantArithmetic(Opc, VT,
611                                    cast<ConstantSDNode>(N1.getOperand(1)),
612                                    cast<ConstantSDNode>(N0));
613       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
614     }
615     if (N1.hasOneUse()) {
616       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
617       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
618                                    N1.getOperand(0), N0);
619       AddToWorkList(OpNode.getNode());
620       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
621     }
622   }
623
624   return SDValue();
625 }
626
627 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
628                                bool AddTo) {
629   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
630   ++NodesCombined;
631   DEBUG(dbgs() << "\nReplacing.1 ";
632         N->dump(&DAG);
633         dbgs() << "\nWith: ";
634         To[0].getNode()->dump(&DAG);
635         dbgs() << " and " << NumTo-1 << " other values\n";
636         for (unsigned i = 0, e = NumTo; i != e; ++i)
637           assert((!To[i].getNode() ||
638                   N->getValueType(i) == To[i].getValueType()) &&
639                  "Cannot combine value to value of different type!"));
640   WorkListRemover DeadNodes(*this);
641   DAG.ReplaceAllUsesWith(N, To);
642   if (AddTo) {
643     // Push the new nodes and any users onto the worklist
644     for (unsigned i = 0, e = NumTo; i != e; ++i) {
645       if (To[i].getNode()) {
646         AddToWorkList(To[i].getNode());
647         AddUsersToWorkList(To[i].getNode());
648       }
649     }
650   }
651
652   // Finally, if the node is now dead, remove it from the graph.  The node
653   // may not be dead if the replacement process recursively simplified to
654   // something else needing this node.
655   if (N->use_empty()) {
656     // Nodes can be reintroduced into the worklist.  Make sure we do not
657     // process a node that has been replaced.
658     removeFromWorkList(N);
659
660     // Finally, since the node is now dead, remove it from the graph.
661     DAG.DeleteNode(N);
662   }
663   return SDValue(N, 0);
664 }
665
666 void DAGCombiner::
667 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
668   // Replace all uses.  If any nodes become isomorphic to other nodes and
669   // are deleted, make sure to remove them from our worklist.
670   WorkListRemover DeadNodes(*this);
671   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
672
673   // Push the new node and any (possibly new) users onto the worklist.
674   AddToWorkList(TLO.New.getNode());
675   AddUsersToWorkList(TLO.New.getNode());
676
677   // Finally, if the node is now dead, remove it from the graph.  The node
678   // may not be dead if the replacement process recursively simplified to
679   // something else needing this node.
680   if (TLO.Old.getNode()->use_empty()) {
681     removeFromWorkList(TLO.Old.getNode());
682
683     // If the operands of this node are only used by the node, they will now
684     // be dead.  Make sure to visit them first to delete dead nodes early.
685     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
686       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
687         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
688
689     DAG.DeleteNode(TLO.Old.getNode());
690   }
691 }
692
693 /// SimplifyDemandedBits - Check the specified integer node value to see if
694 /// it can be simplified or if things it uses can be simplified by bit
695 /// propagation.  If so, return true.
696 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
697   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
698   APInt KnownZero, KnownOne;
699   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
700     return false;
701
702   // Revisit the node.
703   AddToWorkList(Op.getNode());
704
705   // Replace the old value with the new one.
706   ++NodesCombined;
707   DEBUG(dbgs() << "\nReplacing.2 ";
708         TLO.Old.getNode()->dump(&DAG);
709         dbgs() << "\nWith: ";
710         TLO.New.getNode()->dump(&DAG);
711         dbgs() << '\n');
712
713   CommitTargetLoweringOpt(TLO);
714   return true;
715 }
716
717 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
718   SDLoc dl(Load);
719   EVT VT = Load->getValueType(0);
720   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
721
722   DEBUG(dbgs() << "\nReplacing.9 ";
723         Load->dump(&DAG);
724         dbgs() << "\nWith: ";
725         Trunc.getNode()->dump(&DAG);
726         dbgs() << '\n');
727   WorkListRemover DeadNodes(*this);
728   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
729   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
730   removeFromWorkList(Load);
731   DAG.DeleteNode(Load);
732   AddToWorkList(Trunc.getNode());
733 }
734
735 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
736   Replace = false;
737   SDLoc dl(Op);
738   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
739     EVT MemVT = LD->getMemoryVT();
740     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
741       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
742                                                   : ISD::EXTLOAD)
743       : LD->getExtensionType();
744     Replace = true;
745     return DAG.getExtLoad(ExtType, dl, PVT,
746                           LD->getChain(), LD->getBasePtr(),
747                           LD->getPointerInfo(),
748                           MemVT, LD->isVolatile(),
749                           LD->isNonTemporal(), LD->getAlignment());
750   }
751
752   unsigned Opc = Op.getOpcode();
753   switch (Opc) {
754   default: break;
755   case ISD::AssertSext:
756     return DAG.getNode(ISD::AssertSext, dl, PVT,
757                        SExtPromoteOperand(Op.getOperand(0), PVT),
758                        Op.getOperand(1));
759   case ISD::AssertZext:
760     return DAG.getNode(ISD::AssertZext, dl, PVT,
761                        ZExtPromoteOperand(Op.getOperand(0), PVT),
762                        Op.getOperand(1));
763   case ISD::Constant: {
764     unsigned ExtOpc =
765       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
766     return DAG.getNode(ExtOpc, dl, PVT, Op);
767   }
768   }
769
770   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
771     return SDValue();
772   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
773 }
774
775 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
776   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
777     return SDValue();
778   EVT OldVT = Op.getValueType();
779   SDLoc dl(Op);
780   bool Replace = false;
781   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
782   if (NewOp.getNode() == 0)
783     return SDValue();
784   AddToWorkList(NewOp.getNode());
785
786   if (Replace)
787     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
788   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
789                      DAG.getValueType(OldVT));
790 }
791
792 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
793   EVT OldVT = Op.getValueType();
794   SDLoc dl(Op);
795   bool Replace = false;
796   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
797   if (NewOp.getNode() == 0)
798     return SDValue();
799   AddToWorkList(NewOp.getNode());
800
801   if (Replace)
802     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
803   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
804 }
805
806 /// PromoteIntBinOp - Promote the specified integer binary operation if the
807 /// target indicates it is beneficial. e.g. On x86, it's usually better to
808 /// promote i16 operations to i32 since i16 instructions are longer.
809 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
810   if (!LegalOperations)
811     return SDValue();
812
813   EVT VT = Op.getValueType();
814   if (VT.isVector() || !VT.isInteger())
815     return SDValue();
816
817   // If operation type is 'undesirable', e.g. i16 on x86, consider
818   // promoting it.
819   unsigned Opc = Op.getOpcode();
820   if (TLI.isTypeDesirableForOp(Opc, VT))
821     return SDValue();
822
823   EVT PVT = VT;
824   // Consult target whether it is a good idea to promote this operation and
825   // what's the right type to promote it to.
826   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
827     assert(PVT != VT && "Don't know what type to promote to!");
828
829     bool Replace0 = false;
830     SDValue N0 = Op.getOperand(0);
831     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
832     if (NN0.getNode() == 0)
833       return SDValue();
834
835     bool Replace1 = false;
836     SDValue N1 = Op.getOperand(1);
837     SDValue NN1;
838     if (N0 == N1)
839       NN1 = NN0;
840     else {
841       NN1 = PromoteOperand(N1, PVT, Replace1);
842       if (NN1.getNode() == 0)
843         return SDValue();
844     }
845
846     AddToWorkList(NN0.getNode());
847     if (NN1.getNode())
848       AddToWorkList(NN1.getNode());
849
850     if (Replace0)
851       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
852     if (Replace1)
853       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
854
855     DEBUG(dbgs() << "\nPromoting ";
856           Op.getNode()->dump(&DAG));
857     SDLoc dl(Op);
858     return DAG.getNode(ISD::TRUNCATE, dl, VT,
859                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
860   }
861   return SDValue();
862 }
863
864 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
865 /// target indicates it is beneficial. e.g. On x86, it's usually better to
866 /// promote i16 operations to i32 since i16 instructions are longer.
867 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
868   if (!LegalOperations)
869     return SDValue();
870
871   EVT VT = Op.getValueType();
872   if (VT.isVector() || !VT.isInteger())
873     return SDValue();
874
875   // If operation type is 'undesirable', e.g. i16 on x86, consider
876   // promoting it.
877   unsigned Opc = Op.getOpcode();
878   if (TLI.isTypeDesirableForOp(Opc, VT))
879     return SDValue();
880
881   EVT PVT = VT;
882   // Consult target whether it is a good idea to promote this operation and
883   // what's the right type to promote it to.
884   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
885     assert(PVT != VT && "Don't know what type to promote to!");
886
887     bool Replace = false;
888     SDValue N0 = Op.getOperand(0);
889     if (Opc == ISD::SRA)
890       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
891     else if (Opc == ISD::SRL)
892       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
893     else
894       N0 = PromoteOperand(N0, PVT, Replace);
895     if (N0.getNode() == 0)
896       return SDValue();
897
898     AddToWorkList(N0.getNode());
899     if (Replace)
900       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
901
902     DEBUG(dbgs() << "\nPromoting ";
903           Op.getNode()->dump(&DAG));
904     SDLoc dl(Op);
905     return DAG.getNode(ISD::TRUNCATE, dl, VT,
906                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
907   }
908   return SDValue();
909 }
910
911 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
912   if (!LegalOperations)
913     return SDValue();
914
915   EVT VT = Op.getValueType();
916   if (VT.isVector() || !VT.isInteger())
917     return SDValue();
918
919   // If operation type is 'undesirable', e.g. i16 on x86, consider
920   // promoting it.
921   unsigned Opc = Op.getOpcode();
922   if (TLI.isTypeDesirableForOp(Opc, VT))
923     return SDValue();
924
925   EVT PVT = VT;
926   // Consult target whether it is a good idea to promote this operation and
927   // what's the right type to promote it to.
928   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
929     assert(PVT != VT && "Don't know what type to promote to!");
930     // fold (aext (aext x)) -> (aext x)
931     // fold (aext (zext x)) -> (zext x)
932     // fold (aext (sext x)) -> (sext x)
933     DEBUG(dbgs() << "\nPromoting ";
934           Op.getNode()->dump(&DAG));
935     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
936   }
937   return SDValue();
938 }
939
940 bool DAGCombiner::PromoteLoad(SDValue Op) {
941   if (!LegalOperations)
942     return false;
943
944   EVT VT = Op.getValueType();
945   if (VT.isVector() || !VT.isInteger())
946     return false;
947
948   // If operation type is 'undesirable', e.g. i16 on x86, consider
949   // promoting it.
950   unsigned Opc = Op.getOpcode();
951   if (TLI.isTypeDesirableForOp(Opc, VT))
952     return false;
953
954   EVT PVT = VT;
955   // Consult target whether it is a good idea to promote this operation and
956   // what's the right type to promote it to.
957   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
958     assert(PVT != VT && "Don't know what type to promote to!");
959
960     SDLoc dl(Op);
961     SDNode *N = Op.getNode();
962     LoadSDNode *LD = cast<LoadSDNode>(N);
963     EVT MemVT = LD->getMemoryVT();
964     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
965       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
966                                                   : ISD::EXTLOAD)
967       : LD->getExtensionType();
968     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
969                                    LD->getChain(), LD->getBasePtr(),
970                                    LD->getPointerInfo(),
971                                    MemVT, LD->isVolatile(),
972                                    LD->isNonTemporal(), LD->getAlignment());
973     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
974
975     DEBUG(dbgs() << "\nPromoting ";
976           N->dump(&DAG);
977           dbgs() << "\nTo: ";
978           Result.getNode()->dump(&DAG);
979           dbgs() << '\n');
980     WorkListRemover DeadNodes(*this);
981     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
983     removeFromWorkList(N);
984     DAG.DeleteNode(N);
985     AddToWorkList(Result.getNode());
986     return true;
987   }
988   return false;
989 }
990
991
992 //===----------------------------------------------------------------------===//
993 //  Main DAG Combiner implementation
994 //===----------------------------------------------------------------------===//
995
996 void DAGCombiner::Run(CombineLevel AtLevel) {
997   // set the instance variables, so that the various visit routines may use it.
998   Level = AtLevel;
999   LegalOperations = Level >= AfterLegalizeVectorOps;
1000   LegalTypes = Level >= AfterLegalizeTypes;
1001
1002   // Add all the dag nodes to the worklist.
1003   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1004        E = DAG.allnodes_end(); I != E; ++I)
1005     AddToWorkList(I);
1006
1007   // Create a dummy node (which is not added to allnodes), that adds a reference
1008   // to the root node, preventing it from being deleted, and tracking any
1009   // changes of the root.
1010   HandleSDNode Dummy(DAG.getRoot());
1011
1012   // The root of the dag may dangle to deleted nodes until the dag combiner is
1013   // done.  Set it to null to avoid confusion.
1014   DAG.setRoot(SDValue());
1015
1016   // while the worklist isn't empty, find a node and
1017   // try and combine it.
1018   while (!WorkListContents.empty()) {
1019     SDNode *N;
1020     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1021     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1022     // worklist *should* contain, and check the node we want to visit is should
1023     // actually be visited.
1024     do {
1025       N = WorkListOrder.pop_back_val();
1026     } while (!WorkListContents.erase(N));
1027
1028     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1029     // N is deleted from the DAG, since they too may now be dead or may have a
1030     // reduced number of uses, allowing other xforms.
1031     if (N->use_empty() && N != &Dummy) {
1032       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1033         AddToWorkList(N->getOperand(i).getNode());
1034
1035       DAG.DeleteNode(N);
1036       continue;
1037     }
1038
1039     SDValue RV = combine(N);
1040
1041     if (RV.getNode() == 0)
1042       continue;
1043
1044     ++NodesCombined;
1045
1046     // If we get back the same node we passed in, rather than a new node or
1047     // zero, we know that the node must have defined multiple values and
1048     // CombineTo was used.  Since CombineTo takes care of the worklist
1049     // mechanics for us, we have no work to do in this case.
1050     if (RV.getNode() == N)
1051       continue;
1052
1053     assert(N->getOpcode() != ISD::DELETED_NODE &&
1054            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1055            "Node was deleted but visit returned new node!");
1056
1057     DEBUG(dbgs() << "\nReplacing.3 ";
1058           N->dump(&DAG);
1059           dbgs() << "\nWith: ";
1060           RV.getNode()->dump(&DAG);
1061           dbgs() << '\n');
1062
1063     // Transfer debug value.
1064     DAG.TransferDbgValues(SDValue(N, 0), RV);
1065     WorkListRemover DeadNodes(*this);
1066     if (N->getNumValues() == RV.getNode()->getNumValues())
1067       DAG.ReplaceAllUsesWith(N, RV.getNode());
1068     else {
1069       assert(N->getValueType(0) == RV.getValueType() &&
1070              N->getNumValues() == 1 && "Type mismatch");
1071       SDValue OpV = RV;
1072       DAG.ReplaceAllUsesWith(N, &OpV);
1073     }
1074
1075     // Push the new node and any users onto the worklist
1076     AddToWorkList(RV.getNode());
1077     AddUsersToWorkList(RV.getNode());
1078
1079     // Add any uses of the old node to the worklist in case this node is the
1080     // last one that uses them.  They may become dead after this node is
1081     // deleted.
1082     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1083       AddToWorkList(N->getOperand(i).getNode());
1084
1085     // Finally, if the node is now dead, remove it from the graph.  The node
1086     // may not be dead if the replacement process recursively simplified to
1087     // something else needing this node.
1088     if (N->use_empty()) {
1089       // Nodes can be reintroduced into the worklist.  Make sure we do not
1090       // process a node that has been replaced.
1091       removeFromWorkList(N);
1092
1093       // Finally, since the node is now dead, remove it from the graph.
1094       DAG.DeleteNode(N);
1095     }
1096   }
1097
1098   // If the root changed (e.g. it was a dead load, update the root).
1099   DAG.setRoot(Dummy.getValue());
1100   DAG.RemoveDeadNodes();
1101 }
1102
1103 SDValue DAGCombiner::visit(SDNode *N) {
1104   switch (N->getOpcode()) {
1105   default: break;
1106   case ISD::TokenFactor:        return visitTokenFactor(N);
1107   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1108   case ISD::ADD:                return visitADD(N);
1109   case ISD::SUB:                return visitSUB(N);
1110   case ISD::ADDC:               return visitADDC(N);
1111   case ISD::SUBC:               return visitSUBC(N);
1112   case ISD::ADDE:               return visitADDE(N);
1113   case ISD::SUBE:               return visitSUBE(N);
1114   case ISD::MUL:                return visitMUL(N);
1115   case ISD::SDIV:               return visitSDIV(N);
1116   case ISD::UDIV:               return visitUDIV(N);
1117   case ISD::SREM:               return visitSREM(N);
1118   case ISD::UREM:               return visitUREM(N);
1119   case ISD::MULHU:              return visitMULHU(N);
1120   case ISD::MULHS:              return visitMULHS(N);
1121   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1122   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1123   case ISD::SMULO:              return visitSMULO(N);
1124   case ISD::UMULO:              return visitUMULO(N);
1125   case ISD::SDIVREM:            return visitSDIVREM(N);
1126   case ISD::UDIVREM:            return visitUDIVREM(N);
1127   case ISD::AND:                return visitAND(N);
1128   case ISD::OR:                 return visitOR(N);
1129   case ISD::XOR:                return visitXOR(N);
1130   case ISD::SHL:                return visitSHL(N);
1131   case ISD::SRA:                return visitSRA(N);
1132   case ISD::SRL:                return visitSRL(N);
1133   case ISD::CTLZ:               return visitCTLZ(N);
1134   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1135   case ISD::CTTZ:               return visitCTTZ(N);
1136   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1137   case ISD::CTPOP:              return visitCTPOP(N);
1138   case ISD::SELECT:             return visitSELECT(N);
1139   case ISD::VSELECT:            return visitVSELECT(N);
1140   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1141   case ISD::SETCC:              return visitSETCC(N);
1142   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1143   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1144   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1145   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1146   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1147   case ISD::BITCAST:            return visitBITCAST(N);
1148   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1149   case ISD::FADD:               return visitFADD(N);
1150   case ISD::FSUB:               return visitFSUB(N);
1151   case ISD::FMUL:               return visitFMUL(N);
1152   case ISD::FMA:                return visitFMA(N);
1153   case ISD::FDIV:               return visitFDIV(N);
1154   case ISD::FREM:               return visitFREM(N);
1155   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1156   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1157   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1158   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1159   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1160   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1161   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1162   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1163   case ISD::FNEG:               return visitFNEG(N);
1164   case ISD::FABS:               return visitFABS(N);
1165   case ISD::FFLOOR:             return visitFFLOOR(N);
1166   case ISD::FCEIL:              return visitFCEIL(N);
1167   case ISD::FTRUNC:             return visitFTRUNC(N);
1168   case ISD::BRCOND:             return visitBRCOND(N);
1169   case ISD::BR_CC:              return visitBR_CC(N);
1170   case ISD::LOAD:               return visitLOAD(N);
1171   case ISD::STORE:              return visitSTORE(N);
1172   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1173   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1174   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1175   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1176   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1177   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1178   }
1179   return SDValue();
1180 }
1181
1182 SDValue DAGCombiner::combine(SDNode *N) {
1183   SDValue RV = visit(N);
1184
1185   // If nothing happened, try a target-specific DAG combine.
1186   if (RV.getNode() == 0) {
1187     assert(N->getOpcode() != ISD::DELETED_NODE &&
1188            "Node was deleted but visit returned NULL!");
1189
1190     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1191         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1192
1193       // Expose the DAG combiner to the target combiner impls.
1194       TargetLowering::DAGCombinerInfo
1195         DagCombineInfo(DAG, Level, false, this);
1196
1197       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1198     }
1199   }
1200
1201   // If nothing happened still, try promoting the operation.
1202   if (RV.getNode() == 0) {
1203     switch (N->getOpcode()) {
1204     default: break;
1205     case ISD::ADD:
1206     case ISD::SUB:
1207     case ISD::MUL:
1208     case ISD::AND:
1209     case ISD::OR:
1210     case ISD::XOR:
1211       RV = PromoteIntBinOp(SDValue(N, 0));
1212       break;
1213     case ISD::SHL:
1214     case ISD::SRA:
1215     case ISD::SRL:
1216       RV = PromoteIntShiftOp(SDValue(N, 0));
1217       break;
1218     case ISD::SIGN_EXTEND:
1219     case ISD::ZERO_EXTEND:
1220     case ISD::ANY_EXTEND:
1221       RV = PromoteExtend(SDValue(N, 0));
1222       break;
1223     case ISD::LOAD:
1224       if (PromoteLoad(SDValue(N, 0)))
1225         RV = SDValue(N, 0);
1226       break;
1227     }
1228   }
1229
1230   // If N is a commutative binary node, try commuting it to enable more
1231   // sdisel CSE.
1232   if (RV.getNode() == 0 &&
1233       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1234       N->getNumValues() == 1) {
1235     SDValue N0 = N->getOperand(0);
1236     SDValue N1 = N->getOperand(1);
1237
1238     // Constant operands are canonicalized to RHS.
1239     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1240       SDValue Ops[] = { N1, N0 };
1241       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1242                                             Ops, 2);
1243       if (CSENode)
1244         return SDValue(CSENode, 0);
1245     }
1246   }
1247
1248   return RV;
1249 }
1250
1251 /// getInputChainForNode - Given a node, return its input chain if it has one,
1252 /// otherwise return a null sd operand.
1253 static SDValue getInputChainForNode(SDNode *N) {
1254   if (unsigned NumOps = N->getNumOperands()) {
1255     if (N->getOperand(0).getValueType() == MVT::Other)
1256       return N->getOperand(0);
1257     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1258       return N->getOperand(NumOps-1);
1259     for (unsigned i = 1; i < NumOps-1; ++i)
1260       if (N->getOperand(i).getValueType() == MVT::Other)
1261         return N->getOperand(i);
1262   }
1263   return SDValue();
1264 }
1265
1266 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1267   // If N has two operands, where one has an input chain equal to the other,
1268   // the 'other' chain is redundant.
1269   if (N->getNumOperands() == 2) {
1270     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1271       return N->getOperand(0);
1272     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1273       return N->getOperand(1);
1274   }
1275
1276   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1277   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1278   SmallPtrSet<SDNode*, 16> SeenOps;
1279   bool Changed = false;             // If we should replace this token factor.
1280
1281   // Start out with this token factor.
1282   TFs.push_back(N);
1283
1284   // Iterate through token factors.  The TFs grows when new token factors are
1285   // encountered.
1286   for (unsigned i = 0; i < TFs.size(); ++i) {
1287     SDNode *TF = TFs[i];
1288
1289     // Check each of the operands.
1290     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1291       SDValue Op = TF->getOperand(i);
1292
1293       switch (Op.getOpcode()) {
1294       case ISD::EntryToken:
1295         // Entry tokens don't need to be added to the list. They are
1296         // rededundant.
1297         Changed = true;
1298         break;
1299
1300       case ISD::TokenFactor:
1301         if (Op.hasOneUse() &&
1302             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1303           // Queue up for processing.
1304           TFs.push_back(Op.getNode());
1305           // Clean up in case the token factor is removed.
1306           AddToWorkList(Op.getNode());
1307           Changed = true;
1308           break;
1309         }
1310         // Fall thru
1311
1312       default:
1313         // Only add if it isn't already in the list.
1314         if (SeenOps.insert(Op.getNode()))
1315           Ops.push_back(Op);
1316         else
1317           Changed = true;
1318         break;
1319       }
1320     }
1321   }
1322
1323   SDValue Result;
1324
1325   // If we've change things around then replace token factor.
1326   if (Changed) {
1327     if (Ops.empty()) {
1328       // The entry token is the only possible outcome.
1329       Result = DAG.getEntryNode();
1330     } else {
1331       // New and improved token factor.
1332       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1333                            MVT::Other, &Ops[0], Ops.size());
1334     }
1335
1336     // Don't add users to work list.
1337     return CombineTo(N, Result, false);
1338   }
1339
1340   return Result;
1341 }
1342
1343 /// MERGE_VALUES can always be eliminated.
1344 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1345   WorkListRemover DeadNodes(*this);
1346   // Replacing results may cause a different MERGE_VALUES to suddenly
1347   // be CSE'd with N, and carry its uses with it. Iterate until no
1348   // uses remain, to ensure that the node can be safely deleted.
1349   // First add the users of this node to the work list so that they
1350   // can be tried again once they have new operands.
1351   AddUsersToWorkList(N);
1352   do {
1353     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1354       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1355   } while (!N->use_empty());
1356   removeFromWorkList(N);
1357   DAG.DeleteNode(N);
1358   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1359 }
1360
1361 static
1362 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1363                               SelectionDAG &DAG) {
1364   EVT VT = N0.getValueType();
1365   SDValue N00 = N0.getOperand(0);
1366   SDValue N01 = N0.getOperand(1);
1367   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1368
1369   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1370       isa<ConstantSDNode>(N00.getOperand(1))) {
1371     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1372     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1373                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1374                                  N00.getOperand(0), N01),
1375                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1376                                  N00.getOperand(1), N01));
1377     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1378   }
1379
1380   return SDValue();
1381 }
1382
1383 SDValue DAGCombiner::visitADD(SDNode *N) {
1384   SDValue N0 = N->getOperand(0);
1385   SDValue N1 = N->getOperand(1);
1386   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1387   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1388   EVT VT = N0.getValueType();
1389
1390   // fold vector ops
1391   if (VT.isVector()) {
1392     SDValue FoldedVOp = SimplifyVBinOp(N);
1393     if (FoldedVOp.getNode()) return FoldedVOp;
1394
1395     // fold (add x, 0) -> x, vector edition
1396     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1397       return N0;
1398     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1399       return N1;
1400   }
1401
1402   // fold (add x, undef) -> undef
1403   if (N0.getOpcode() == ISD::UNDEF)
1404     return N0;
1405   if (N1.getOpcode() == ISD::UNDEF)
1406     return N1;
1407   // fold (add c1, c2) -> c1+c2
1408   if (N0C && N1C)
1409     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1410   // canonicalize constant to RHS
1411   if (N0C && !N1C)
1412     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1413   // fold (add x, 0) -> x
1414   if (N1C && N1C->isNullValue())
1415     return N0;
1416   // fold (add Sym, c) -> Sym+c
1417   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1418     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1419         GA->getOpcode() == ISD::GlobalAddress)
1420       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1421                                   GA->getOffset() +
1422                                     (uint64_t)N1C->getSExtValue());
1423   // fold ((c1-A)+c2) -> (c1+c2)-A
1424   if (N1C && N0.getOpcode() == ISD::SUB)
1425     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1426       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1427                          DAG.getConstant(N1C->getAPIntValue()+
1428                                          N0C->getAPIntValue(), VT),
1429                          N0.getOperand(1));
1430   // reassociate add
1431   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1432   if (RADD.getNode() != 0)
1433     return RADD;
1434   // fold ((0-A) + B) -> B-A
1435   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1436       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1437     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1438   // fold (A + (0-B)) -> A-B
1439   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1440       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1441     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1442   // fold (A+(B-A)) -> B
1443   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1444     return N1.getOperand(0);
1445   // fold ((B-A)+A) -> B
1446   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1447     return N0.getOperand(0);
1448   // fold (A+(B-(A+C))) to (B-C)
1449   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1450       N0 == N1.getOperand(1).getOperand(0))
1451     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1452                        N1.getOperand(1).getOperand(1));
1453   // fold (A+(B-(C+A))) to (B-C)
1454   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1455       N0 == N1.getOperand(1).getOperand(1))
1456     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1457                        N1.getOperand(1).getOperand(0));
1458   // fold (A+((B-A)+or-C)) to (B+or-C)
1459   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1460       N1.getOperand(0).getOpcode() == ISD::SUB &&
1461       N0 == N1.getOperand(0).getOperand(1))
1462     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1463                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1464
1465   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1466   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1467     SDValue N00 = N0.getOperand(0);
1468     SDValue N01 = N0.getOperand(1);
1469     SDValue N10 = N1.getOperand(0);
1470     SDValue N11 = N1.getOperand(1);
1471
1472     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1473       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1474                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1475                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1476   }
1477
1478   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1479     return SDValue(N, 0);
1480
1481   // fold (a+b) -> (a|b) iff a and b share no bits.
1482   if (VT.isInteger() && !VT.isVector()) {
1483     APInt LHSZero, LHSOne;
1484     APInt RHSZero, RHSOne;
1485     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1486
1487     if (LHSZero.getBoolValue()) {
1488       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1489
1490       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1491       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1492       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1493         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1494     }
1495   }
1496
1497   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1498   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1499     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1500     if (Result.getNode()) return Result;
1501   }
1502   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1503     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1504     if (Result.getNode()) return Result;
1505   }
1506
1507   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1508   if (N1.getOpcode() == ISD::SHL &&
1509       N1.getOperand(0).getOpcode() == ISD::SUB)
1510     if (ConstantSDNode *C =
1511           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1512       if (C->getAPIntValue() == 0)
1513         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1514                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1515                                        N1.getOperand(0).getOperand(1),
1516                                        N1.getOperand(1)));
1517   if (N0.getOpcode() == ISD::SHL &&
1518       N0.getOperand(0).getOpcode() == ISD::SUB)
1519     if (ConstantSDNode *C =
1520           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1521       if (C->getAPIntValue() == 0)
1522         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1523                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1524                                        N0.getOperand(0).getOperand(1),
1525                                        N0.getOperand(1)));
1526
1527   if (N1.getOpcode() == ISD::AND) {
1528     SDValue AndOp0 = N1.getOperand(0);
1529     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1530     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1531     unsigned DestBits = VT.getScalarType().getSizeInBits();
1532
1533     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1534     // and similar xforms where the inner op is either ~0 or 0.
1535     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1536       SDLoc DL(N);
1537       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1538     }
1539   }
1540
1541   // add (sext i1), X -> sub X, (zext i1)
1542   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1543       N0.getOperand(0).getValueType() == MVT::i1 &&
1544       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1545     SDLoc DL(N);
1546     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1547     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1548   }
1549
1550   return SDValue();
1551 }
1552
1553 SDValue DAGCombiner::visitADDC(SDNode *N) {
1554   SDValue N0 = N->getOperand(0);
1555   SDValue N1 = N->getOperand(1);
1556   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1557   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1558   EVT VT = N0.getValueType();
1559
1560   // If the flag result is dead, turn this into an ADD.
1561   if (!N->hasAnyUseOfValue(1))
1562     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1563                      DAG.getNode(ISD::CARRY_FALSE,
1564                                  SDLoc(N), MVT::Glue));
1565
1566   // canonicalize constant to RHS.
1567   if (N0C && !N1C)
1568     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1569
1570   // fold (addc x, 0) -> x + no carry out
1571   if (N1C && N1C->isNullValue())
1572     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1573                                         SDLoc(N), MVT::Glue));
1574
1575   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1576   APInt LHSZero, LHSOne;
1577   APInt RHSZero, RHSOne;
1578   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1579
1580   if (LHSZero.getBoolValue()) {
1581     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1582
1583     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1586       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1587                        DAG.getNode(ISD::CARRY_FALSE,
1588                                    SDLoc(N), MVT::Glue));
1589   }
1590
1591   return SDValue();
1592 }
1593
1594 SDValue DAGCombiner::visitADDE(SDNode *N) {
1595   SDValue N0 = N->getOperand(0);
1596   SDValue N1 = N->getOperand(1);
1597   SDValue CarryIn = N->getOperand(2);
1598   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1599   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1600
1601   // canonicalize constant to RHS
1602   if (N0C && !N1C)
1603     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1604                        N1, N0, CarryIn);
1605
1606   // fold (adde x, y, false) -> (addc x, y)
1607   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1608     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1609
1610   return SDValue();
1611 }
1612
1613 // Since it may not be valid to emit a fold to zero for vector initializers
1614 // check if we can before folding.
1615 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1616                              SelectionDAG &DAG,
1617                              bool LegalOperations, bool LegalTypes) {
1618   if (!VT.isVector())
1619     return DAG.getConstant(0, VT);
1620   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1621     // Produce a vector of zeros.
1622     EVT ElemTy = VT.getVectorElementType();
1623     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1624                       TargetLowering::TypePromoteInteger)
1625       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1626     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1627            "Type for zero vector elements is not legal");
1628     SDValue El = DAG.getConstant(0, ElemTy);
1629     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1630     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1631       &Ops[0], Ops.size());
1632   }
1633   return SDValue();
1634 }
1635
1636 SDValue DAGCombiner::visitSUB(SDNode *N) {
1637   SDValue N0 = N->getOperand(0);
1638   SDValue N1 = N->getOperand(1);
1639   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1640   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1641   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1642     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1643   EVT VT = N0.getValueType();
1644
1645   // fold vector ops
1646   if (VT.isVector()) {
1647     SDValue FoldedVOp = SimplifyVBinOp(N);
1648     if (FoldedVOp.getNode()) return FoldedVOp;
1649
1650     // fold (sub x, 0) -> x, vector edition
1651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1652       return N0;
1653   }
1654
1655   // fold (sub x, x) -> 0
1656   // FIXME: Refactor this and xor and other similar operations together.
1657   if (N0 == N1)
1658     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1659   // fold (sub c1, c2) -> c1-c2
1660   if (N0C && N1C)
1661     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1662   // fold (sub x, c) -> (add x, -c)
1663   if (N1C)
1664     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1665                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1666   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1667   if (N0C && N0C->isAllOnesValue())
1668     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1669   // fold A-(A-B) -> B
1670   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1671     return N1.getOperand(1);
1672   // fold (A+B)-A -> B
1673   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1674     return N0.getOperand(1);
1675   // fold (A+B)-B -> A
1676   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1677     return N0.getOperand(0);
1678   // fold C2-(A+C1) -> (C2-C1)-A
1679   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1680     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1681                                    VT);
1682     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1683                        N1.getOperand(0));
1684   }
1685   // fold ((A+(B+or-C))-B) -> A+or-C
1686   if (N0.getOpcode() == ISD::ADD &&
1687       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1688        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1689       N0.getOperand(1).getOperand(0) == N1)
1690     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1691                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1692   // fold ((A+(C+B))-B) -> A+C
1693   if (N0.getOpcode() == ISD::ADD &&
1694       N0.getOperand(1).getOpcode() == ISD::ADD &&
1695       N0.getOperand(1).getOperand(1) == N1)
1696     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1697                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1698   // fold ((A-(B-C))-C) -> A-B
1699   if (N0.getOpcode() == ISD::SUB &&
1700       N0.getOperand(1).getOpcode() == ISD::SUB &&
1701       N0.getOperand(1).getOperand(1) == N1)
1702     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1703                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1704
1705   // If either operand of a sub is undef, the result is undef
1706   if (N0.getOpcode() == ISD::UNDEF)
1707     return N0;
1708   if (N1.getOpcode() == ISD::UNDEF)
1709     return N1;
1710
1711   // If the relocation model supports it, consider symbol offsets.
1712   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1713     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1714       // fold (sub Sym, c) -> Sym-c
1715       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1716         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1717                                     GA->getOffset() -
1718                                       (uint64_t)N1C->getSExtValue());
1719       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1720       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1721         if (GA->getGlobal() == GB->getGlobal())
1722           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1723                                  VT);
1724     }
1725
1726   return SDValue();
1727 }
1728
1729 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1730   SDValue N0 = N->getOperand(0);
1731   SDValue N1 = N->getOperand(1);
1732   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1733   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1734   EVT VT = N0.getValueType();
1735
1736   // If the flag result is dead, turn this into an SUB.
1737   if (!N->hasAnyUseOfValue(1))
1738     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1739                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1740                                  MVT::Glue));
1741
1742   // fold (subc x, x) -> 0 + no borrow
1743   if (N0 == N1)
1744     return CombineTo(N, DAG.getConstant(0, VT),
1745                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1746                                  MVT::Glue));
1747
1748   // fold (subc x, 0) -> x + no borrow
1749   if (N1C && N1C->isNullValue())
1750     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1751                                         MVT::Glue));
1752
1753   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1754   if (N0C && N0C->isAllOnesValue())
1755     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1756                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1757                                  MVT::Glue));
1758
1759   return SDValue();
1760 }
1761
1762 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1763   SDValue N0 = N->getOperand(0);
1764   SDValue N1 = N->getOperand(1);
1765   SDValue CarryIn = N->getOperand(2);
1766
1767   // fold (sube x, y, false) -> (subc x, y)
1768   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1769     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1770
1771   return SDValue();
1772 }
1773
1774 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1775 /// all the same constant or undefined.
1776 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1777   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1778   if (!C)
1779     return false;
1780
1781   APInt SplatUndef;
1782   unsigned SplatBitSize;
1783   bool HasAnyUndefs;
1784   EVT EltVT = N->getValueType(0).getVectorElementType();
1785   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1786                              HasAnyUndefs) &&
1787           EltVT.getSizeInBits() >= SplatBitSize);
1788 }
1789
1790 SDValue DAGCombiner::visitMUL(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   EVT VT = N0.getValueType();
1794
1795   // fold (mul x, undef) -> 0
1796   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1797     return DAG.getConstant(0, VT);
1798
1799   bool N0IsConst = false;
1800   bool N1IsConst = false;
1801   APInt ConstValue0, ConstValue1;
1802   // fold vector ops
1803   if (VT.isVector()) {
1804     SDValue FoldedVOp = SimplifyVBinOp(N);
1805     if (FoldedVOp.getNode()) return FoldedVOp;
1806
1807     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1808     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1809   } else {
1810     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1811     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1812     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1813     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1814   }
1815
1816   // fold (mul c1, c2) -> c1*c2
1817   if (N0IsConst && N1IsConst)
1818     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1819
1820   // canonicalize constant to RHS
1821   if (N0IsConst && !N1IsConst)
1822     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1823   // fold (mul x, 0) -> 0
1824   if (N1IsConst && ConstValue1 == 0)
1825     return N1;
1826   // fold (mul x, 1) -> x
1827   if (N1IsConst && ConstValue1 == 1)
1828     return N0;
1829   // fold (mul x, -1) -> 0-x
1830   if (N1IsConst && ConstValue1.isAllOnesValue())
1831     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1832                        DAG.getConstant(0, VT), N0);
1833   // fold (mul x, (1 << c)) -> x << c
1834   if (N1IsConst && ConstValue1.isPowerOf2())
1835     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1836                        DAG.getConstant(ConstValue1.logBase2(),
1837                                        getShiftAmountTy(N0.getValueType())));
1838   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1839   if (N1IsConst && (-ConstValue1).isPowerOf2()) {
1840     unsigned Log2Val = (-ConstValue1).logBase2();
1841     // FIXME: If the input is something that is easily negated (e.g. a
1842     // single-use add), we should put the negate there.
1843     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1844                        DAG.getConstant(0, VT),
1845                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1846                             DAG.getConstant(Log2Val,
1847                                       getShiftAmountTy(N0.getValueType()))));
1848   }
1849
1850   APInt Val;
1851   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1852   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1853       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1854                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1855     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1856                              N1, N0.getOperand(1));
1857     AddToWorkList(C3.getNode());
1858     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1859                        N0.getOperand(0), C3);
1860   }
1861
1862   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1863   // use.
1864   {
1865     SDValue Sh(0,0), Y(0,0);
1866     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1867     if (N0.getOpcode() == ISD::SHL &&
1868         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1869                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1870         N0.getNode()->hasOneUse()) {
1871       Sh = N0; Y = N1;
1872     } else if (N1.getOpcode() == ISD::SHL &&
1873                isa<ConstantSDNode>(N1.getOperand(1)) &&
1874                N1.getNode()->hasOneUse()) {
1875       Sh = N1; Y = N0;
1876     }
1877
1878     if (Sh.getNode()) {
1879       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1880                                 Sh.getOperand(0), Y);
1881       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1882                          Mul, Sh.getOperand(1));
1883     }
1884   }
1885
1886   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1887   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1888       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1889                      isa<ConstantSDNode>(N0.getOperand(1))))
1890     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1891                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1892                                    N0.getOperand(0), N1),
1893                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1894                                    N0.getOperand(1), N1));
1895
1896   // reassociate mul
1897   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1898   if (RMUL.getNode() != 0)
1899     return RMUL;
1900
1901   return SDValue();
1902 }
1903
1904 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1905   SDValue N0 = N->getOperand(0);
1906   SDValue N1 = N->getOperand(1);
1907   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1908   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1909   EVT VT = N->getValueType(0);
1910
1911   // fold vector ops
1912   if (VT.isVector()) {
1913     SDValue FoldedVOp = SimplifyVBinOp(N);
1914     if (FoldedVOp.getNode()) return FoldedVOp;
1915   }
1916
1917   // fold (sdiv c1, c2) -> c1/c2
1918   if (N0C && N1C && !N1C->isNullValue())
1919     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1920   // fold (sdiv X, 1) -> X
1921   if (N1C && N1C->getAPIntValue() == 1LL)
1922     return N0;
1923   // fold (sdiv X, -1) -> 0-X
1924   if (N1C && N1C->isAllOnesValue())
1925     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1926                        DAG.getConstant(0, VT), N0);
1927   // If we know the sign bits of both operands are zero, strength reduce to a
1928   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1929   if (!VT.isVector()) {
1930     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1931       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1932                          N0, N1);
1933   }
1934   // fold (sdiv X, pow2) -> simple ops after legalize
1935   if (N1C && !N1C->isNullValue() &&
1936       (N1C->getAPIntValue().isPowerOf2() ||
1937        (-N1C->getAPIntValue()).isPowerOf2())) {
1938     // If dividing by powers of two is cheap, then don't perform the following
1939     // fold.
1940     if (TLI.isPow2DivCheap())
1941       return SDValue();
1942
1943     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1944
1945     // Splat the sign bit into the register
1946     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1947                               DAG.getConstant(VT.getSizeInBits()-1,
1948                                        getShiftAmountTy(N0.getValueType())));
1949     AddToWorkList(SGN.getNode());
1950
1951     // Add (N0 < 0) ? abs2 - 1 : 0;
1952     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1953                               DAG.getConstant(VT.getSizeInBits() - lg2,
1954                                        getShiftAmountTy(SGN.getValueType())));
1955     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1956     AddToWorkList(SRL.getNode());
1957     AddToWorkList(ADD.getNode());    // Divide by pow2
1958     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1959                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1960
1961     // If we're dividing by a positive value, we're done.  Otherwise, we must
1962     // negate the result.
1963     if (N1C->getAPIntValue().isNonNegative())
1964       return SRA;
1965
1966     AddToWorkList(SRA.getNode());
1967     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1968                        DAG.getConstant(0, VT), SRA);
1969   }
1970
1971   // if integer divide is expensive and we satisfy the requirements, emit an
1972   // alternate sequence.
1973   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1974     SDValue Op = BuildSDIV(N);
1975     if (Op.getNode()) return Op;
1976   }
1977
1978   // undef / X -> 0
1979   if (N0.getOpcode() == ISD::UNDEF)
1980     return DAG.getConstant(0, VT);
1981   // X / undef -> undef
1982   if (N1.getOpcode() == ISD::UNDEF)
1983     return N1;
1984
1985   return SDValue();
1986 }
1987
1988 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1989   SDValue N0 = N->getOperand(0);
1990   SDValue N1 = N->getOperand(1);
1991   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1992   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1993   EVT VT = N->getValueType(0);
1994
1995   // fold vector ops
1996   if (VT.isVector()) {
1997     SDValue FoldedVOp = SimplifyVBinOp(N);
1998     if (FoldedVOp.getNode()) return FoldedVOp;
1999   }
2000
2001   // fold (udiv c1, c2) -> c1/c2
2002   if (N0C && N1C && !N1C->isNullValue())
2003     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2004   // fold (udiv x, (1 << c)) -> x >>u c
2005   if (N1C && N1C->getAPIntValue().isPowerOf2())
2006     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2007                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2008                                        getShiftAmountTy(N0.getValueType())));
2009   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2010   if (N1.getOpcode() == ISD::SHL) {
2011     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2012       if (SHC->getAPIntValue().isPowerOf2()) {
2013         EVT ADDVT = N1.getOperand(1).getValueType();
2014         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2015                                   N1.getOperand(1),
2016                                   DAG.getConstant(SHC->getAPIntValue()
2017                                                                   .logBase2(),
2018                                                   ADDVT));
2019         AddToWorkList(Add.getNode());
2020         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2021       }
2022     }
2023   }
2024   // fold (udiv x, c) -> alternate
2025   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2026     SDValue Op = BuildUDIV(N);
2027     if (Op.getNode()) return Op;
2028   }
2029
2030   // undef / X -> 0
2031   if (N0.getOpcode() == ISD::UNDEF)
2032     return DAG.getConstant(0, VT);
2033   // X / undef -> undef
2034   if (N1.getOpcode() == ISD::UNDEF)
2035     return N1;
2036
2037   return SDValue();
2038 }
2039
2040 SDValue DAGCombiner::visitSREM(SDNode *N) {
2041   SDValue N0 = N->getOperand(0);
2042   SDValue N1 = N->getOperand(1);
2043   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2044   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2045   EVT VT = N->getValueType(0);
2046
2047   // fold (srem c1, c2) -> c1%c2
2048   if (N0C && N1C && !N1C->isNullValue())
2049     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2050   // If we know the sign bits of both operands are zero, strength reduce to a
2051   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2052   if (!VT.isVector()) {
2053     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2054       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2055   }
2056
2057   // If X/C can be simplified by the division-by-constant logic, lower
2058   // X%C to the equivalent of X-X/C*C.
2059   if (N1C && !N1C->isNullValue()) {
2060     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2061     AddToWorkList(Div.getNode());
2062     SDValue OptimizedDiv = combine(Div.getNode());
2063     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2064       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2065                                 OptimizedDiv, N1);
2066       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2067       AddToWorkList(Mul.getNode());
2068       return Sub;
2069     }
2070   }
2071
2072   // undef % X -> 0
2073   if (N0.getOpcode() == ISD::UNDEF)
2074     return DAG.getConstant(0, VT);
2075   // X % undef -> undef
2076   if (N1.getOpcode() == ISD::UNDEF)
2077     return N1;
2078
2079   return SDValue();
2080 }
2081
2082 SDValue DAGCombiner::visitUREM(SDNode *N) {
2083   SDValue N0 = N->getOperand(0);
2084   SDValue N1 = N->getOperand(1);
2085   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2086   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2087   EVT VT = N->getValueType(0);
2088
2089   // fold (urem c1, c2) -> c1%c2
2090   if (N0C && N1C && !N1C->isNullValue())
2091     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2092   // fold (urem x, pow2) -> (and x, pow2-1)
2093   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2094     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2095                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2096   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2097   if (N1.getOpcode() == ISD::SHL) {
2098     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2099       if (SHC->getAPIntValue().isPowerOf2()) {
2100         SDValue Add =
2101           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2102                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2103                                  VT));
2104         AddToWorkList(Add.getNode());
2105         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2106       }
2107     }
2108   }
2109
2110   // If X/C can be simplified by the division-by-constant logic, lower
2111   // X%C to the equivalent of X-X/C*C.
2112   if (N1C && !N1C->isNullValue()) {
2113     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2114     AddToWorkList(Div.getNode());
2115     SDValue OptimizedDiv = combine(Div.getNode());
2116     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2117       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2118                                 OptimizedDiv, N1);
2119       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2120       AddToWorkList(Mul.getNode());
2121       return Sub;
2122     }
2123   }
2124
2125   // undef % X -> 0
2126   if (N0.getOpcode() == ISD::UNDEF)
2127     return DAG.getConstant(0, VT);
2128   // X % undef -> undef
2129   if (N1.getOpcode() == ISD::UNDEF)
2130     return N1;
2131
2132   return SDValue();
2133 }
2134
2135 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2136   SDValue N0 = N->getOperand(0);
2137   SDValue N1 = N->getOperand(1);
2138   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2139   EVT VT = N->getValueType(0);
2140   SDLoc DL(N);
2141
2142   // fold (mulhs x, 0) -> 0
2143   if (N1C && N1C->isNullValue())
2144     return N1;
2145   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2146   if (N1C && N1C->getAPIntValue() == 1)
2147     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2148                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2149                                        getShiftAmountTy(N0.getValueType())));
2150   // fold (mulhs x, undef) -> 0
2151   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2152     return DAG.getConstant(0, VT);
2153
2154   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2155   // plus a shift.
2156   if (VT.isSimple() && !VT.isVector()) {
2157     MVT Simple = VT.getSimpleVT();
2158     unsigned SimpleSize = Simple.getSizeInBits();
2159     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2160     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2161       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2162       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2163       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2164       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2165             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2166       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2167     }
2168   }
2169
2170   return SDValue();
2171 }
2172
2173 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2174   SDValue N0 = N->getOperand(0);
2175   SDValue N1 = N->getOperand(1);
2176   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2177   EVT VT = N->getValueType(0);
2178   SDLoc DL(N);
2179
2180   // fold (mulhu x, 0) -> 0
2181   if (N1C && N1C->isNullValue())
2182     return N1;
2183   // fold (mulhu x, 1) -> 0
2184   if (N1C && N1C->getAPIntValue() == 1)
2185     return DAG.getConstant(0, N0.getValueType());
2186   // fold (mulhu x, undef) -> 0
2187   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2188     return DAG.getConstant(0, VT);
2189
2190   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2191   // plus a shift.
2192   if (VT.isSimple() && !VT.isVector()) {
2193     MVT Simple = VT.getSimpleVT();
2194     unsigned SimpleSize = Simple.getSizeInBits();
2195     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2196     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2197       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2198       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2199       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2200       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2201             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2202       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2203     }
2204   }
2205
2206   return SDValue();
2207 }
2208
2209 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2210 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2211 /// that are being performed. Return true if a simplification was made.
2212 ///
2213 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2214                                                 unsigned HiOp) {
2215   // If the high half is not needed, just compute the low half.
2216   bool HiExists = N->hasAnyUseOfValue(1);
2217   if (!HiExists &&
2218       (!LegalOperations ||
2219        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2220     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2221                               N->op_begin(), N->getNumOperands());
2222     return CombineTo(N, Res, Res);
2223   }
2224
2225   // If the low half is not needed, just compute the high half.
2226   bool LoExists = N->hasAnyUseOfValue(0);
2227   if (!LoExists &&
2228       (!LegalOperations ||
2229        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2230     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2231                               N->op_begin(), N->getNumOperands());
2232     return CombineTo(N, Res, Res);
2233   }
2234
2235   // If both halves are used, return as it is.
2236   if (LoExists && HiExists)
2237     return SDValue();
2238
2239   // If the two computed results can be simplified separately, separate them.
2240   if (LoExists) {
2241     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2242                              N->op_begin(), N->getNumOperands());
2243     AddToWorkList(Lo.getNode());
2244     SDValue LoOpt = combine(Lo.getNode());
2245     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2246         (!LegalOperations ||
2247          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2248       return CombineTo(N, LoOpt, LoOpt);
2249   }
2250
2251   if (HiExists) {
2252     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2253                              N->op_begin(), N->getNumOperands());
2254     AddToWorkList(Hi.getNode());
2255     SDValue HiOpt = combine(Hi.getNode());
2256     if (HiOpt.getNode() && HiOpt != Hi &&
2257         (!LegalOperations ||
2258          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2259       return CombineTo(N, HiOpt, HiOpt);
2260   }
2261
2262   return SDValue();
2263 }
2264
2265 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2266   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2267   if (Res.getNode()) return Res;
2268
2269   EVT VT = N->getValueType(0);
2270   SDLoc DL(N);
2271
2272   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2273   // plus a shift.
2274   if (VT.isSimple() && !VT.isVector()) {
2275     MVT Simple = VT.getSimpleVT();
2276     unsigned SimpleSize = Simple.getSizeInBits();
2277     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2278     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2279       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2280       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2281       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2282       // Compute the high part as N1.
2283       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2284             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2285       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2286       // Compute the low part as N0.
2287       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2288       return CombineTo(N, Lo, Hi);
2289     }
2290   }
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2296   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2297   if (Res.getNode()) return Res;
2298
2299   EVT VT = N->getValueType(0);
2300   SDLoc DL(N);
2301
2302   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2303   // plus a shift.
2304   if (VT.isSimple() && !VT.isVector()) {
2305     MVT Simple = VT.getSimpleVT();
2306     unsigned SimpleSize = Simple.getSizeInBits();
2307     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2308     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2309       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2310       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2311       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2312       // Compute the high part as N1.
2313       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2314             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2315       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2316       // Compute the low part as N0.
2317       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2318       return CombineTo(N, Lo, Hi);
2319     }
2320   }
2321
2322   return SDValue();
2323 }
2324
2325 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2326   // (smulo x, 2) -> (saddo x, x)
2327   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2328     if (C2->getAPIntValue() == 2)
2329       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2330                          N->getOperand(0), N->getOperand(0));
2331
2332   return SDValue();
2333 }
2334
2335 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2336   // (umulo x, 2) -> (uaddo x, x)
2337   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2338     if (C2->getAPIntValue() == 2)
2339       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2340                          N->getOperand(0), N->getOperand(0));
2341
2342   return SDValue();
2343 }
2344
2345 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2346   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2347   if (Res.getNode()) return Res;
2348
2349   return SDValue();
2350 }
2351
2352 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2353   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2354   if (Res.getNode()) return Res;
2355
2356   return SDValue();
2357 }
2358
2359 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2360 /// two operands of the same opcode, try to simplify it.
2361 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2362   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2363   EVT VT = N0.getValueType();
2364   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2365
2366   // Bail early if none of these transforms apply.
2367   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2368
2369   // For each of OP in AND/OR/XOR:
2370   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2371   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2372   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2373   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2374   //
2375   // do not sink logical op inside of a vector extend, since it may combine
2376   // into a vsetcc.
2377   EVT Op0VT = N0.getOperand(0).getValueType();
2378   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2379        N0.getOpcode() == ISD::SIGN_EXTEND ||
2380        // Avoid infinite looping with PromoteIntBinOp.
2381        (N0.getOpcode() == ISD::ANY_EXTEND &&
2382         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2383        (N0.getOpcode() == ISD::TRUNCATE &&
2384         (!TLI.isZExtFree(VT, Op0VT) ||
2385          !TLI.isTruncateFree(Op0VT, VT)) &&
2386         TLI.isTypeLegal(Op0VT))) &&
2387       !VT.isVector() &&
2388       Op0VT == N1.getOperand(0).getValueType() &&
2389       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2390     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2391                                  N0.getOperand(0).getValueType(),
2392                                  N0.getOperand(0), N1.getOperand(0));
2393     AddToWorkList(ORNode.getNode());
2394     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2395   }
2396
2397   // For each of OP in SHL/SRL/SRA/AND...
2398   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2399   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2400   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2401   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2402        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2403       N0.getOperand(1) == N1.getOperand(1)) {
2404     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2405                                  N0.getOperand(0).getValueType(),
2406                                  N0.getOperand(0), N1.getOperand(0));
2407     AddToWorkList(ORNode.getNode());
2408     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2409                        ORNode, N0.getOperand(1));
2410   }
2411
2412   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2413   // Only perform this optimization after type legalization and before
2414   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2415   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2416   // we don't want to undo this promotion.
2417   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2418   // on scalars.
2419   if ((N0.getOpcode() == ISD::BITCAST ||
2420        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2421       Level == AfterLegalizeTypes) {
2422     SDValue In0 = N0.getOperand(0);
2423     SDValue In1 = N1.getOperand(0);
2424     EVT In0Ty = In0.getValueType();
2425     EVT In1Ty = In1.getValueType();
2426     SDLoc DL(N);
2427     // If both incoming values are integers, and the original types are the
2428     // same.
2429     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2430       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2431       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2432       AddToWorkList(Op.getNode());
2433       return BC;
2434     }
2435   }
2436
2437   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2438   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2439   // If both shuffles use the same mask, and both shuffle within a single
2440   // vector, then it is worthwhile to move the swizzle after the operation.
2441   // The type-legalizer generates this pattern when loading illegal
2442   // vector types from memory. In many cases this allows additional shuffle
2443   // optimizations.
2444   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2445       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2446       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2447     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2448     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2449
2450     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2451            "Inputs to shuffles are not the same type");
2452
2453     unsigned NumElts = VT.getVectorNumElements();
2454
2455     // Check that both shuffles use the same mask. The masks are known to be of
2456     // the same length because the result vector type is the same.
2457     bool SameMask = true;
2458     for (unsigned i = 0; i != NumElts; ++i) {
2459       int Idx0 = SVN0->getMaskElt(i);
2460       int Idx1 = SVN1->getMaskElt(i);
2461       if (Idx0 != Idx1) {
2462         SameMask = false;
2463         break;
2464       }
2465     }
2466
2467     if (SameMask) {
2468       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2469                                N0.getOperand(0), N1.getOperand(0));
2470       AddToWorkList(Op.getNode());
2471       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2472                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2473     }
2474   }
2475
2476   return SDValue();
2477 }
2478
2479 SDValue DAGCombiner::visitAND(SDNode *N) {
2480   SDValue N0 = N->getOperand(0);
2481   SDValue N1 = N->getOperand(1);
2482   SDValue LL, LR, RL, RR, CC0, CC1;
2483   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2484   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2485   EVT VT = N1.getValueType();
2486   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2487
2488   // fold vector ops
2489   if (VT.isVector()) {
2490     SDValue FoldedVOp = SimplifyVBinOp(N);
2491     if (FoldedVOp.getNode()) return FoldedVOp;
2492
2493     // fold (and x, 0) -> 0, vector edition
2494     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2495       return N0;
2496     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2497       return N1;
2498
2499     // fold (and x, -1) -> x, vector edition
2500     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2501       return N1;
2502     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2503       return N0;
2504   }
2505
2506   // fold (and x, undef) -> 0
2507   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2508     return DAG.getConstant(0, VT);
2509   // fold (and c1, c2) -> c1&c2
2510   if (N0C && N1C)
2511     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2512   // canonicalize constant to RHS
2513   if (N0C && !N1C)
2514     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2515   // fold (and x, -1) -> x
2516   if (N1C && N1C->isAllOnesValue())
2517     return N0;
2518   // if (and x, c) is known to be zero, return 0
2519   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2520                                    APInt::getAllOnesValue(BitWidth)))
2521     return DAG.getConstant(0, VT);
2522   // reassociate and
2523   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2524   if (RAND.getNode() != 0)
2525     return RAND;
2526   // fold (and (or x, C), D) -> D if (C & D) == D
2527   if (N1C && N0.getOpcode() == ISD::OR)
2528     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2529       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2530         return N1;
2531   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2532   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2533     SDValue N0Op0 = N0.getOperand(0);
2534     APInt Mask = ~N1C->getAPIntValue();
2535     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2536     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2537       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2538                                  N0.getValueType(), N0Op0);
2539
2540       // Replace uses of the AND with uses of the Zero extend node.
2541       CombineTo(N, Zext);
2542
2543       // We actually want to replace all uses of the any_extend with the
2544       // zero_extend, to avoid duplicating things.  This will later cause this
2545       // AND to be folded.
2546       CombineTo(N0.getNode(), Zext);
2547       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2548     }
2549   }
2550   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2551   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2552   // already be zero by virtue of the width of the base type of the load.
2553   //
2554   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2555   // more cases.
2556   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2557        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2558       N0.getOpcode() == ISD::LOAD) {
2559     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2560                                          N0 : N0.getOperand(0) );
2561
2562     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2563     // This can be a pure constant or a vector splat, in which case we treat the
2564     // vector as a scalar and use the splat value.
2565     APInt Constant = APInt::getNullValue(1);
2566     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2567       Constant = C->getAPIntValue();
2568     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2569       APInt SplatValue, SplatUndef;
2570       unsigned SplatBitSize;
2571       bool HasAnyUndefs;
2572       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2573                                              SplatBitSize, HasAnyUndefs);
2574       if (IsSplat) {
2575         // Undef bits can contribute to a possible optimisation if set, so
2576         // set them.
2577         SplatValue |= SplatUndef;
2578
2579         // The splat value may be something like "0x00FFFFFF", which means 0 for
2580         // the first vector value and FF for the rest, repeating. We need a mask
2581         // that will apply equally to all members of the vector, so AND all the
2582         // lanes of the constant together.
2583         EVT VT = Vector->getValueType(0);
2584         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2585
2586         // If the splat value has been compressed to a bitlength lower
2587         // than the size of the vector lane, we need to re-expand it to
2588         // the lane size.
2589         if (BitWidth > SplatBitSize)
2590           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2591                SplatBitSize < BitWidth;
2592                SplatBitSize = SplatBitSize * 2)
2593             SplatValue |= SplatValue.shl(SplatBitSize);
2594
2595         Constant = APInt::getAllOnesValue(BitWidth);
2596         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2597           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2598       }
2599     }
2600
2601     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2602     // actually legal and isn't going to get expanded, else this is a false
2603     // optimisation.
2604     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2605                                                     Load->getMemoryVT());
2606
2607     // Resize the constant to the same size as the original memory access before
2608     // extension. If it is still the AllOnesValue then this AND is completely
2609     // unneeded.
2610     Constant =
2611       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2612
2613     bool B;
2614     switch (Load->getExtensionType()) {
2615     default: B = false; break;
2616     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2617     case ISD::ZEXTLOAD:
2618     case ISD::NON_EXTLOAD: B = true; break;
2619     }
2620
2621     if (B && Constant.isAllOnesValue()) {
2622       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2623       // preserve semantics once we get rid of the AND.
2624       SDValue NewLoad(Load, 0);
2625       if (Load->getExtensionType() == ISD::EXTLOAD) {
2626         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2627                               Load->getValueType(0), SDLoc(Load),
2628                               Load->getChain(), Load->getBasePtr(),
2629                               Load->getOffset(), Load->getMemoryVT(),
2630                               Load->getMemOperand());
2631         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2632         if (Load->getNumValues() == 3) {
2633           // PRE/POST_INC loads have 3 values.
2634           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2635                            NewLoad.getValue(2) };
2636           CombineTo(Load, To, 3, true);
2637         } else {
2638           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2639         }
2640       }
2641
2642       // Fold the AND away, taking care not to fold to the old load node if we
2643       // replaced it.
2644       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2645
2646       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2647     }
2648   }
2649   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2650   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2651     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2652     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2653
2654     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2655         LL.getValueType().isInteger()) {
2656       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2657       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2658         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2659                                      LR.getValueType(), LL, RL);
2660         AddToWorkList(ORNode.getNode());
2661         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2662       }
2663       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2664       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2665         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2666                                       LR.getValueType(), LL, RL);
2667         AddToWorkList(ANDNode.getNode());
2668         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2669       }
2670       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2671       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2672         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2673                                      LR.getValueType(), LL, RL);
2674         AddToWorkList(ORNode.getNode());
2675         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2676       }
2677     }
2678     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2679     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2680         Op0 == Op1 && LL.getValueType().isInteger() &&
2681       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2682                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2683                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2684                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2685       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2686                                     LL, DAG.getConstant(1, LL.getValueType()));
2687       AddToWorkList(ADDNode.getNode());
2688       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2689                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2690     }
2691     // canonicalize equivalent to ll == rl
2692     if (LL == RR && LR == RL) {
2693       Op1 = ISD::getSetCCSwappedOperands(Op1);
2694       std::swap(RL, RR);
2695     }
2696     if (LL == RL && LR == RR) {
2697       bool isInteger = LL.getValueType().isInteger();
2698       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2699       if (Result != ISD::SETCC_INVALID &&
2700           (!LegalOperations ||
2701            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2702             TLI.isOperationLegal(ISD::SETCC,
2703                             getSetCCResultType(N0.getSimpleValueType())))))
2704         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2705                             LL, LR, Result);
2706     }
2707   }
2708
2709   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2710   if (N0.getOpcode() == N1.getOpcode()) {
2711     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2712     if (Tmp.getNode()) return Tmp;
2713   }
2714
2715   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2716   // fold (and (sra)) -> (and (srl)) when possible.
2717   if (!VT.isVector() &&
2718       SimplifyDemandedBits(SDValue(N, 0)))
2719     return SDValue(N, 0);
2720
2721   // fold (zext_inreg (extload x)) -> (zextload x)
2722   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2723     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2724     EVT MemVT = LN0->getMemoryVT();
2725     // If we zero all the possible extended bits, then we can turn this into
2726     // a zextload if we are running before legalize or the operation is legal.
2727     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2728     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2729                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2730         ((!LegalOperations && !LN0->isVolatile()) ||
2731          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2732       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2733                                        LN0->getChain(), LN0->getBasePtr(),
2734                                        LN0->getPointerInfo(), MemVT,
2735                                        LN0->isVolatile(), LN0->isNonTemporal(),
2736                                        LN0->getAlignment());
2737       AddToWorkList(N);
2738       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2739       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2740     }
2741   }
2742   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2743   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2744       N0.hasOneUse()) {
2745     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2746     EVT MemVT = LN0->getMemoryVT();
2747     // If we zero all the possible extended bits, then we can turn this into
2748     // a zextload if we are running before legalize or the operation is legal.
2749     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2750     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2751                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2752         ((!LegalOperations && !LN0->isVolatile()) ||
2753          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2754       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2755                                        LN0->getChain(),
2756                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2757                                        MemVT,
2758                                        LN0->isVolatile(), LN0->isNonTemporal(),
2759                                        LN0->getAlignment());
2760       AddToWorkList(N);
2761       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2762       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2763     }
2764   }
2765
2766   // fold (and (load x), 255) -> (zextload x, i8)
2767   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2768   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2769   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2770               (N0.getOpcode() == ISD::ANY_EXTEND &&
2771                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2772     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2773     LoadSDNode *LN0 = HasAnyExt
2774       ? cast<LoadSDNode>(N0.getOperand(0))
2775       : cast<LoadSDNode>(N0);
2776     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2777         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2778       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2779       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2780         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2781         EVT LoadedVT = LN0->getMemoryVT();
2782
2783         if (ExtVT == LoadedVT &&
2784             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2785           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2786
2787           SDValue NewLoad =
2788             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2789                            LN0->getChain(), LN0->getBasePtr(),
2790                            LN0->getPointerInfo(),
2791                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2792                            LN0->getAlignment());
2793           AddToWorkList(N);
2794           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2795           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2796         }
2797
2798         // Do not change the width of a volatile load.
2799         // Do not generate loads of non-round integer types since these can
2800         // be expensive (and would be wrong if the type is not byte sized).
2801         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2802             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2803           EVT PtrType = LN0->getOperand(1).getValueType();
2804
2805           unsigned Alignment = LN0->getAlignment();
2806           SDValue NewPtr = LN0->getBasePtr();
2807
2808           // For big endian targets, we need to add an offset to the pointer
2809           // to load the correct bytes.  For little endian systems, we merely
2810           // need to read fewer bytes from the same pointer.
2811           if (TLI.isBigEndian()) {
2812             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2813             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2814             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2815             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2816                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2817             Alignment = MinAlign(Alignment, PtrOff);
2818           }
2819
2820           AddToWorkList(NewPtr.getNode());
2821
2822           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2823           SDValue Load =
2824             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2825                            LN0->getChain(), NewPtr,
2826                            LN0->getPointerInfo(),
2827                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2828                            Alignment);
2829           AddToWorkList(N);
2830           CombineTo(LN0, Load, Load.getValue(1));
2831           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2832         }
2833       }
2834     }
2835   }
2836
2837   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2838       VT.getSizeInBits() <= 64) {
2839     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2840       APInt ADDC = ADDI->getAPIntValue();
2841       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2842         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2843         // immediate for an add, but it is legal if its top c2 bits are set,
2844         // transform the ADD so the immediate doesn't need to be materialized
2845         // in a register.
2846         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2847           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2848                                              SRLI->getZExtValue());
2849           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2850             ADDC |= Mask;
2851             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2852               SDValue NewAdd =
2853                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2854                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2855               CombineTo(N0.getNode(), NewAdd);
2856               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2857             }
2858           }
2859         }
2860       }
2861     }
2862   }
2863
2864   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2865   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2866     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2867                                        N0.getOperand(1), false);
2868     if (BSwap.getNode())
2869       return BSwap;
2870   }
2871
2872   return SDValue();
2873 }
2874
2875 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2876 ///
2877 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2878                                         bool DemandHighBits) {
2879   if (!LegalOperations)
2880     return SDValue();
2881
2882   EVT VT = N->getValueType(0);
2883   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2884     return SDValue();
2885   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2886     return SDValue();
2887
2888   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2889   bool LookPassAnd0 = false;
2890   bool LookPassAnd1 = false;
2891   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2892       std::swap(N0, N1);
2893   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2894       std::swap(N0, N1);
2895   if (N0.getOpcode() == ISD::AND) {
2896     if (!N0.getNode()->hasOneUse())
2897       return SDValue();
2898     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2899     if (!N01C || N01C->getZExtValue() != 0xFF00)
2900       return SDValue();
2901     N0 = N0.getOperand(0);
2902     LookPassAnd0 = true;
2903   }
2904
2905   if (N1.getOpcode() == ISD::AND) {
2906     if (!N1.getNode()->hasOneUse())
2907       return SDValue();
2908     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2909     if (!N11C || N11C->getZExtValue() != 0xFF)
2910       return SDValue();
2911     N1 = N1.getOperand(0);
2912     LookPassAnd1 = true;
2913   }
2914
2915   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2916     std::swap(N0, N1);
2917   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2918     return SDValue();
2919   if (!N0.getNode()->hasOneUse() ||
2920       !N1.getNode()->hasOneUse())
2921     return SDValue();
2922
2923   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2924   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2925   if (!N01C || !N11C)
2926     return SDValue();
2927   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2928     return SDValue();
2929
2930   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2931   SDValue N00 = N0->getOperand(0);
2932   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2933     if (!N00.getNode()->hasOneUse())
2934       return SDValue();
2935     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2936     if (!N001C || N001C->getZExtValue() != 0xFF)
2937       return SDValue();
2938     N00 = N00.getOperand(0);
2939     LookPassAnd0 = true;
2940   }
2941
2942   SDValue N10 = N1->getOperand(0);
2943   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2944     if (!N10.getNode()->hasOneUse())
2945       return SDValue();
2946     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2947     if (!N101C || N101C->getZExtValue() != 0xFF00)
2948       return SDValue();
2949     N10 = N10.getOperand(0);
2950     LookPassAnd1 = true;
2951   }
2952
2953   if (N00 != N10)
2954     return SDValue();
2955
2956   // Make sure everything beyond the low halfword gets set to zero since the SRL
2957   // 16 will clear the top bits.
2958   unsigned OpSizeInBits = VT.getSizeInBits();
2959   if (DemandHighBits && OpSizeInBits > 16) {
2960     // If the left-shift isn't masked out then the only way this is a bswap is
2961     // if all bits beyond the low 8 are 0. In that case the entire pattern
2962     // reduces to a left shift anyway: leave it for other parts of the combiner.
2963     if (!LookPassAnd0)
2964       return SDValue();
2965
2966     // However, if the right shift isn't masked out then it might be because
2967     // it's not needed. See if we can spot that too.
2968     if (!LookPassAnd1 &&
2969         !DAG.MaskedValueIsZero(
2970             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2971       return SDValue();
2972   }
2973
2974   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2975   if (OpSizeInBits > 16)
2976     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2977                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2978   return Res;
2979 }
2980
2981 /// isBSwapHWordElement - Return true if the specified node is an element
2982 /// that makes up a 32-bit packed halfword byteswap. i.e.
2983 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2984 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2985   if (!N.getNode()->hasOneUse())
2986     return false;
2987
2988   unsigned Opc = N.getOpcode();
2989   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2990     return false;
2991
2992   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2993   if (!N1C)
2994     return false;
2995
2996   unsigned Num;
2997   switch (N1C->getZExtValue()) {
2998   default:
2999     return false;
3000   case 0xFF:       Num = 0; break;
3001   case 0xFF00:     Num = 1; break;
3002   case 0xFF0000:   Num = 2; break;
3003   case 0xFF000000: Num = 3; break;
3004   }
3005
3006   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3007   SDValue N0 = N.getOperand(0);
3008   if (Opc == ISD::AND) {
3009     if (Num == 0 || Num == 2) {
3010       // (x >> 8) & 0xff
3011       // (x >> 8) & 0xff0000
3012       if (N0.getOpcode() != ISD::SRL)
3013         return false;
3014       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3015       if (!C || C->getZExtValue() != 8)
3016         return false;
3017     } else {
3018       // (x << 8) & 0xff00
3019       // (x << 8) & 0xff000000
3020       if (N0.getOpcode() != ISD::SHL)
3021         return false;
3022       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023       if (!C || C->getZExtValue() != 8)
3024         return false;
3025     }
3026   } else if (Opc == ISD::SHL) {
3027     // (x & 0xff) << 8
3028     // (x & 0xff0000) << 8
3029     if (Num != 0 && Num != 2)
3030       return false;
3031     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3032     if (!C || C->getZExtValue() != 8)
3033       return false;
3034   } else { // Opc == ISD::SRL
3035     // (x & 0xff00) >> 8
3036     // (x & 0xff000000) >> 8
3037     if (Num != 1 && Num != 3)
3038       return false;
3039     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3040     if (!C || C->getZExtValue() != 8)
3041       return false;
3042   }
3043
3044   if (Parts[Num])
3045     return false;
3046
3047   Parts[Num] = N0.getOperand(0).getNode();
3048   return true;
3049 }
3050
3051 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3052 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3053 /// => (rotl (bswap x), 16)
3054 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3055   if (!LegalOperations)
3056     return SDValue();
3057
3058   EVT VT = N->getValueType(0);
3059   if (VT != MVT::i32)
3060     return SDValue();
3061   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3062     return SDValue();
3063
3064   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3065   // Look for either
3066   // (or (or (and), (and)), (or (and), (and)))
3067   // (or (or (or (and), (and)), (and)), (and))
3068   if (N0.getOpcode() != ISD::OR)
3069     return SDValue();
3070   SDValue N00 = N0.getOperand(0);
3071   SDValue N01 = N0.getOperand(1);
3072
3073   if (N1.getOpcode() == ISD::OR &&
3074       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3075     // (or (or (and), (and)), (or (and), (and)))
3076     SDValue N000 = N00.getOperand(0);
3077     if (!isBSwapHWordElement(N000, Parts))
3078       return SDValue();
3079
3080     SDValue N001 = N00.getOperand(1);
3081     if (!isBSwapHWordElement(N001, Parts))
3082       return SDValue();
3083     SDValue N010 = N01.getOperand(0);
3084     if (!isBSwapHWordElement(N010, Parts))
3085       return SDValue();
3086     SDValue N011 = N01.getOperand(1);
3087     if (!isBSwapHWordElement(N011, Parts))
3088       return SDValue();
3089   } else {
3090     // (or (or (or (and), (and)), (and)), (and))
3091     if (!isBSwapHWordElement(N1, Parts))
3092       return SDValue();
3093     if (!isBSwapHWordElement(N01, Parts))
3094       return SDValue();
3095     if (N00.getOpcode() != ISD::OR)
3096       return SDValue();
3097     SDValue N000 = N00.getOperand(0);
3098     if (!isBSwapHWordElement(N000, Parts))
3099       return SDValue();
3100     SDValue N001 = N00.getOperand(1);
3101     if (!isBSwapHWordElement(N001, Parts))
3102       return SDValue();
3103   }
3104
3105   // Make sure the parts are all coming from the same node.
3106   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3107     return SDValue();
3108
3109   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3110                               SDValue(Parts[0],0));
3111
3112   // Result of the bswap should be rotated by 16. If it's not legal, than
3113   // do  (x << 16) | (x >> 16).
3114   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3115   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3116     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3117   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3118     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3119   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3120                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3121                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3122 }
3123
3124 SDValue DAGCombiner::visitOR(SDNode *N) {
3125   SDValue N0 = N->getOperand(0);
3126   SDValue N1 = N->getOperand(1);
3127   SDValue LL, LR, RL, RR, CC0, CC1;
3128   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3129   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3130   EVT VT = N1.getValueType();
3131
3132   // fold vector ops
3133   if (VT.isVector()) {
3134     SDValue FoldedVOp = SimplifyVBinOp(N);
3135     if (FoldedVOp.getNode()) return FoldedVOp;
3136
3137     // fold (or x, 0) -> x, vector edition
3138     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3139       return N1;
3140     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3141       return N0;
3142
3143     // fold (or x, -1) -> -1, vector edition
3144     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3145       return N0;
3146     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3147       return N1;
3148   }
3149
3150   // fold (or x, undef) -> -1
3151   if (!LegalOperations &&
3152       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3153     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3154     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3155   }
3156   // fold (or c1, c2) -> c1|c2
3157   if (N0C && N1C)
3158     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3159   // canonicalize constant to RHS
3160   if (N0C && !N1C)
3161     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3162   // fold (or x, 0) -> x
3163   if (N1C && N1C->isNullValue())
3164     return N0;
3165   // fold (or x, -1) -> -1
3166   if (N1C && N1C->isAllOnesValue())
3167     return N1;
3168   // fold (or x, c) -> c iff (x & ~c) == 0
3169   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3170     return N1;
3171
3172   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3173   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3174   if (BSwap.getNode() != 0)
3175     return BSwap;
3176   BSwap = MatchBSwapHWordLow(N, N0, N1);
3177   if (BSwap.getNode() != 0)
3178     return BSwap;
3179
3180   // reassociate or
3181   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3182   if (ROR.getNode() != 0)
3183     return ROR;
3184   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3185   // iff (c1 & c2) == 0.
3186   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3187              isa<ConstantSDNode>(N0.getOperand(1))) {
3188     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3189     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3190       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3191                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3192                                      N0.getOperand(0), N1),
3193                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3194   }
3195   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3196   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3197     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3198     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3199
3200     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3201         LL.getValueType().isInteger()) {
3202       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3203       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3204       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3205           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3206         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3207                                      LR.getValueType(), LL, RL);
3208         AddToWorkList(ORNode.getNode());
3209         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3210       }
3211       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3212       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3213       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3214           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3215         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3216                                       LR.getValueType(), LL, RL);
3217         AddToWorkList(ANDNode.getNode());
3218         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3219       }
3220     }
3221     // canonicalize equivalent to ll == rl
3222     if (LL == RR && LR == RL) {
3223       Op1 = ISD::getSetCCSwappedOperands(Op1);
3224       std::swap(RL, RR);
3225     }
3226     if (LL == RL && LR == RR) {
3227       bool isInteger = LL.getValueType().isInteger();
3228       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3229       if (Result != ISD::SETCC_INVALID &&
3230           (!LegalOperations ||
3231            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3232             TLI.isOperationLegal(ISD::SETCC,
3233               getSetCCResultType(N0.getValueType())))))
3234         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3235                             LL, LR, Result);
3236     }
3237   }
3238
3239   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3240   if (N0.getOpcode() == N1.getOpcode()) {
3241     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3242     if (Tmp.getNode()) return Tmp;
3243   }
3244
3245   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3246   if (N0.getOpcode() == ISD::AND &&
3247       N1.getOpcode() == ISD::AND &&
3248       N0.getOperand(1).getOpcode() == ISD::Constant &&
3249       N1.getOperand(1).getOpcode() == ISD::Constant &&
3250       // Don't increase # computations.
3251       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3252     // We can only do this xform if we know that bits from X that are set in C2
3253     // but not in C1 are already zero.  Likewise for Y.
3254     const APInt &LHSMask =
3255       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3256     const APInt &RHSMask =
3257       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3258
3259     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3260         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3261       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3262                               N0.getOperand(0), N1.getOperand(0));
3263       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3264                          DAG.getConstant(LHSMask | RHSMask, VT));
3265     }
3266   }
3267
3268   // See if this is some rotate idiom.
3269   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3270     return SDValue(Rot, 0);
3271
3272   // Simplify the operands using demanded-bits information.
3273   if (!VT.isVector() &&
3274       SimplifyDemandedBits(SDValue(N, 0)))
3275     return SDValue(N, 0);
3276
3277   return SDValue();
3278 }
3279
3280 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3281 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3282   if (Op.getOpcode() == ISD::AND) {
3283     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3284       Mask = Op.getOperand(1);
3285       Op = Op.getOperand(0);
3286     } else {
3287       return false;
3288     }
3289   }
3290
3291   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3292     Shift = Op;
3293     return true;
3294   }
3295
3296   return false;
3297 }
3298
3299 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3300 // idioms for rotate, and if the target supports rotation instructions, generate
3301 // a rot[lr].
3302 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3303   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3304   EVT VT = LHS.getValueType();
3305   if (!TLI.isTypeLegal(VT)) return 0;
3306
3307   // The target must have at least one rotate flavor.
3308   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3309   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3310   if (!HasROTL && !HasROTR) return 0;
3311
3312   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3313   SDValue LHSShift;   // The shift.
3314   SDValue LHSMask;    // AND value if any.
3315   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3316     return 0; // Not part of a rotate.
3317
3318   SDValue RHSShift;   // The shift.
3319   SDValue RHSMask;    // AND value if any.
3320   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3321     return 0; // Not part of a rotate.
3322
3323   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3324     return 0;   // Not shifting the same value.
3325
3326   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3327     return 0;   // Shifts must disagree.
3328
3329   // Canonicalize shl to left side in a shl/srl pair.
3330   if (RHSShift.getOpcode() == ISD::SHL) {
3331     std::swap(LHS, RHS);
3332     std::swap(LHSShift, RHSShift);
3333     std::swap(LHSMask , RHSMask );
3334   }
3335
3336   unsigned OpSizeInBits = VT.getSizeInBits();
3337   SDValue LHSShiftArg = LHSShift.getOperand(0);
3338   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3339   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3340
3341   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3342   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3343   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3344       RHSShiftAmt.getOpcode() == ISD::Constant) {
3345     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3346     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3347     if ((LShVal + RShVal) != OpSizeInBits)
3348       return 0;
3349
3350     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3351                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3352
3353     // If there is an AND of either shifted operand, apply it to the result.
3354     if (LHSMask.getNode() || RHSMask.getNode()) {
3355       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3356
3357       if (LHSMask.getNode()) {
3358         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3359         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3360       }
3361       if (RHSMask.getNode()) {
3362         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3363         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3364       }
3365
3366       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3367     }
3368
3369     return Rot.getNode();
3370   }
3371
3372   // If there is a mask here, and we have a variable shift, we can't be sure
3373   // that we're masking out the right stuff.
3374   if (LHSMask.getNode() || RHSMask.getNode())
3375     return 0;
3376
3377   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3378   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3379   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3380       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3381     if (ConstantSDNode *SUBC =
3382           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3383       if (SUBC->getAPIntValue() == OpSizeInBits)
3384         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3385                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3386     }
3387   }
3388
3389   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3390   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3391   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3392       RHSShiftAmt == LHSShiftAmt.getOperand(1))
3393     if (ConstantSDNode *SUBC =
3394           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0)))
3395       if (SUBC->getAPIntValue() == OpSizeInBits)
3396         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3397                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3398
3399   // Look for sign/zext/any-extended or truncate cases:
3400   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3401        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3402        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3403        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3404       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3405        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3406        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3407        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3408     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3409     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3410     if (RExtOp0.getOpcode() == ISD::SUB &&
3411         RExtOp0.getOperand(1) == LExtOp0) {
3412       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3413       //   (rotl x, y)
3414       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3415       //   (rotr x, (sub 32, y))
3416       if (ConstantSDNode *SUBC =
3417             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0)))
3418         if (SUBC->getAPIntValue() == OpSizeInBits)
3419           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3420                              LHSShiftArg,
3421                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3422     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3423                RExtOp0 == LExtOp0.getOperand(1)) {
3424       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3425       //   (rotr x, y)
3426       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3427       //   (rotl x, (sub 32, y))
3428       if (ConstantSDNode *SUBC =
3429             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0)))
3430         if (SUBC->getAPIntValue() == OpSizeInBits)
3431           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3432                              LHSShiftArg,
3433                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3434     }
3435   }
3436
3437   return 0;
3438 }
3439
3440 SDValue DAGCombiner::visitXOR(SDNode *N) {
3441   SDValue N0 = N->getOperand(0);
3442   SDValue N1 = N->getOperand(1);
3443   SDValue LHS, RHS, CC;
3444   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3445   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3446   EVT VT = N0.getValueType();
3447
3448   // fold vector ops
3449   if (VT.isVector()) {
3450     SDValue FoldedVOp = SimplifyVBinOp(N);
3451     if (FoldedVOp.getNode()) return FoldedVOp;
3452
3453     // fold (xor x, 0) -> x, vector edition
3454     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3455       return N1;
3456     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3457       return N0;
3458   }
3459
3460   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3461   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3462     return DAG.getConstant(0, VT);
3463   // fold (xor x, undef) -> undef
3464   if (N0.getOpcode() == ISD::UNDEF)
3465     return N0;
3466   if (N1.getOpcode() == ISD::UNDEF)
3467     return N1;
3468   // fold (xor c1, c2) -> c1^c2
3469   if (N0C && N1C)
3470     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3471   // canonicalize constant to RHS
3472   if (N0C && !N1C)
3473     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3474   // fold (xor x, 0) -> x
3475   if (N1C && N1C->isNullValue())
3476     return N0;
3477   // reassociate xor
3478   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3479   if (RXOR.getNode() != 0)
3480     return RXOR;
3481
3482   // fold !(x cc y) -> (x !cc y)
3483   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3484     bool isInt = LHS.getValueType().isInteger();
3485     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3486                                                isInt);
3487
3488     if (!LegalOperations ||
3489         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3490       switch (N0.getOpcode()) {
3491       default:
3492         llvm_unreachable("Unhandled SetCC Equivalent!");
3493       case ISD::SETCC:
3494         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3495       case ISD::SELECT_CC:
3496         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3497                                N0.getOperand(3), NotCC);
3498       }
3499     }
3500   }
3501
3502   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3503   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3504       N0.getNode()->hasOneUse() &&
3505       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3506     SDValue V = N0.getOperand(0);
3507     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3508                     DAG.getConstant(1, V.getValueType()));
3509     AddToWorkList(V.getNode());
3510     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3511   }
3512
3513   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3514   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3515       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3516     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3517     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3518       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3519       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3520       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3521       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3522       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3523     }
3524   }
3525   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3526   if (N1C && N1C->isAllOnesValue() &&
3527       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3528     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3529     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3530       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3531       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3532       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3533       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3534       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3535     }
3536   }
3537   // fold (xor (and x, y), y) -> (and (not x), y)
3538   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3539       N0->getOperand(1) == N1) {
3540     SDValue X = N0->getOperand(0);
3541     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3542     AddToWorkList(NotX.getNode());
3543     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3544   }
3545   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3546   if (N1C && N0.getOpcode() == ISD::XOR) {
3547     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3548     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3549     if (N00C)
3550       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3551                          DAG.getConstant(N1C->getAPIntValue() ^
3552                                          N00C->getAPIntValue(), VT));
3553     if (N01C)
3554       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3555                          DAG.getConstant(N1C->getAPIntValue() ^
3556                                          N01C->getAPIntValue(), VT));
3557   }
3558   // fold (xor x, x) -> 0
3559   if (N0 == N1)
3560     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3561
3562   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3563   if (N0.getOpcode() == N1.getOpcode()) {
3564     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3565     if (Tmp.getNode()) return Tmp;
3566   }
3567
3568   // Simplify the expression using non-local knowledge.
3569   if (!VT.isVector() &&
3570       SimplifyDemandedBits(SDValue(N, 0)))
3571     return SDValue(N, 0);
3572
3573   return SDValue();
3574 }
3575
3576 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3577 /// the shift amount is a constant.
3578 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3579   SDNode *LHS = N->getOperand(0).getNode();
3580   if (!LHS->hasOneUse()) return SDValue();
3581
3582   // We want to pull some binops through shifts, so that we have (and (shift))
3583   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3584   // thing happens with address calculations, so it's important to canonicalize
3585   // it.
3586   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3587
3588   switch (LHS->getOpcode()) {
3589   default: return SDValue();
3590   case ISD::OR:
3591   case ISD::XOR:
3592     HighBitSet = false; // We can only transform sra if the high bit is clear.
3593     break;
3594   case ISD::AND:
3595     HighBitSet = true;  // We can only transform sra if the high bit is set.
3596     break;
3597   case ISD::ADD:
3598     if (N->getOpcode() != ISD::SHL)
3599       return SDValue(); // only shl(add) not sr[al](add).
3600     HighBitSet = false; // We can only transform sra if the high bit is clear.
3601     break;
3602   }
3603
3604   // We require the RHS of the binop to be a constant as well.
3605   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3606   if (!BinOpCst) return SDValue();
3607
3608   // FIXME: disable this unless the input to the binop is a shift by a constant.
3609   // If it is not a shift, it pessimizes some common cases like:
3610   //
3611   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3612   //    int bar(int *X, int i) { return X[i & 255]; }
3613   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3614   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3615        BinOpLHSVal->getOpcode() != ISD::SRA &&
3616        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3617       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3618     return SDValue();
3619
3620   EVT VT = N->getValueType(0);
3621
3622   // If this is a signed shift right, and the high bit is modified by the
3623   // logical operation, do not perform the transformation. The highBitSet
3624   // boolean indicates the value of the high bit of the constant which would
3625   // cause it to be modified for this operation.
3626   if (N->getOpcode() == ISD::SRA) {
3627     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3628     if (BinOpRHSSignSet != HighBitSet)
3629       return SDValue();
3630   }
3631
3632   // Fold the constants, shifting the binop RHS by the shift amount.
3633   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3634                                N->getValueType(0),
3635                                LHS->getOperand(1), N->getOperand(1));
3636
3637   // Create the new shift.
3638   SDValue NewShift = DAG.getNode(N->getOpcode(),
3639                                  SDLoc(LHS->getOperand(0)),
3640                                  VT, LHS->getOperand(0), N->getOperand(1));
3641
3642   // Create the new binop.
3643   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3644 }
3645
3646 SDValue DAGCombiner::visitSHL(SDNode *N) {
3647   SDValue N0 = N->getOperand(0);
3648   SDValue N1 = N->getOperand(1);
3649   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3650   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3651   EVT VT = N0.getValueType();
3652   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3653
3654   // fold (shl c1, c2) -> c1<<c2
3655   if (N0C && N1C)
3656     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3657   // fold (shl 0, x) -> 0
3658   if (N0C && N0C->isNullValue())
3659     return N0;
3660   // fold (shl x, c >= size(x)) -> undef
3661   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3662     return DAG.getUNDEF(VT);
3663   // fold (shl x, 0) -> x
3664   if (N1C && N1C->isNullValue())
3665     return N0;
3666   // fold (shl undef, x) -> 0
3667   if (N0.getOpcode() == ISD::UNDEF)
3668     return DAG.getConstant(0, VT);
3669   // if (shl x, c) is known to be zero, return 0
3670   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3671                             APInt::getAllOnesValue(OpSizeInBits)))
3672     return DAG.getConstant(0, VT);
3673   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3674   if (N1.getOpcode() == ISD::TRUNCATE &&
3675       N1.getOperand(0).getOpcode() == ISD::AND &&
3676       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3677     SDValue N101 = N1.getOperand(0).getOperand(1);
3678     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3679       EVT TruncVT = N1.getValueType();
3680       SDValue N100 = N1.getOperand(0).getOperand(0);
3681       APInt TruncC = N101C->getAPIntValue();
3682       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3683       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3684                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3685                                      DAG.getNode(ISD::TRUNCATE,
3686                                                  SDLoc(N),
3687                                                  TruncVT, N100),
3688                                      DAG.getConstant(TruncC, TruncVT)));
3689     }
3690   }
3691
3692   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3693     return SDValue(N, 0);
3694
3695   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3696   if (N1C && N0.getOpcode() == ISD::SHL &&
3697       N0.getOperand(1).getOpcode() == ISD::Constant) {
3698     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3699     uint64_t c2 = N1C->getZExtValue();
3700     if (c1 + c2 >= OpSizeInBits)
3701       return DAG.getConstant(0, VT);
3702     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3703                        DAG.getConstant(c1 + c2, N1.getValueType()));
3704   }
3705
3706   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3707   // For this to be valid, the second form must not preserve any of the bits
3708   // that are shifted out by the inner shift in the first form.  This means
3709   // the outer shift size must be >= the number of bits added by the ext.
3710   // As a corollary, we don't care what kind of ext it is.
3711   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3712               N0.getOpcode() == ISD::ANY_EXTEND ||
3713               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3714       N0.getOperand(0).getOpcode() == ISD::SHL &&
3715       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3716     uint64_t c1 =
3717       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3718     uint64_t c2 = N1C->getZExtValue();
3719     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3720     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3721     if (c2 >= OpSizeInBits - InnerShiftSize) {
3722       if (c1 + c2 >= OpSizeInBits)
3723         return DAG.getConstant(0, VT);
3724       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3725                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3726                                      N0.getOperand(0)->getOperand(0)),
3727                          DAG.getConstant(c1 + c2, N1.getValueType()));
3728     }
3729   }
3730
3731   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3732   //                               (and (srl x, (sub c1, c2), MASK)
3733   // Only fold this if the inner shift has no other uses -- if it does, folding
3734   // this will increase the total number of instructions.
3735   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3736       N0.getOperand(1).getOpcode() == ISD::Constant) {
3737     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3738     if (c1 < VT.getSizeInBits()) {
3739       uint64_t c2 = N1C->getZExtValue();
3740       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3741                                          VT.getSizeInBits() - c1);
3742       SDValue Shift;
3743       if (c2 > c1) {
3744         Mask = Mask.shl(c2-c1);
3745         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3746                             DAG.getConstant(c2-c1, N1.getValueType()));
3747       } else {
3748         Mask = Mask.lshr(c1-c2);
3749         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3750                             DAG.getConstant(c1-c2, N1.getValueType()));
3751       }
3752       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3753                          DAG.getConstant(Mask, VT));
3754     }
3755   }
3756   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3757   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3758     SDValue HiBitsMask =
3759       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3760                                             VT.getSizeInBits() -
3761                                               N1C->getZExtValue()),
3762                       VT);
3763     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3764                        HiBitsMask);
3765   }
3766
3767   if (N1C) {
3768     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3769     if (NewSHL.getNode())
3770       return NewSHL;
3771   }
3772
3773   return SDValue();
3774 }
3775
3776 SDValue DAGCombiner::visitSRA(SDNode *N) {
3777   SDValue N0 = N->getOperand(0);
3778   SDValue N1 = N->getOperand(1);
3779   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3780   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3781   EVT VT = N0.getValueType();
3782   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3783
3784   // fold (sra c1, c2) -> (sra c1, c2)
3785   if (N0C && N1C)
3786     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3787   // fold (sra 0, x) -> 0
3788   if (N0C && N0C->isNullValue())
3789     return N0;
3790   // fold (sra -1, x) -> -1
3791   if (N0C && N0C->isAllOnesValue())
3792     return N0;
3793   // fold (sra x, (setge c, size(x))) -> undef
3794   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3795     return DAG.getUNDEF(VT);
3796   // fold (sra x, 0) -> x
3797   if (N1C && N1C->isNullValue())
3798     return N0;
3799   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3800   // sext_inreg.
3801   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3802     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3803     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3804     if (VT.isVector())
3805       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3806                                ExtVT, VT.getVectorNumElements());
3807     if ((!LegalOperations ||
3808          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3809       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3810                          N0.getOperand(0), DAG.getValueType(ExtVT));
3811   }
3812
3813   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3814   if (N1C && N0.getOpcode() == ISD::SRA) {
3815     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3816       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3817       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3818       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3819                          DAG.getConstant(Sum, N1C->getValueType(0)));
3820     }
3821   }
3822
3823   // fold (sra (shl X, m), (sub result_size, n))
3824   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3825   // result_size - n != m.
3826   // If truncate is free for the target sext(shl) is likely to result in better
3827   // code.
3828   if (N0.getOpcode() == ISD::SHL) {
3829     // Get the two constanst of the shifts, CN0 = m, CN = n.
3830     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3831     if (N01C && N1C) {
3832       // Determine what the truncate's result bitsize and type would be.
3833       EVT TruncVT =
3834         EVT::getIntegerVT(*DAG.getContext(),
3835                           OpSizeInBits - N1C->getZExtValue());
3836       // Determine the residual right-shift amount.
3837       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3838
3839       // If the shift is not a no-op (in which case this should be just a sign
3840       // extend already), the truncated to type is legal, sign_extend is legal
3841       // on that type, and the truncate to that type is both legal and free,
3842       // perform the transform.
3843       if ((ShiftAmt > 0) &&
3844           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3845           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3846           TLI.isTruncateFree(VT, TruncVT)) {
3847
3848           SDValue Amt = DAG.getConstant(ShiftAmt,
3849               getShiftAmountTy(N0.getOperand(0).getValueType()));
3850           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3851                                       N0.getOperand(0), Amt);
3852           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3853                                       Shift);
3854           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3855                              N->getValueType(0), Trunc);
3856       }
3857     }
3858   }
3859
3860   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3861   if (N1.getOpcode() == ISD::TRUNCATE &&
3862       N1.getOperand(0).getOpcode() == ISD::AND &&
3863       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3864     SDValue N101 = N1.getOperand(0).getOperand(1);
3865     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3866       EVT TruncVT = N1.getValueType();
3867       SDValue N100 = N1.getOperand(0).getOperand(0);
3868       APInt TruncC = N101C->getAPIntValue();
3869       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3870       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3871                          DAG.getNode(ISD::AND, SDLoc(N),
3872                                      TruncVT,
3873                                      DAG.getNode(ISD::TRUNCATE,
3874                                                  SDLoc(N),
3875                                                  TruncVT, N100),
3876                                      DAG.getConstant(TruncC, TruncVT)));
3877     }
3878   }
3879
3880   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3881   //      if c1 is equal to the number of bits the trunc removes
3882   if (N0.getOpcode() == ISD::TRUNCATE &&
3883       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3884        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3885       N0.getOperand(0).hasOneUse() &&
3886       N0.getOperand(0).getOperand(1).hasOneUse() &&
3887       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3888     EVT LargeVT = N0.getOperand(0).getValueType();
3889     ConstantSDNode *LargeShiftAmt =
3890       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3891
3892     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3893         LargeShiftAmt->getZExtValue()) {
3894       SDValue Amt =
3895         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3896               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3897       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3898                                 N0.getOperand(0).getOperand(0), Amt);
3899       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3900     }
3901   }
3902
3903   // Simplify, based on bits shifted out of the LHS.
3904   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3905     return SDValue(N, 0);
3906
3907
3908   // If the sign bit is known to be zero, switch this to a SRL.
3909   if (DAG.SignBitIsZero(N0))
3910     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3911
3912   if (N1C) {
3913     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3914     if (NewSRA.getNode())
3915       return NewSRA;
3916   }
3917
3918   return SDValue();
3919 }
3920
3921 SDValue DAGCombiner::visitSRL(SDNode *N) {
3922   SDValue N0 = N->getOperand(0);
3923   SDValue N1 = N->getOperand(1);
3924   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3925   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3926   EVT VT = N0.getValueType();
3927   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3928
3929   // fold (srl c1, c2) -> c1 >>u c2
3930   if (N0C && N1C)
3931     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3932   // fold (srl 0, x) -> 0
3933   if (N0C && N0C->isNullValue())
3934     return N0;
3935   // fold (srl x, c >= size(x)) -> undef
3936   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3937     return DAG.getUNDEF(VT);
3938   // fold (srl x, 0) -> x
3939   if (N1C && N1C->isNullValue())
3940     return N0;
3941   // if (srl x, c) is known to be zero, return 0
3942   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3943                                    APInt::getAllOnesValue(OpSizeInBits)))
3944     return DAG.getConstant(0, VT);
3945
3946   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3947   if (N1C && N0.getOpcode() == ISD::SRL &&
3948       N0.getOperand(1).getOpcode() == ISD::Constant) {
3949     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3950     uint64_t c2 = N1C->getZExtValue();
3951     if (c1 + c2 >= OpSizeInBits)
3952       return DAG.getConstant(0, VT);
3953     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3954                        DAG.getConstant(c1 + c2, N1.getValueType()));
3955   }
3956
3957   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3958   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3959       N0.getOperand(0).getOpcode() == ISD::SRL &&
3960       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3961     uint64_t c1 =
3962       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3963     uint64_t c2 = N1C->getZExtValue();
3964     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3965     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3966     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3967     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3968     if (c1 + OpSizeInBits == InnerShiftSize) {
3969       if (c1 + c2 >= InnerShiftSize)
3970         return DAG.getConstant(0, VT);
3971       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
3972                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
3973                                      N0.getOperand(0)->getOperand(0),
3974                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3975     }
3976   }
3977
3978   // fold (srl (shl x, c), c) -> (and x, cst2)
3979   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3980       N0.getValueSizeInBits() <= 64) {
3981     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3982     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3983                        DAG.getConstant(~0ULL >> ShAmt, VT));
3984   }
3985
3986   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
3987   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3988     // Shifting in all undef bits?
3989     EVT SmallVT = N0.getOperand(0).getValueType();
3990     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3991       return DAG.getUNDEF(VT);
3992
3993     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3994       uint64_t ShiftAmt = N1C->getZExtValue();
3995       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
3996                                        N0.getOperand(0),
3997                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3998       AddToWorkList(SmallShift.getNode());
3999       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4000       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4001                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4002                          DAG.getConstant(Mask, VT));
4003     }
4004   }
4005
4006   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4007   // bit, which is unmodified by sra.
4008   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4009     if (N0.getOpcode() == ISD::SRA)
4010       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4011   }
4012
4013   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4014   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4015       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4016     APInt KnownZero, KnownOne;
4017     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4018
4019     // If any of the input bits are KnownOne, then the input couldn't be all
4020     // zeros, thus the result of the srl will always be zero.
4021     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4022
4023     // If all of the bits input the to ctlz node are known to be zero, then
4024     // the result of the ctlz is "32" and the result of the shift is one.
4025     APInt UnknownBits = ~KnownZero;
4026     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4027
4028     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4029     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4030       // Okay, we know that only that the single bit specified by UnknownBits
4031       // could be set on input to the CTLZ node. If this bit is set, the SRL
4032       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4033       // to an SRL/XOR pair, which is likely to simplify more.
4034       unsigned ShAmt = UnknownBits.countTrailingZeros();
4035       SDValue Op = N0.getOperand(0);
4036
4037       if (ShAmt) {
4038         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4039                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4040         AddToWorkList(Op.getNode());
4041       }
4042
4043       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4044                          Op, DAG.getConstant(1, VT));
4045     }
4046   }
4047
4048   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4049   if (N1.getOpcode() == ISD::TRUNCATE &&
4050       N1.getOperand(0).getOpcode() == ISD::AND &&
4051       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4052     SDValue N101 = N1.getOperand(0).getOperand(1);
4053     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4054       EVT TruncVT = N1.getValueType();
4055       SDValue N100 = N1.getOperand(0).getOperand(0);
4056       APInt TruncC = N101C->getAPIntValue();
4057       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4058       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4059                          DAG.getNode(ISD::AND, SDLoc(N),
4060                                      TruncVT,
4061                                      DAG.getNode(ISD::TRUNCATE,
4062                                                  SDLoc(N),
4063                                                  TruncVT, N100),
4064                                      DAG.getConstant(TruncC, TruncVT)));
4065     }
4066   }
4067
4068   // fold operands of srl based on knowledge that the low bits are not
4069   // demanded.
4070   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4071     return SDValue(N, 0);
4072
4073   if (N1C) {
4074     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4075     if (NewSRL.getNode())
4076       return NewSRL;
4077   }
4078
4079   // Attempt to convert a srl of a load into a narrower zero-extending load.
4080   SDValue NarrowLoad = ReduceLoadWidth(N);
4081   if (NarrowLoad.getNode())
4082     return NarrowLoad;
4083
4084   // Here is a common situation. We want to optimize:
4085   //
4086   //   %a = ...
4087   //   %b = and i32 %a, 2
4088   //   %c = srl i32 %b, 1
4089   //   brcond i32 %c ...
4090   //
4091   // into
4092   //
4093   //   %a = ...
4094   //   %b = and %a, 2
4095   //   %c = setcc eq %b, 0
4096   //   brcond %c ...
4097   //
4098   // However when after the source operand of SRL is optimized into AND, the SRL
4099   // itself may not be optimized further. Look for it and add the BRCOND into
4100   // the worklist.
4101   if (N->hasOneUse()) {
4102     SDNode *Use = *N->use_begin();
4103     if (Use->getOpcode() == ISD::BRCOND)
4104       AddToWorkList(Use);
4105     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4106       // Also look pass the truncate.
4107       Use = *Use->use_begin();
4108       if (Use->getOpcode() == ISD::BRCOND)
4109         AddToWorkList(Use);
4110     }
4111   }
4112
4113   return SDValue();
4114 }
4115
4116 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4117   SDValue N0 = N->getOperand(0);
4118   EVT VT = N->getValueType(0);
4119
4120   // fold (ctlz c1) -> c2
4121   if (isa<ConstantSDNode>(N0))
4122     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4123   return SDValue();
4124 }
4125
4126 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4127   SDValue N0 = N->getOperand(0);
4128   EVT VT = N->getValueType(0);
4129
4130   // fold (ctlz_zero_undef c1) -> c2
4131   if (isa<ConstantSDNode>(N0))
4132     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4133   return SDValue();
4134 }
4135
4136 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4137   SDValue N0 = N->getOperand(0);
4138   EVT VT = N->getValueType(0);
4139
4140   // fold (cttz c1) -> c2
4141   if (isa<ConstantSDNode>(N0))
4142     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4143   return SDValue();
4144 }
4145
4146 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4147   SDValue N0 = N->getOperand(0);
4148   EVT VT = N->getValueType(0);
4149
4150   // fold (cttz_zero_undef c1) -> c2
4151   if (isa<ConstantSDNode>(N0))
4152     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4153   return SDValue();
4154 }
4155
4156 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4157   SDValue N0 = N->getOperand(0);
4158   EVT VT = N->getValueType(0);
4159
4160   // fold (ctpop c1) -> c2
4161   if (isa<ConstantSDNode>(N0))
4162     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4163   return SDValue();
4164 }
4165
4166 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4167   SDValue N0 = N->getOperand(0);
4168   SDValue N1 = N->getOperand(1);
4169   SDValue N2 = N->getOperand(2);
4170   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4171   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4172   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4173   EVT VT = N->getValueType(0);
4174   EVT VT0 = N0.getValueType();
4175
4176   // fold (select C, X, X) -> X
4177   if (N1 == N2)
4178     return N1;
4179   // fold (select true, X, Y) -> X
4180   if (N0C && !N0C->isNullValue())
4181     return N1;
4182   // fold (select false, X, Y) -> Y
4183   if (N0C && N0C->isNullValue())
4184     return N2;
4185   // fold (select C, 1, X) -> (or C, X)
4186   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4187     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4188   // fold (select C, 0, 1) -> (xor C, 1)
4189   if (VT.isInteger() &&
4190       (VT0 == MVT::i1 ||
4191        (VT0.isInteger() &&
4192         TLI.getBooleanContents(false) ==
4193         TargetLowering::ZeroOrOneBooleanContent)) &&
4194       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4195     SDValue XORNode;
4196     if (VT == VT0)
4197       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4198                          N0, DAG.getConstant(1, VT0));
4199     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4200                           N0, DAG.getConstant(1, VT0));
4201     AddToWorkList(XORNode.getNode());
4202     if (VT.bitsGT(VT0))
4203       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4204     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4205   }
4206   // fold (select C, 0, X) -> (and (not C), X)
4207   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4208     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4209     AddToWorkList(NOTNode.getNode());
4210     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4211   }
4212   // fold (select C, X, 1) -> (or (not C), X)
4213   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4214     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4215     AddToWorkList(NOTNode.getNode());
4216     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4217   }
4218   // fold (select C, X, 0) -> (and C, X)
4219   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4220     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4221   // fold (select X, X, Y) -> (or X, Y)
4222   // fold (select X, 1, Y) -> (or X, Y)
4223   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4224     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4225   // fold (select X, Y, X) -> (and X, Y)
4226   // fold (select X, Y, 0) -> (and X, Y)
4227   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4228     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4229
4230   // If we can fold this based on the true/false value, do so.
4231   if (SimplifySelectOps(N, N1, N2))
4232     return SDValue(N, 0);  // Don't revisit N.
4233
4234   // fold selects based on a setcc into other things, such as min/max/abs
4235   if (N0.getOpcode() == ISD::SETCC) {
4236     // FIXME:
4237     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4238     // having to say they don't support SELECT_CC on every type the DAG knows
4239     // about, since there is no way to mark an opcode illegal at all value types
4240     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4241         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4242       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4243                          N0.getOperand(0), N0.getOperand(1),
4244                          N1, N2, N0.getOperand(2));
4245     return SimplifySelect(SDLoc(N), N0, N1, N2);
4246   }
4247
4248   return SDValue();
4249 }
4250
4251 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4252   SDValue N0 = N->getOperand(0);
4253   SDValue N1 = N->getOperand(1);
4254   SDValue N2 = N->getOperand(2);
4255   SDLoc DL(N);
4256
4257   // Canonicalize integer abs.
4258   // vselect (setg[te] X,  0),  X, -X ->
4259   // vselect (setgt    X, -1),  X, -X ->
4260   // vselect (setl[te] X,  0), -X,  X ->
4261   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4262   if (N0.getOpcode() == ISD::SETCC) {
4263     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4264     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4265     bool isAbs = false;
4266     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4267
4268     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4269          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4270         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4271       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4272     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4273              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4274       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4275
4276     if (isAbs) {
4277       EVT VT = LHS.getValueType();
4278       SDValue Shift = DAG.getNode(
4279           ISD::SRA, DL, VT, LHS,
4280           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4281       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4282       AddToWorkList(Shift.getNode());
4283       AddToWorkList(Add.getNode());
4284       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4285     }
4286   }
4287
4288   return SDValue();
4289 }
4290
4291 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4292   SDValue N0 = N->getOperand(0);
4293   SDValue N1 = N->getOperand(1);
4294   SDValue N2 = N->getOperand(2);
4295   SDValue N3 = N->getOperand(3);
4296   SDValue N4 = N->getOperand(4);
4297   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4298
4299   // fold select_cc lhs, rhs, x, x, cc -> x
4300   if (N2 == N3)
4301     return N2;
4302
4303   // Determine if the condition we're dealing with is constant
4304   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4305                               N0, N1, CC, SDLoc(N), false);
4306   if (SCC.getNode()) {
4307     AddToWorkList(SCC.getNode());
4308
4309     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4310       if (!SCCC->isNullValue())
4311         return N2;    // cond always true -> true val
4312       else
4313         return N3;    // cond always false -> false val
4314     }
4315
4316     // Fold to a simpler select_cc
4317     if (SCC.getOpcode() == ISD::SETCC)
4318       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4319                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4320                          SCC.getOperand(2));
4321   }
4322
4323   // If we can fold this based on the true/false value, do so.
4324   if (SimplifySelectOps(N, N2, N3))
4325     return SDValue(N, 0);  // Don't revisit N.
4326
4327   // fold select_cc into other things, such as min/max/abs
4328   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4329 }
4330
4331 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4332   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4333                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4334                        SDLoc(N));
4335 }
4336
4337 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4338 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4339 // transformation. Returns true if extension are possible and the above
4340 // mentioned transformation is profitable.
4341 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4342                                     unsigned ExtOpc,
4343                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4344                                     const TargetLowering &TLI) {
4345   bool HasCopyToRegUses = false;
4346   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4347   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4348                             UE = N0.getNode()->use_end();
4349        UI != UE; ++UI) {
4350     SDNode *User = *UI;
4351     if (User == N)
4352       continue;
4353     if (UI.getUse().getResNo() != N0.getResNo())
4354       continue;
4355     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4356     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4357       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4358       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4359         // Sign bits will be lost after a zext.
4360         return false;
4361       bool Add = false;
4362       for (unsigned i = 0; i != 2; ++i) {
4363         SDValue UseOp = User->getOperand(i);
4364         if (UseOp == N0)
4365           continue;
4366         if (!isa<ConstantSDNode>(UseOp))
4367           return false;
4368         Add = true;
4369       }
4370       if (Add)
4371         ExtendNodes.push_back(User);
4372       continue;
4373     }
4374     // If truncates aren't free and there are users we can't
4375     // extend, it isn't worthwhile.
4376     if (!isTruncFree)
4377       return false;
4378     // Remember if this value is live-out.
4379     if (User->getOpcode() == ISD::CopyToReg)
4380       HasCopyToRegUses = true;
4381   }
4382
4383   if (HasCopyToRegUses) {
4384     bool BothLiveOut = false;
4385     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4386          UI != UE; ++UI) {
4387       SDUse &Use = UI.getUse();
4388       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4389         BothLiveOut = true;
4390         break;
4391       }
4392     }
4393     if (BothLiveOut)
4394       // Both unextended and extended values are live out. There had better be
4395       // a good reason for the transformation.
4396       return ExtendNodes.size();
4397   }
4398   return true;
4399 }
4400
4401 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4402                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4403                                   ISD::NodeType ExtType) {
4404   // Extend SetCC uses if necessary.
4405   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4406     SDNode *SetCC = SetCCs[i];
4407     SmallVector<SDValue, 4> Ops;
4408
4409     for (unsigned j = 0; j != 2; ++j) {
4410       SDValue SOp = SetCC->getOperand(j);
4411       if (SOp == Trunc)
4412         Ops.push_back(ExtLoad);
4413       else
4414         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4415     }
4416
4417     Ops.push_back(SetCC->getOperand(2));
4418     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4419                                  &Ops[0], Ops.size()));
4420   }
4421 }
4422
4423 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4424   SDValue N0 = N->getOperand(0);
4425   EVT VT = N->getValueType(0);
4426
4427   // fold (sext c1) -> c1
4428   if (isa<ConstantSDNode>(N0))
4429     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4430
4431   // fold (sext (sext x)) -> (sext x)
4432   // fold (sext (aext x)) -> (sext x)
4433   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4434     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4435                        N0.getOperand(0));
4436
4437   if (N0.getOpcode() == ISD::TRUNCATE) {
4438     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4439     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4440     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4441     if (NarrowLoad.getNode()) {
4442       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4443       if (NarrowLoad.getNode() != N0.getNode()) {
4444         CombineTo(N0.getNode(), NarrowLoad);
4445         // CombineTo deleted the truncate, if needed, but not what's under it.
4446         AddToWorkList(oye);
4447       }
4448       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4449     }
4450
4451     // See if the value being truncated is already sign extended.  If so, just
4452     // eliminate the trunc/sext pair.
4453     SDValue Op = N0.getOperand(0);
4454     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4455     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4456     unsigned DestBits = VT.getScalarType().getSizeInBits();
4457     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4458
4459     if (OpBits == DestBits) {
4460       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4461       // bits, it is already ready.
4462       if (NumSignBits > DestBits-MidBits)
4463         return Op;
4464     } else if (OpBits < DestBits) {
4465       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4466       // bits, just sext from i32.
4467       if (NumSignBits > OpBits-MidBits)
4468         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4469     } else {
4470       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4471       // bits, just truncate to i32.
4472       if (NumSignBits > OpBits-MidBits)
4473         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4474     }
4475
4476     // fold (sext (truncate x)) -> (sextinreg x).
4477     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4478                                                  N0.getValueType())) {
4479       if (OpBits < DestBits)
4480         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4481       else if (OpBits > DestBits)
4482         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4483       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4484                          DAG.getValueType(N0.getValueType()));
4485     }
4486   }
4487
4488   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4489   // None of the supported targets knows how to perform load and sign extend
4490   // on vectors in one instruction.  We only perform this transformation on
4491   // scalars.
4492   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4493       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4494        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4495     bool DoXform = true;
4496     SmallVector<SDNode*, 4> SetCCs;
4497     if (!N0.hasOneUse())
4498       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4499     if (DoXform) {
4500       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4501       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4502                                        LN0->getChain(),
4503                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4504                                        N0.getValueType(),
4505                                        LN0->isVolatile(), LN0->isNonTemporal(),
4506                                        LN0->getAlignment());
4507       CombineTo(N, ExtLoad);
4508       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4509                                   N0.getValueType(), ExtLoad);
4510       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4511       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4512                       ISD::SIGN_EXTEND);
4513       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4514     }
4515   }
4516
4517   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4518   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4519   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4520       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4521     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4522     EVT MemVT = LN0->getMemoryVT();
4523     if ((!LegalOperations && !LN0->isVolatile()) ||
4524         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4525       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4526                                        LN0->getChain(),
4527                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4528                                        MemVT,
4529                                        LN0->isVolatile(), LN0->isNonTemporal(),
4530                                        LN0->getAlignment());
4531       CombineTo(N, ExtLoad);
4532       CombineTo(N0.getNode(),
4533                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4534                             N0.getValueType(), ExtLoad),
4535                 ExtLoad.getValue(1));
4536       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4537     }
4538   }
4539
4540   // fold (sext (and/or/xor (load x), cst)) ->
4541   //      (and/or/xor (sextload x), (sext cst))
4542   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4543        N0.getOpcode() == ISD::XOR) &&
4544       isa<LoadSDNode>(N0.getOperand(0)) &&
4545       N0.getOperand(1).getOpcode() == ISD::Constant &&
4546       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4547       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4548     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4549     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4550       bool DoXform = true;
4551       SmallVector<SDNode*, 4> SetCCs;
4552       if (!N0.hasOneUse())
4553         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4554                                           SetCCs, TLI);
4555       if (DoXform) {
4556         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4557                                          LN0->getChain(), LN0->getBasePtr(),
4558                                          LN0->getPointerInfo(),
4559                                          LN0->getMemoryVT(),
4560                                          LN0->isVolatile(),
4561                                          LN0->isNonTemporal(),
4562                                          LN0->getAlignment());
4563         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4564         Mask = Mask.sext(VT.getSizeInBits());
4565         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4566                                   ExtLoad, DAG.getConstant(Mask, VT));
4567         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4568                                     SDLoc(N0.getOperand(0)),
4569                                     N0.getOperand(0).getValueType(), ExtLoad);
4570         CombineTo(N, And);
4571         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4572         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4573                         ISD::SIGN_EXTEND);
4574         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4575       }
4576     }
4577   }
4578
4579   if (N0.getOpcode() == ISD::SETCC) {
4580     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4581     // Only do this before legalize for now.
4582     if (VT.isVector() && !LegalOperations &&
4583         TLI.getBooleanContents(true) ==
4584           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4585       EVT N0VT = N0.getOperand(0).getValueType();
4586       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4587       // of the same size as the compared operands. Only optimize sext(setcc())
4588       // if this is the case.
4589       EVT SVT = getSetCCResultType(N0VT);
4590
4591       // We know that the # elements of the results is the same as the
4592       // # elements of the compare (and the # elements of the compare result
4593       // for that matter).  Check to see that they are the same size.  If so,
4594       // we know that the element size of the sext'd result matches the
4595       // element size of the compare operands.
4596       if (VT.getSizeInBits() == SVT.getSizeInBits())
4597         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4598                              N0.getOperand(1),
4599                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4600
4601       // If the desired elements are smaller or larger than the source
4602       // elements we can use a matching integer vector type and then
4603       // truncate/sign extend
4604       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4605       if (SVT == MatchingVectorType) {
4606         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4607                                N0.getOperand(0), N0.getOperand(1),
4608                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4609         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4610       }
4611     }
4612
4613     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4614     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4615     SDValue NegOne =
4616       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4617     SDValue SCC =
4618       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4619                        NegOne, DAG.getConstant(0, VT),
4620                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4621     if (SCC.getNode()) return SCC;
4622     if (!VT.isVector() &&
4623         (!LegalOperations ||
4624          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4625       return DAG.getSelect(SDLoc(N), VT,
4626                            DAG.getSetCC(SDLoc(N),
4627                                         getSetCCResultType(VT),
4628                                         N0.getOperand(0), N0.getOperand(1),
4629                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4630                            NegOne, DAG.getConstant(0, VT));
4631     }
4632   }
4633
4634   // fold (sext x) -> (zext x) if the sign bit is known zero.
4635   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4636       DAG.SignBitIsZero(N0))
4637     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4638
4639   return SDValue();
4640 }
4641
4642 // isTruncateOf - If N is a truncate of some other value, return true, record
4643 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4644 // This function computes KnownZero to avoid a duplicated call to
4645 // ComputeMaskedBits in the caller.
4646 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4647                          APInt &KnownZero) {
4648   APInt KnownOne;
4649   if (N->getOpcode() == ISD::TRUNCATE) {
4650     Op = N->getOperand(0);
4651     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4652     return true;
4653   }
4654
4655   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4656       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4657     return false;
4658
4659   SDValue Op0 = N->getOperand(0);
4660   SDValue Op1 = N->getOperand(1);
4661   assert(Op0.getValueType() == Op1.getValueType());
4662
4663   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4664   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4665   if (COp0 && COp0->isNullValue())
4666     Op = Op1;
4667   else if (COp1 && COp1->isNullValue())
4668     Op = Op0;
4669   else
4670     return false;
4671
4672   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4673
4674   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4675     return false;
4676
4677   return true;
4678 }
4679
4680 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4681   SDValue N0 = N->getOperand(0);
4682   EVT VT = N->getValueType(0);
4683
4684   // fold (zext c1) -> c1
4685   if (isa<ConstantSDNode>(N0))
4686     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4687   // fold (zext (zext x)) -> (zext x)
4688   // fold (zext (aext x)) -> (zext x)
4689   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4690     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4691                        N0.getOperand(0));
4692
4693   // fold (zext (truncate x)) -> (zext x) or
4694   //      (zext (truncate x)) -> (truncate x)
4695   // This is valid when the truncated bits of x are already zero.
4696   // FIXME: We should extend this to work for vectors too.
4697   SDValue Op;
4698   APInt KnownZero;
4699   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4700     APInt TruncatedBits =
4701       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4702       APInt(Op.getValueSizeInBits(), 0) :
4703       APInt::getBitsSet(Op.getValueSizeInBits(),
4704                         N0.getValueSizeInBits(),
4705                         std::min(Op.getValueSizeInBits(),
4706                                  VT.getSizeInBits()));
4707     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4708       if (VT.bitsGT(Op.getValueType()))
4709         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4710       if (VT.bitsLT(Op.getValueType()))
4711         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4712
4713       return Op;
4714     }
4715   }
4716
4717   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4718   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4719   if (N0.getOpcode() == ISD::TRUNCATE) {
4720     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4721     if (NarrowLoad.getNode()) {
4722       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4723       if (NarrowLoad.getNode() != N0.getNode()) {
4724         CombineTo(N0.getNode(), NarrowLoad);
4725         // CombineTo deleted the truncate, if needed, but not what's under it.
4726         AddToWorkList(oye);
4727       }
4728       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4729     }
4730   }
4731
4732   // fold (zext (truncate x)) -> (and x, mask)
4733   if (N0.getOpcode() == ISD::TRUNCATE &&
4734       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4735
4736     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4737     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4738     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4739     if (NarrowLoad.getNode()) {
4740       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4741       if (NarrowLoad.getNode() != N0.getNode()) {
4742         CombineTo(N0.getNode(), NarrowLoad);
4743         // CombineTo deleted the truncate, if needed, but not what's under it.
4744         AddToWorkList(oye);
4745       }
4746       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4747     }
4748
4749     SDValue Op = N0.getOperand(0);
4750     if (Op.getValueType().bitsLT(VT)) {
4751       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4752       AddToWorkList(Op.getNode());
4753     } else if (Op.getValueType().bitsGT(VT)) {
4754       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4755       AddToWorkList(Op.getNode());
4756     }
4757     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4758                                   N0.getValueType().getScalarType());
4759   }
4760
4761   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4762   // if either of the casts is not free.
4763   if (N0.getOpcode() == ISD::AND &&
4764       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4765       N0.getOperand(1).getOpcode() == ISD::Constant &&
4766       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4767                            N0.getValueType()) ||
4768        !TLI.isZExtFree(N0.getValueType(), VT))) {
4769     SDValue X = N0.getOperand(0).getOperand(0);
4770     if (X.getValueType().bitsLT(VT)) {
4771       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4772     } else if (X.getValueType().bitsGT(VT)) {
4773       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4774     }
4775     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4776     Mask = Mask.zext(VT.getSizeInBits());
4777     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4778                        X, DAG.getConstant(Mask, VT));
4779   }
4780
4781   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4782   // None of the supported targets knows how to perform load and vector_zext
4783   // on vectors in one instruction.  We only perform this transformation on
4784   // scalars.
4785   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4786       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4787        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4788     bool DoXform = true;
4789     SmallVector<SDNode*, 4> SetCCs;
4790     if (!N0.hasOneUse())
4791       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4792     if (DoXform) {
4793       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4794       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4795                                        LN0->getChain(),
4796                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4797                                        N0.getValueType(),
4798                                        LN0->isVolatile(), LN0->isNonTemporal(),
4799                                        LN0->getAlignment());
4800       CombineTo(N, ExtLoad);
4801       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4802                                   N0.getValueType(), ExtLoad);
4803       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4804
4805       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4806                       ISD::ZERO_EXTEND);
4807       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4808     }
4809   }
4810
4811   // fold (zext (and/or/xor (load x), cst)) ->
4812   //      (and/or/xor (zextload x), (zext cst))
4813   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4814        N0.getOpcode() == ISD::XOR) &&
4815       isa<LoadSDNode>(N0.getOperand(0)) &&
4816       N0.getOperand(1).getOpcode() == ISD::Constant &&
4817       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4818       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4819     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4820     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4821       bool DoXform = true;
4822       SmallVector<SDNode*, 4> SetCCs;
4823       if (!N0.hasOneUse())
4824         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4825                                           SetCCs, TLI);
4826       if (DoXform) {
4827         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4828                                          LN0->getChain(), LN0->getBasePtr(),
4829                                          LN0->getPointerInfo(),
4830                                          LN0->getMemoryVT(),
4831                                          LN0->isVolatile(),
4832                                          LN0->isNonTemporal(),
4833                                          LN0->getAlignment());
4834         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4835         Mask = Mask.zext(VT.getSizeInBits());
4836         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4837                                   ExtLoad, DAG.getConstant(Mask, VT));
4838         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4839                                     SDLoc(N0.getOperand(0)),
4840                                     N0.getOperand(0).getValueType(), ExtLoad);
4841         CombineTo(N, And);
4842         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4843         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4844                         ISD::ZERO_EXTEND);
4845         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4846       }
4847     }
4848   }
4849
4850   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4851   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4852   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4853       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4854     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4855     EVT MemVT = LN0->getMemoryVT();
4856     if ((!LegalOperations && !LN0->isVolatile()) ||
4857         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4858       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4859                                        LN0->getChain(),
4860                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4861                                        MemVT,
4862                                        LN0->isVolatile(), LN0->isNonTemporal(),
4863                                        LN0->getAlignment());
4864       CombineTo(N, ExtLoad);
4865       CombineTo(N0.getNode(),
4866                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4867                             ExtLoad),
4868                 ExtLoad.getValue(1));
4869       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4870     }
4871   }
4872
4873   if (N0.getOpcode() == ISD::SETCC) {
4874     if (!LegalOperations && VT.isVector()) {
4875       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4876       // Only do this before legalize for now.
4877       EVT N0VT = N0.getOperand(0).getValueType();
4878       EVT EltVT = VT.getVectorElementType();
4879       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4880                                     DAG.getConstant(1, EltVT));
4881       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4882         // We know that the # elements of the results is the same as the
4883         // # elements of the compare (and the # elements of the compare result
4884         // for that matter).  Check to see that they are the same size.  If so,
4885         // we know that the element size of the sext'd result matches the
4886         // element size of the compare operands.
4887         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4888                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4889                                          N0.getOperand(1),
4890                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4891                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4892                                        &OneOps[0], OneOps.size()));
4893
4894       // If the desired elements are smaller or larger than the source
4895       // elements we can use a matching integer vector type and then
4896       // truncate/sign extend
4897       EVT MatchingElementType =
4898         EVT::getIntegerVT(*DAG.getContext(),
4899                           N0VT.getScalarType().getSizeInBits());
4900       EVT MatchingVectorType =
4901         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4902                          N0VT.getVectorNumElements());
4903       SDValue VsetCC =
4904         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4905                       N0.getOperand(1),
4906                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4907       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4908                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4909                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4910                                      &OneOps[0], OneOps.size()));
4911     }
4912
4913     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4914     SDValue SCC =
4915       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4916                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4917                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4918     if (SCC.getNode()) return SCC;
4919   }
4920
4921   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4922   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4923       isa<ConstantSDNode>(N0.getOperand(1)) &&
4924       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4925       N0.hasOneUse()) {
4926     SDValue ShAmt = N0.getOperand(1);
4927     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4928     if (N0.getOpcode() == ISD::SHL) {
4929       SDValue InnerZExt = N0.getOperand(0);
4930       // If the original shl may be shifting out bits, do not perform this
4931       // transformation.
4932       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4933         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4934       if (ShAmtVal > KnownZeroBits)
4935         return SDValue();
4936     }
4937
4938     SDLoc DL(N);
4939
4940     // Ensure that the shift amount is wide enough for the shifted value.
4941     if (VT.getSizeInBits() >= 256)
4942       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4943
4944     return DAG.getNode(N0.getOpcode(), DL, VT,
4945                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4946                        ShAmt);
4947   }
4948
4949   return SDValue();
4950 }
4951
4952 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4953   SDValue N0 = N->getOperand(0);
4954   EVT VT = N->getValueType(0);
4955
4956   // fold (aext c1) -> c1
4957   if (isa<ConstantSDNode>(N0))
4958     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4959   // fold (aext (aext x)) -> (aext x)
4960   // fold (aext (zext x)) -> (zext x)
4961   // fold (aext (sext x)) -> (sext x)
4962   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4963       N0.getOpcode() == ISD::ZERO_EXTEND ||
4964       N0.getOpcode() == ISD::SIGN_EXTEND)
4965     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
4966
4967   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4968   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4969   if (N0.getOpcode() == ISD::TRUNCATE) {
4970     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4971     if (NarrowLoad.getNode()) {
4972       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4973       if (NarrowLoad.getNode() != N0.getNode()) {
4974         CombineTo(N0.getNode(), NarrowLoad);
4975         // CombineTo deleted the truncate, if needed, but not what's under it.
4976         AddToWorkList(oye);
4977       }
4978       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4979     }
4980   }
4981
4982   // fold (aext (truncate x))
4983   if (N0.getOpcode() == ISD::TRUNCATE) {
4984     SDValue TruncOp = N0.getOperand(0);
4985     if (TruncOp.getValueType() == VT)
4986       return TruncOp; // x iff x size == zext size.
4987     if (TruncOp.getValueType().bitsGT(VT))
4988       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
4989     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
4990   }
4991
4992   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4993   // if the trunc is not free.
4994   if (N0.getOpcode() == ISD::AND &&
4995       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4996       N0.getOperand(1).getOpcode() == ISD::Constant &&
4997       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4998                           N0.getValueType())) {
4999     SDValue X = N0.getOperand(0).getOperand(0);
5000     if (X.getValueType().bitsLT(VT)) {
5001       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5002     } else if (X.getValueType().bitsGT(VT)) {
5003       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5004     }
5005     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5006     Mask = Mask.zext(VT.getSizeInBits());
5007     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5008                        X, DAG.getConstant(Mask, VT));
5009   }
5010
5011   // fold (aext (load x)) -> (aext (truncate (extload x)))
5012   // None of the supported targets knows how to perform load and any_ext
5013   // on vectors in one instruction.  We only perform this transformation on
5014   // scalars.
5015   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5016       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5017        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5018     bool DoXform = true;
5019     SmallVector<SDNode*, 4> SetCCs;
5020     if (!N0.hasOneUse())
5021       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5022     if (DoXform) {
5023       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5024       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5025                                        LN0->getChain(),
5026                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5027                                        N0.getValueType(),
5028                                        LN0->isVolatile(), LN0->isNonTemporal(),
5029                                        LN0->getAlignment());
5030       CombineTo(N, ExtLoad);
5031       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5032                                   N0.getValueType(), ExtLoad);
5033       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5034       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5035                       ISD::ANY_EXTEND);
5036       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5037     }
5038   }
5039
5040   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5041   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5042   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5043   if (N0.getOpcode() == ISD::LOAD &&
5044       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5045       N0.hasOneUse()) {
5046     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5047     EVT MemVT = LN0->getMemoryVT();
5048     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5049                                      VT, LN0->getChain(), LN0->getBasePtr(),
5050                                      LN0->getPointerInfo(), MemVT,
5051                                      LN0->isVolatile(), LN0->isNonTemporal(),
5052                                      LN0->getAlignment());
5053     CombineTo(N, ExtLoad);
5054     CombineTo(N0.getNode(),
5055               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5056                           N0.getValueType(), ExtLoad),
5057               ExtLoad.getValue(1));
5058     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5059   }
5060
5061   if (N0.getOpcode() == ISD::SETCC) {
5062     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5063     // Only do this before legalize for now.
5064     if (VT.isVector() && !LegalOperations) {
5065       EVT N0VT = N0.getOperand(0).getValueType();
5066         // We know that the # elements of the results is the same as the
5067         // # elements of the compare (and the # elements of the compare result
5068         // for that matter).  Check to see that they are the same size.  If so,
5069         // we know that the element size of the sext'd result matches the
5070         // element size of the compare operands.
5071       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5072         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5073                              N0.getOperand(1),
5074                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5075       // If the desired elements are smaller or larger than the source
5076       // elements we can use a matching integer vector type and then
5077       // truncate/sign extend
5078       else {
5079         EVT MatchingElementType =
5080           EVT::getIntegerVT(*DAG.getContext(),
5081                             N0VT.getScalarType().getSizeInBits());
5082         EVT MatchingVectorType =
5083           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5084                            N0VT.getVectorNumElements());
5085         SDValue VsetCC =
5086           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5087                         N0.getOperand(1),
5088                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5089         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5090       }
5091     }
5092
5093     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5094     SDValue SCC =
5095       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5096                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5097                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5098     if (SCC.getNode())
5099       return SCC;
5100   }
5101
5102   return SDValue();
5103 }
5104
5105 /// GetDemandedBits - See if the specified operand can be simplified with the
5106 /// knowledge that only the bits specified by Mask are used.  If so, return the
5107 /// simpler operand, otherwise return a null SDValue.
5108 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5109   switch (V.getOpcode()) {
5110   default: break;
5111   case ISD::Constant: {
5112     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5113     assert(CV != 0 && "Const value should be ConstSDNode.");
5114     const APInt &CVal = CV->getAPIntValue();
5115     APInt NewVal = CVal & Mask;
5116     if (NewVal != CVal)
5117       return DAG.getConstant(NewVal, V.getValueType());
5118     break;
5119   }
5120   case ISD::OR:
5121   case ISD::XOR:
5122     // If the LHS or RHS don't contribute bits to the or, drop them.
5123     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5124       return V.getOperand(1);
5125     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5126       return V.getOperand(0);
5127     break;
5128   case ISD::SRL:
5129     // Only look at single-use SRLs.
5130     if (!V.getNode()->hasOneUse())
5131       break;
5132     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5133       // See if we can recursively simplify the LHS.
5134       unsigned Amt = RHSC->getZExtValue();
5135
5136       // Watch out for shift count overflow though.
5137       if (Amt >= Mask.getBitWidth()) break;
5138       APInt NewMask = Mask << Amt;
5139       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5140       if (SimplifyLHS.getNode())
5141         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5142                            SimplifyLHS, V.getOperand(1));
5143     }
5144   }
5145   return SDValue();
5146 }
5147
5148 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5149 /// bits and then truncated to a narrower type and where N is a multiple
5150 /// of number of bits of the narrower type, transform it to a narrower load
5151 /// from address + N / num of bits of new type. If the result is to be
5152 /// extended, also fold the extension to form a extending load.
5153 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5154   unsigned Opc = N->getOpcode();
5155
5156   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5157   SDValue N0 = N->getOperand(0);
5158   EVT VT = N->getValueType(0);
5159   EVT ExtVT = VT;
5160
5161   // This transformation isn't valid for vector loads.
5162   if (VT.isVector())
5163     return SDValue();
5164
5165   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5166   // extended to VT.
5167   if (Opc == ISD::SIGN_EXTEND_INREG) {
5168     ExtType = ISD::SEXTLOAD;
5169     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5170   } else if (Opc == ISD::SRL) {
5171     // Another special-case: SRL is basically zero-extending a narrower value.
5172     ExtType = ISD::ZEXTLOAD;
5173     N0 = SDValue(N, 0);
5174     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5175     if (!N01) return SDValue();
5176     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5177                               VT.getSizeInBits() - N01->getZExtValue());
5178   }
5179   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5180     return SDValue();
5181
5182   unsigned EVTBits = ExtVT.getSizeInBits();
5183
5184   // Do not generate loads of non-round integer types since these can
5185   // be expensive (and would be wrong if the type is not byte sized).
5186   if (!ExtVT.isRound())
5187     return SDValue();
5188
5189   unsigned ShAmt = 0;
5190   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5191     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5192       ShAmt = N01->getZExtValue();
5193       // Is the shift amount a multiple of size of VT?
5194       if ((ShAmt & (EVTBits-1)) == 0) {
5195         N0 = N0.getOperand(0);
5196         // Is the load width a multiple of size of VT?
5197         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5198           return SDValue();
5199       }
5200
5201       // At this point, we must have a load or else we can't do the transform.
5202       if (!isa<LoadSDNode>(N0)) return SDValue();
5203
5204       // Because a SRL must be assumed to *need* to zero-extend the high bits
5205       // (as opposed to anyext the high bits), we can't combine the zextload
5206       // lowering of SRL and an sextload.
5207       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5208         return SDValue();
5209
5210       // If the shift amount is larger than the input type then we're not
5211       // accessing any of the loaded bytes.  If the load was a zextload/extload
5212       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5213       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5214         return SDValue();
5215     }
5216   }
5217
5218   // If the load is shifted left (and the result isn't shifted back right),
5219   // we can fold the truncate through the shift.
5220   unsigned ShLeftAmt = 0;
5221   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5222       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5223     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5224       ShLeftAmt = N01->getZExtValue();
5225       N0 = N0.getOperand(0);
5226     }
5227   }
5228
5229   // If we haven't found a load, we can't narrow it.  Don't transform one with
5230   // multiple uses, this would require adding a new load.
5231   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5232     return SDValue();
5233
5234   // Don't change the width of a volatile load.
5235   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5236   if (LN0->isVolatile())
5237     return SDValue();
5238
5239   // Verify that we are actually reducing a load width here.
5240   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5241     return SDValue();
5242
5243   // For the transform to be legal, the load must produce only two values
5244   // (the value loaded and the chain).  Don't transform a pre-increment
5245   // load, for example, which produces an extra value.  Otherwise the
5246   // transformation is not equivalent, and the downstream logic to replace
5247   // uses gets things wrong.
5248   if (LN0->getNumValues() > 2)
5249     return SDValue();
5250
5251   // If the load that we're shrinking is an extload and we're not just
5252   // discarding the extension we can't simply shrink the load. Bail.
5253   // TODO: It would be possible to merge the extensions in some cases.
5254   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5255       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5256     return SDValue();
5257
5258   EVT PtrType = N0.getOperand(1).getValueType();
5259
5260   if (PtrType == MVT::Untyped || PtrType.isExtended())
5261     // It's not possible to generate a constant of extended or untyped type.
5262     return SDValue();
5263
5264   // For big endian targets, we need to adjust the offset to the pointer to
5265   // load the correct bytes.
5266   if (TLI.isBigEndian()) {
5267     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5268     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5269     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5270   }
5271
5272   uint64_t PtrOff = ShAmt / 8;
5273   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5274   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5275                                PtrType, LN0->getBasePtr(),
5276                                DAG.getConstant(PtrOff, PtrType));
5277   AddToWorkList(NewPtr.getNode());
5278
5279   SDValue Load;
5280   if (ExtType == ISD::NON_EXTLOAD)
5281     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5282                         LN0->getPointerInfo().getWithOffset(PtrOff),
5283                         LN0->isVolatile(), LN0->isNonTemporal(),
5284                         LN0->isInvariant(), NewAlign);
5285   else
5286     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5287                           LN0->getPointerInfo().getWithOffset(PtrOff),
5288                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5289                           NewAlign);
5290
5291   // Replace the old load's chain with the new load's chain.
5292   WorkListRemover DeadNodes(*this);
5293   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5294
5295   // Shift the result left, if we've swallowed a left shift.
5296   SDValue Result = Load;
5297   if (ShLeftAmt != 0) {
5298     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5299     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5300       ShImmTy = VT;
5301     // If the shift amount is as large as the result size (but, presumably,
5302     // no larger than the source) then the useful bits of the result are
5303     // zero; we can't simply return the shortened shift, because the result
5304     // of that operation is undefined.
5305     if (ShLeftAmt >= VT.getSizeInBits())
5306       Result = DAG.getConstant(0, VT);
5307     else
5308       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5309                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5310   }
5311
5312   // Return the new loaded value.
5313   return Result;
5314 }
5315
5316 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5317   SDValue N0 = N->getOperand(0);
5318   SDValue N1 = N->getOperand(1);
5319   EVT VT = N->getValueType(0);
5320   EVT EVT = cast<VTSDNode>(N1)->getVT();
5321   unsigned VTBits = VT.getScalarType().getSizeInBits();
5322   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5323
5324   // fold (sext_in_reg c1) -> c1
5325   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5326     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5327
5328   // If the input is already sign extended, just drop the extension.
5329   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5330     return N0;
5331
5332   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5333   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5334       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5335     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5336                        N0.getOperand(0), N1);
5337
5338   // fold (sext_in_reg (sext x)) -> (sext x)
5339   // fold (sext_in_reg (aext x)) -> (sext x)
5340   // if x is small enough.
5341   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5342     SDValue N00 = N0.getOperand(0);
5343     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5344         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5345       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5346   }
5347
5348   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5349   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5350     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5351
5352   // fold operands of sext_in_reg based on knowledge that the top bits are not
5353   // demanded.
5354   if (SimplifyDemandedBits(SDValue(N, 0)))
5355     return SDValue(N, 0);
5356
5357   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5358   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5359   SDValue NarrowLoad = ReduceLoadWidth(N);
5360   if (NarrowLoad.getNode())
5361     return NarrowLoad;
5362
5363   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5364   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5365   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5366   if (N0.getOpcode() == ISD::SRL) {
5367     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5368       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5369         // We can turn this into an SRA iff the input to the SRL is already sign
5370         // extended enough.
5371         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5372         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5373           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5374                              N0.getOperand(0), N0.getOperand(1));
5375       }
5376   }
5377
5378   // fold (sext_inreg (extload x)) -> (sextload x)
5379   if (ISD::isEXTLoad(N0.getNode()) &&
5380       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5381       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5382       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5383        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5384     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5385     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5386                                      LN0->getChain(),
5387                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5388                                      EVT,
5389                                      LN0->isVolatile(), LN0->isNonTemporal(),
5390                                      LN0->getAlignment());
5391     CombineTo(N, ExtLoad);
5392     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5393     AddToWorkList(ExtLoad.getNode());
5394     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5395   }
5396   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5397   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5398       N0.hasOneUse() &&
5399       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5400       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5401        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5402     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5403     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5404                                      LN0->getChain(),
5405                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5406                                      EVT,
5407                                      LN0->isVolatile(), LN0->isNonTemporal(),
5408                                      LN0->getAlignment());
5409     CombineTo(N, ExtLoad);
5410     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5411     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5412   }
5413
5414   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5415   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5416     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5417                                        N0.getOperand(1), false);
5418     if (BSwap.getNode() != 0)
5419       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5420                          BSwap, N1);
5421   }
5422
5423   return SDValue();
5424 }
5425
5426 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5427   SDValue N0 = N->getOperand(0);
5428   EVT VT = N->getValueType(0);
5429   bool isLE = TLI.isLittleEndian();
5430
5431   // noop truncate
5432   if (N0.getValueType() == N->getValueType(0))
5433     return N0;
5434   // fold (truncate c1) -> c1
5435   if (isa<ConstantSDNode>(N0))
5436     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5437   // fold (truncate (truncate x)) -> (truncate x)
5438   if (N0.getOpcode() == ISD::TRUNCATE)
5439     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5440   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5441   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5442       N0.getOpcode() == ISD::SIGN_EXTEND ||
5443       N0.getOpcode() == ISD::ANY_EXTEND) {
5444     if (N0.getOperand(0).getValueType().bitsLT(VT))
5445       // if the source is smaller than the dest, we still need an extend
5446       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5447                          N0.getOperand(0));
5448     if (N0.getOperand(0).getValueType().bitsGT(VT))
5449       // if the source is larger than the dest, than we just need the truncate
5450       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5451     // if the source and dest are the same type, we can drop both the extend
5452     // and the truncate.
5453     return N0.getOperand(0);
5454   }
5455
5456   // Fold extract-and-trunc into a narrow extract. For example:
5457   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5458   //   i32 y = TRUNCATE(i64 x)
5459   //        -- becomes --
5460   //   v16i8 b = BITCAST (v2i64 val)
5461   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5462   //
5463   // Note: We only run this optimization after type legalization (which often
5464   // creates this pattern) and before operation legalization after which
5465   // we need to be more careful about the vector instructions that we generate.
5466   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5467       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5468
5469     EVT VecTy = N0.getOperand(0).getValueType();
5470     EVT ExTy = N0.getValueType();
5471     EVT TrTy = N->getValueType(0);
5472
5473     unsigned NumElem = VecTy.getVectorNumElements();
5474     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5475
5476     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5477     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5478
5479     SDValue EltNo = N0->getOperand(1);
5480     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5481       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5482       EVT IndexTy = TLI.getVectorIdxTy();
5483       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5484
5485       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5486                               NVT, N0.getOperand(0));
5487
5488       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5489                          SDLoc(N), TrTy, V,
5490                          DAG.getConstant(Index, IndexTy));
5491     }
5492   }
5493
5494   // Fold a series of buildvector, bitcast, and truncate if possible.
5495   // For example fold
5496   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5497   //   (2xi32 (buildvector x, y)).
5498   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5499       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5500       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5501       N0.getOperand(0).hasOneUse()) {
5502
5503     SDValue BuildVect = N0.getOperand(0);
5504     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5505     EVT TruncVecEltTy = VT.getVectorElementType();
5506
5507     // Check that the element types match.
5508     if (BuildVectEltTy == TruncVecEltTy) {
5509       // Now we only need to compute the offset of the truncated elements.
5510       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5511       unsigned TruncVecNumElts = VT.getVectorNumElements();
5512       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5513
5514       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5515              "Invalid number of elements");
5516
5517       SmallVector<SDValue, 8> Opnds;
5518       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5519         Opnds.push_back(BuildVect.getOperand(i));
5520
5521       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5522                          Opnds.size());
5523     }
5524   }
5525
5526   // See if we can simplify the input to this truncate through knowledge that
5527   // only the low bits are being used.
5528   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5529   // Currently we only perform this optimization on scalars because vectors
5530   // may have different active low bits.
5531   if (!VT.isVector()) {
5532     SDValue Shorter =
5533       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5534                                                VT.getSizeInBits()));
5535     if (Shorter.getNode())
5536       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5537   }
5538   // fold (truncate (load x)) -> (smaller load x)
5539   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5540   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5541     SDValue Reduced = ReduceLoadWidth(N);
5542     if (Reduced.getNode())
5543       return Reduced;
5544   }
5545   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5546   // where ... are all 'undef'.
5547   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5548     SmallVector<EVT, 8> VTs;
5549     SDValue V;
5550     unsigned Idx = 0;
5551     unsigned NumDefs = 0;
5552
5553     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5554       SDValue X = N0.getOperand(i);
5555       if (X.getOpcode() != ISD::UNDEF) {
5556         V = X;
5557         Idx = i;
5558         NumDefs++;
5559       }
5560       // Stop if more than one members are non-undef.
5561       if (NumDefs > 1)
5562         break;
5563       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5564                                      VT.getVectorElementType(),
5565                                      X.getValueType().getVectorNumElements()));
5566     }
5567
5568     if (NumDefs == 0)
5569       return DAG.getUNDEF(VT);
5570
5571     if (NumDefs == 1) {
5572       assert(V.getNode() && "The single defined operand is empty!");
5573       SmallVector<SDValue, 8> Opnds;
5574       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5575         if (i != Idx) {
5576           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5577           continue;
5578         }
5579         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5580         AddToWorkList(NV.getNode());
5581         Opnds.push_back(NV);
5582       }
5583       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5584                          &Opnds[0], Opnds.size());
5585     }
5586   }
5587
5588   // Simplify the operands using demanded-bits information.
5589   if (!VT.isVector() &&
5590       SimplifyDemandedBits(SDValue(N, 0)))
5591     return SDValue(N, 0);
5592
5593   return SDValue();
5594 }
5595
5596 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5597   SDValue Elt = N->getOperand(i);
5598   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5599     return Elt.getNode();
5600   return Elt.getOperand(Elt.getResNo()).getNode();
5601 }
5602
5603 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5604 /// if load locations are consecutive.
5605 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5606   assert(N->getOpcode() == ISD::BUILD_PAIR);
5607
5608   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5609   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5610   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5611       LD1->getPointerInfo().getAddrSpace() !=
5612          LD2->getPointerInfo().getAddrSpace())
5613     return SDValue();
5614   EVT LD1VT = LD1->getValueType(0);
5615
5616   if (ISD::isNON_EXTLoad(LD2) &&
5617       LD2->hasOneUse() &&
5618       // If both are volatile this would reduce the number of volatile loads.
5619       // If one is volatile it might be ok, but play conservative and bail out.
5620       !LD1->isVolatile() &&
5621       !LD2->isVolatile() &&
5622       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5623     unsigned Align = LD1->getAlignment();
5624     unsigned NewAlign = TLI.getDataLayout()->
5625       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5626
5627     if (NewAlign <= Align &&
5628         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5629       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5630                          LD1->getBasePtr(), LD1->getPointerInfo(),
5631                          false, false, false, Align);
5632   }
5633
5634   return SDValue();
5635 }
5636
5637 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5638   SDValue N0 = N->getOperand(0);
5639   EVT VT = N->getValueType(0);
5640
5641   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5642   // Only do this before legalize, since afterward the target may be depending
5643   // on the bitconvert.
5644   // First check to see if this is all constant.
5645   if (!LegalTypes &&
5646       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5647       VT.isVector()) {
5648     bool isSimple = true;
5649     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5650       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5651           N0.getOperand(i).getOpcode() != ISD::Constant &&
5652           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5653         isSimple = false;
5654         break;
5655       }
5656
5657     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5658     assert(!DestEltVT.isVector() &&
5659            "Element type of vector ValueType must not be vector!");
5660     if (isSimple)
5661       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5662   }
5663
5664   // If the input is a constant, let getNode fold it.
5665   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5666     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5667     if (Res.getNode() != N) {
5668       if (!LegalOperations ||
5669           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5670         return Res;
5671
5672       // Folding it resulted in an illegal node, and it's too late to
5673       // do that. Clean up the old node and forego the transformation.
5674       // Ideally this won't happen very often, because instcombine
5675       // and the earlier dagcombine runs (where illegal nodes are
5676       // permitted) should have folded most of them already.
5677       DAG.DeleteNode(Res.getNode());
5678     }
5679   }
5680
5681   // (conv (conv x, t1), t2) -> (conv x, t2)
5682   if (N0.getOpcode() == ISD::BITCAST)
5683     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5684                        N0.getOperand(0));
5685
5686   // fold (conv (load x)) -> (load (conv*)x)
5687   // If the resultant load doesn't need a higher alignment than the original!
5688   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5689       // Do not change the width of a volatile load.
5690       !cast<LoadSDNode>(N0)->isVolatile() &&
5691       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5692     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5693     unsigned Align = TLI.getDataLayout()->
5694       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5695     unsigned OrigAlign = LN0->getAlignment();
5696
5697     if (Align <= OrigAlign) {
5698       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5699                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5700                                  LN0->isVolatile(), LN0->isNonTemporal(),
5701                                  LN0->isInvariant(), OrigAlign);
5702       AddToWorkList(N);
5703       CombineTo(N0.getNode(),
5704                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5705                             N0.getValueType(), Load),
5706                 Load.getValue(1));
5707       return Load;
5708     }
5709   }
5710
5711   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5712   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5713   // This often reduces constant pool loads.
5714   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5715        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5716       N0.getNode()->hasOneUse() && VT.isInteger() &&
5717       !VT.isVector() && !N0.getValueType().isVector()) {
5718     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5719                                   N0.getOperand(0));
5720     AddToWorkList(NewConv.getNode());
5721
5722     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5723     if (N0.getOpcode() == ISD::FNEG)
5724       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5725                          NewConv, DAG.getConstant(SignBit, VT));
5726     assert(N0.getOpcode() == ISD::FABS);
5727     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5728                        NewConv, DAG.getConstant(~SignBit, VT));
5729   }
5730
5731   // fold (bitconvert (fcopysign cst, x)) ->
5732   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5733   // Note that we don't handle (copysign x, cst) because this can always be
5734   // folded to an fneg or fabs.
5735   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5736       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5737       VT.isInteger() && !VT.isVector()) {
5738     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5739     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5740     if (isTypeLegal(IntXVT)) {
5741       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5742                               IntXVT, N0.getOperand(1));
5743       AddToWorkList(X.getNode());
5744
5745       // If X has a different width than the result/lhs, sext it or truncate it.
5746       unsigned VTWidth = VT.getSizeInBits();
5747       if (OrigXWidth < VTWidth) {
5748         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5749         AddToWorkList(X.getNode());
5750       } else if (OrigXWidth > VTWidth) {
5751         // To get the sign bit in the right place, we have to shift it right
5752         // before truncating.
5753         X = DAG.getNode(ISD::SRL, SDLoc(X),
5754                         X.getValueType(), X,
5755                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5756         AddToWorkList(X.getNode());
5757         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5758         AddToWorkList(X.getNode());
5759       }
5760
5761       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5762       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5763                       X, DAG.getConstant(SignBit, VT));
5764       AddToWorkList(X.getNode());
5765
5766       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5767                                 VT, N0.getOperand(0));
5768       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5769                         Cst, DAG.getConstant(~SignBit, VT));
5770       AddToWorkList(Cst.getNode());
5771
5772       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5773     }
5774   }
5775
5776   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5777   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5778     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5779     if (CombineLD.getNode())
5780       return CombineLD;
5781   }
5782
5783   return SDValue();
5784 }
5785
5786 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5787   EVT VT = N->getValueType(0);
5788   return CombineConsecutiveLoads(N, VT);
5789 }
5790
5791 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5792 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5793 /// destination element value type.
5794 SDValue DAGCombiner::
5795 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5796   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5797
5798   // If this is already the right type, we're done.
5799   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5800
5801   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5802   unsigned DstBitSize = DstEltVT.getSizeInBits();
5803
5804   // If this is a conversion of N elements of one type to N elements of another
5805   // type, convert each element.  This handles FP<->INT cases.
5806   if (SrcBitSize == DstBitSize) {
5807     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5808                               BV->getValueType(0).getVectorNumElements());
5809
5810     // Due to the FP element handling below calling this routine recursively,
5811     // we can end up with a scalar-to-vector node here.
5812     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5813       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5814                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5815                                      DstEltVT, BV->getOperand(0)));
5816
5817     SmallVector<SDValue, 8> Ops;
5818     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5819       SDValue Op = BV->getOperand(i);
5820       // If the vector element type is not legal, the BUILD_VECTOR operands
5821       // are promoted and implicitly truncated.  Make that explicit here.
5822       if (Op.getValueType() != SrcEltVT)
5823         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5824       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5825                                 DstEltVT, Op));
5826       AddToWorkList(Ops.back().getNode());
5827     }
5828     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5829                        &Ops[0], Ops.size());
5830   }
5831
5832   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5833   // handle annoying details of growing/shrinking FP values, we convert them to
5834   // int first.
5835   if (SrcEltVT.isFloatingPoint()) {
5836     // Convert the input float vector to a int vector where the elements are the
5837     // same sizes.
5838     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5839     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5840     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5841     SrcEltVT = IntVT;
5842   }
5843
5844   // Now we know the input is an integer vector.  If the output is a FP type,
5845   // convert to integer first, then to FP of the right size.
5846   if (DstEltVT.isFloatingPoint()) {
5847     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5848     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5849     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5850
5851     // Next, convert to FP elements of the same size.
5852     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5853   }
5854
5855   // Okay, we know the src/dst types are both integers of differing types.
5856   // Handling growing first.
5857   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5858   if (SrcBitSize < DstBitSize) {
5859     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5860
5861     SmallVector<SDValue, 8> Ops;
5862     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5863          i += NumInputsPerOutput) {
5864       bool isLE = TLI.isLittleEndian();
5865       APInt NewBits = APInt(DstBitSize, 0);
5866       bool EltIsUndef = true;
5867       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5868         // Shift the previously computed bits over.
5869         NewBits <<= SrcBitSize;
5870         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5871         if (Op.getOpcode() == ISD::UNDEF) continue;
5872         EltIsUndef = false;
5873
5874         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5875                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5876       }
5877
5878       if (EltIsUndef)
5879         Ops.push_back(DAG.getUNDEF(DstEltVT));
5880       else
5881         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5882     }
5883
5884     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5885     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5886                        &Ops[0], Ops.size());
5887   }
5888
5889   // Finally, this must be the case where we are shrinking elements: each input
5890   // turns into multiple outputs.
5891   bool isS2V = ISD::isScalarToVector(BV);
5892   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5893   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5894                             NumOutputsPerInput*BV->getNumOperands());
5895   SmallVector<SDValue, 8> Ops;
5896
5897   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5898     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5899       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5900         Ops.push_back(DAG.getUNDEF(DstEltVT));
5901       continue;
5902     }
5903
5904     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5905                   getAPIntValue().zextOrTrunc(SrcBitSize);
5906
5907     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5908       APInt ThisVal = OpVal.trunc(DstBitSize);
5909       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5910       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5911         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5912         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5913                            Ops[0]);
5914       OpVal = OpVal.lshr(DstBitSize);
5915     }
5916
5917     // For big endian targets, swap the order of the pieces of each element.
5918     if (TLI.isBigEndian())
5919       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5920   }
5921
5922   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5923                      &Ops[0], Ops.size());
5924 }
5925
5926 SDValue DAGCombiner::visitFADD(SDNode *N) {
5927   SDValue N0 = N->getOperand(0);
5928   SDValue N1 = N->getOperand(1);
5929   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5930   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5931   EVT VT = N->getValueType(0);
5932
5933   // fold vector ops
5934   if (VT.isVector()) {
5935     SDValue FoldedVOp = SimplifyVBinOp(N);
5936     if (FoldedVOp.getNode()) return FoldedVOp;
5937   }
5938
5939   // fold (fadd c1, c2) -> c1 + c2
5940   if (N0CFP && N1CFP)
5941     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5942   // canonicalize constant to RHS
5943   if (N0CFP && !N1CFP)
5944     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5945   // fold (fadd A, 0) -> A
5946   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5947       N1CFP->getValueAPF().isZero())
5948     return N0;
5949   // fold (fadd A, (fneg B)) -> (fsub A, B)
5950   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5951     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5952     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5953                        GetNegatedExpression(N1, DAG, LegalOperations));
5954   // fold (fadd (fneg A), B) -> (fsub B, A)
5955   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5956     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5957     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5958                        GetNegatedExpression(N0, DAG, LegalOperations));
5959
5960   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5961   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5962       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5963       isa<ConstantFPSDNode>(N0.getOperand(1)))
5964     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
5965                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
5966                                    N0.getOperand(1), N1));
5967
5968   // No FP constant should be created after legalization as Instruction
5969   // Selection pass has hard time in dealing with FP constant.
5970   //
5971   // We don't need test this condition for transformation like following, as
5972   // the DAG being transformed implies it is legal to take FP constant as
5973   // operand.
5974   //
5975   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5976   //
5977   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5978
5979   // If allow, fold (fadd (fneg x), x) -> 0.0
5980   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5981       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
5982     return DAG.getConstantFP(0.0, VT);
5983
5984     // If allow, fold (fadd x, (fneg x)) -> 0.0
5985   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5986       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
5987     return DAG.getConstantFP(0.0, VT);
5988
5989   // In unsafe math mode, we can fold chains of FADD's of the same value
5990   // into multiplications.  This transform is not safe in general because
5991   // we are reducing the number of rounding steps.
5992   if (DAG.getTarget().Options.UnsafeFPMath &&
5993       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5994       !N0CFP && !N1CFP) {
5995     if (N0.getOpcode() == ISD::FMUL) {
5996       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5997       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5998
5999       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6000       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6001         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6002                                      SDValue(CFP00, 0),
6003                                      DAG.getConstantFP(1.0, VT));
6004         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6005                            N1, NewCFP);
6006       }
6007
6008       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6009       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6010         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6011                                      SDValue(CFP01, 0),
6012                                      DAG.getConstantFP(1.0, VT));
6013         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6014                            N1, NewCFP);
6015       }
6016
6017       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6018       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6019           N1.getOperand(0) == N1.getOperand(1) &&
6020           N0.getOperand(1) == N1.getOperand(0)) {
6021         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6022                                      SDValue(CFP00, 0),
6023                                      DAG.getConstantFP(2.0, VT));
6024         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6025                            N0.getOperand(1), NewCFP);
6026       }
6027
6028       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6029       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6030           N1.getOperand(0) == N1.getOperand(1) &&
6031           N0.getOperand(0) == N1.getOperand(0)) {
6032         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6033                                      SDValue(CFP01, 0),
6034                                      DAG.getConstantFP(2.0, VT));
6035         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6036                            N0.getOperand(0), NewCFP);
6037       }
6038     }
6039
6040     if (N1.getOpcode() == ISD::FMUL) {
6041       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6042       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6043
6044       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6045       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6046         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6047                                      SDValue(CFP10, 0),
6048                                      DAG.getConstantFP(1.0, VT));
6049         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6050                            N0, NewCFP);
6051       }
6052
6053       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6054       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6055         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6056                                      SDValue(CFP11, 0),
6057                                      DAG.getConstantFP(1.0, VT));
6058         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6059                            N0, NewCFP);
6060       }
6061
6062
6063       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6064       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6065           N0.getOperand(0) == N0.getOperand(1) &&
6066           N1.getOperand(1) == N0.getOperand(0)) {
6067         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6068                                      SDValue(CFP10, 0),
6069                                      DAG.getConstantFP(2.0, VT));
6070         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6071                            N1.getOperand(1), NewCFP);
6072       }
6073
6074       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6075       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6076           N0.getOperand(0) == N0.getOperand(1) &&
6077           N1.getOperand(0) == N0.getOperand(0)) {
6078         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6079                                      SDValue(CFP11, 0),
6080                                      DAG.getConstantFP(2.0, VT));
6081         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6082                            N1.getOperand(0), NewCFP);
6083       }
6084     }
6085
6086     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6087       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6088       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6089       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6090           (N0.getOperand(0) == N1))
6091         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6092                            N1, DAG.getConstantFP(3.0, VT));
6093     }
6094
6095     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6096       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6097       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6098       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6099           N1.getOperand(0) == N0)
6100         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6101                            N0, DAG.getConstantFP(3.0, VT));
6102     }
6103
6104     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6105     if (AllowNewFpConst &&
6106         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6107         N0.getOperand(0) == N0.getOperand(1) &&
6108         N1.getOperand(0) == N1.getOperand(1) &&
6109         N0.getOperand(0) == N1.getOperand(0))
6110       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6111                          N0.getOperand(0),
6112                          DAG.getConstantFP(4.0, VT));
6113   }
6114
6115   // FADD -> FMA combines:
6116   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6117        DAG.getTarget().Options.UnsafeFPMath) &&
6118       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6119       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6120
6121     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6122     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6123       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6124                          N0.getOperand(0), N0.getOperand(1), N1);
6125
6126     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6127     // Note: Commutes FADD operands.
6128     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6129       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6130                          N1.getOperand(0), N1.getOperand(1), N0);
6131   }
6132
6133   return SDValue();
6134 }
6135
6136 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6137   SDValue N0 = N->getOperand(0);
6138   SDValue N1 = N->getOperand(1);
6139   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6140   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6141   EVT VT = N->getValueType(0);
6142   SDLoc dl(N);
6143
6144   // fold vector ops
6145   if (VT.isVector()) {
6146     SDValue FoldedVOp = SimplifyVBinOp(N);
6147     if (FoldedVOp.getNode()) return FoldedVOp;
6148   }
6149
6150   // fold (fsub c1, c2) -> c1-c2
6151   if (N0CFP && N1CFP)
6152     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6153   // fold (fsub A, 0) -> A
6154   if (DAG.getTarget().Options.UnsafeFPMath &&
6155       N1CFP && N1CFP->getValueAPF().isZero())
6156     return N0;
6157   // fold (fsub 0, B) -> -B
6158   if (DAG.getTarget().Options.UnsafeFPMath &&
6159       N0CFP && N0CFP->getValueAPF().isZero()) {
6160     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6161       return GetNegatedExpression(N1, DAG, LegalOperations);
6162     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6163       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6164   }
6165   // fold (fsub A, (fneg B)) -> (fadd A, B)
6166   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6167     return DAG.getNode(ISD::FADD, dl, VT, N0,
6168                        GetNegatedExpression(N1, DAG, LegalOperations));
6169
6170   // If 'unsafe math' is enabled, fold
6171   //    (fsub x, x) -> 0.0 &
6172   //    (fsub x, (fadd x, y)) -> (fneg y) &
6173   //    (fsub x, (fadd y, x)) -> (fneg y)
6174   if (DAG.getTarget().Options.UnsafeFPMath) {
6175     if (N0 == N1)
6176       return DAG.getConstantFP(0.0f, VT);
6177
6178     if (N1.getOpcode() == ISD::FADD) {
6179       SDValue N10 = N1->getOperand(0);
6180       SDValue N11 = N1->getOperand(1);
6181
6182       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6183                                           &DAG.getTarget().Options))
6184         return GetNegatedExpression(N11, DAG, LegalOperations);
6185
6186       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6187                                           &DAG.getTarget().Options))
6188         return GetNegatedExpression(N10, DAG, LegalOperations);
6189     }
6190   }
6191
6192   // FSUB -> FMA combines:
6193   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6194        DAG.getTarget().Options.UnsafeFPMath) &&
6195       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6196       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6197
6198     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6199     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6200       return DAG.getNode(ISD::FMA, dl, VT,
6201                          N0.getOperand(0), N0.getOperand(1),
6202                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6203
6204     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6205     // Note: Commutes FSUB operands.
6206     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6207       return DAG.getNode(ISD::FMA, dl, VT,
6208                          DAG.getNode(ISD::FNEG, dl, VT,
6209                          N1.getOperand(0)),
6210                          N1.getOperand(1), N0);
6211
6212     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6213     if (N0.getOpcode() == ISD::FNEG &&
6214         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6215         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6216       SDValue N00 = N0.getOperand(0).getOperand(0);
6217       SDValue N01 = N0.getOperand(0).getOperand(1);
6218       return DAG.getNode(ISD::FMA, dl, VT,
6219                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6220                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6221     }
6222   }
6223
6224   return SDValue();
6225 }
6226
6227 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6228   SDValue N0 = N->getOperand(0);
6229   SDValue N1 = N->getOperand(1);
6230   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6231   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6232   EVT VT = N->getValueType(0);
6233   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6234
6235   // fold vector ops
6236   if (VT.isVector()) {
6237     SDValue FoldedVOp = SimplifyVBinOp(N);
6238     if (FoldedVOp.getNode()) return FoldedVOp;
6239   }
6240
6241   // fold (fmul c1, c2) -> c1*c2
6242   if (N0CFP && N1CFP)
6243     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6244   // canonicalize constant to RHS
6245   if (N0CFP && !N1CFP)
6246     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6247   // fold (fmul A, 0) -> 0
6248   if (DAG.getTarget().Options.UnsafeFPMath &&
6249       N1CFP && N1CFP->getValueAPF().isZero())
6250     return N1;
6251   // fold (fmul A, 0) -> 0, vector edition.
6252   if (DAG.getTarget().Options.UnsafeFPMath &&
6253       ISD::isBuildVectorAllZeros(N1.getNode()))
6254     return N1;
6255   // fold (fmul A, 1.0) -> A
6256   if (N1CFP && N1CFP->isExactlyValue(1.0))
6257     return N0;
6258   // fold (fmul X, 2.0) -> (fadd X, X)
6259   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6260     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6261   // fold (fmul X, -1.0) -> (fneg X)
6262   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6263     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6264       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6265
6266   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6267   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6268                                        &DAG.getTarget().Options)) {
6269     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6270                                          &DAG.getTarget().Options)) {
6271       // Both can be negated for free, check to see if at least one is cheaper
6272       // negated.
6273       if (LHSNeg == 2 || RHSNeg == 2)
6274         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6275                            GetNegatedExpression(N0, DAG, LegalOperations),
6276                            GetNegatedExpression(N1, DAG, LegalOperations));
6277     }
6278   }
6279
6280   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6281   if (DAG.getTarget().Options.UnsafeFPMath &&
6282       N1CFP && N0.getOpcode() == ISD::FMUL &&
6283       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6284     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6285                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6286                                    N0.getOperand(1), N1));
6287
6288   return SDValue();
6289 }
6290
6291 SDValue DAGCombiner::visitFMA(SDNode *N) {
6292   SDValue N0 = N->getOperand(0);
6293   SDValue N1 = N->getOperand(1);
6294   SDValue N2 = N->getOperand(2);
6295   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6296   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6297   EVT VT = N->getValueType(0);
6298   SDLoc dl(N);
6299
6300   if (DAG.getTarget().Options.UnsafeFPMath) {
6301     if (N0CFP && N0CFP->isZero())
6302       return N2;
6303     if (N1CFP && N1CFP->isZero())
6304       return N2;
6305   }
6306   if (N0CFP && N0CFP->isExactlyValue(1.0))
6307     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6308   if (N1CFP && N1CFP->isExactlyValue(1.0))
6309     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6310
6311   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6312   if (N0CFP && !N1CFP)
6313     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6314
6315   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6316   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6317       N2.getOpcode() == ISD::FMUL &&
6318       N0 == N2.getOperand(0) &&
6319       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6320     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6321                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6322   }
6323
6324
6325   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6326   if (DAG.getTarget().Options.UnsafeFPMath &&
6327       N0.getOpcode() == ISD::FMUL && N1CFP &&
6328       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6329     return DAG.getNode(ISD::FMA, dl, VT,
6330                        N0.getOperand(0),
6331                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6332                        N2);
6333   }
6334
6335   // (fma x, 1, y) -> (fadd x, y)
6336   // (fma x, -1, y) -> (fadd (fneg x), y)
6337   if (N1CFP) {
6338     if (N1CFP->isExactlyValue(1.0))
6339       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6340
6341     if (N1CFP->isExactlyValue(-1.0) &&
6342         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6343       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6344       AddToWorkList(RHSNeg.getNode());
6345       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6346     }
6347   }
6348
6349   // (fma x, c, x) -> (fmul x, (c+1))
6350   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6351     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6352                        DAG.getNode(ISD::FADD, dl, VT,
6353                                    N1, DAG.getConstantFP(1.0, VT)));
6354
6355   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6356   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6357       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6358     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6359                        DAG.getNode(ISD::FADD, dl, VT,
6360                                    N1, DAG.getConstantFP(-1.0, VT)));
6361
6362
6363   return SDValue();
6364 }
6365
6366 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6367   SDValue N0 = N->getOperand(0);
6368   SDValue N1 = N->getOperand(1);
6369   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6370   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6371   EVT VT = N->getValueType(0);
6372   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6373
6374   // fold vector ops
6375   if (VT.isVector()) {
6376     SDValue FoldedVOp = SimplifyVBinOp(N);
6377     if (FoldedVOp.getNode()) return FoldedVOp;
6378   }
6379
6380   // fold (fdiv c1, c2) -> c1/c2
6381   if (N0CFP && N1CFP)
6382     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6383
6384   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6385   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6386     // Compute the reciprocal 1.0 / c2.
6387     APFloat N1APF = N1CFP->getValueAPF();
6388     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6389     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6390     // Only do the transform if the reciprocal is a legal fp immediate that
6391     // isn't too nasty (eg NaN, denormal, ...).
6392     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6393         (!LegalOperations ||
6394          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6395          // backend)... we should handle this gracefully after Legalize.
6396          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6397          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6398          TLI.isFPImmLegal(Recip, VT)))
6399       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6400                          DAG.getConstantFP(Recip, VT));
6401   }
6402
6403   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6404   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6405                                        &DAG.getTarget().Options)) {
6406     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6407                                          &DAG.getTarget().Options)) {
6408       // Both can be negated for free, check to see if at least one is cheaper
6409       // negated.
6410       if (LHSNeg == 2 || RHSNeg == 2)
6411         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6412                            GetNegatedExpression(N0, DAG, LegalOperations),
6413                            GetNegatedExpression(N1, DAG, LegalOperations));
6414     }
6415   }
6416
6417   return SDValue();
6418 }
6419
6420 SDValue DAGCombiner::visitFREM(SDNode *N) {
6421   SDValue N0 = N->getOperand(0);
6422   SDValue N1 = N->getOperand(1);
6423   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6424   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6425   EVT VT = N->getValueType(0);
6426
6427   // fold (frem c1, c2) -> fmod(c1,c2)
6428   if (N0CFP && N1CFP)
6429     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6430
6431   return SDValue();
6432 }
6433
6434 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6435   SDValue N0 = N->getOperand(0);
6436   SDValue N1 = N->getOperand(1);
6437   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6438   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6439   EVT VT = N->getValueType(0);
6440
6441   if (N0CFP && N1CFP)  // Constant fold
6442     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6443
6444   if (N1CFP) {
6445     const APFloat& V = N1CFP->getValueAPF();
6446     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6447     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6448     if (!V.isNegative()) {
6449       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6450         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6451     } else {
6452       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6453         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6454                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6455     }
6456   }
6457
6458   // copysign(fabs(x), y) -> copysign(x, y)
6459   // copysign(fneg(x), y) -> copysign(x, y)
6460   // copysign(copysign(x,z), y) -> copysign(x, y)
6461   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6462       N0.getOpcode() == ISD::FCOPYSIGN)
6463     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6464                        N0.getOperand(0), N1);
6465
6466   // copysign(x, abs(y)) -> abs(x)
6467   if (N1.getOpcode() == ISD::FABS)
6468     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6469
6470   // copysign(x, copysign(y,z)) -> copysign(x, z)
6471   if (N1.getOpcode() == ISD::FCOPYSIGN)
6472     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6473                        N0, N1.getOperand(1));
6474
6475   // copysign(x, fp_extend(y)) -> copysign(x, y)
6476   // copysign(x, fp_round(y)) -> copysign(x, y)
6477   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6478     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6479                        N0, N1.getOperand(0));
6480
6481   return SDValue();
6482 }
6483
6484 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6485   SDValue N0 = N->getOperand(0);
6486   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6487   EVT VT = N->getValueType(0);
6488   EVT OpVT = N0.getValueType();
6489
6490   // fold (sint_to_fp c1) -> c1fp
6491   if (N0C &&
6492       // ...but only if the target supports immediate floating-point values
6493       (!LegalOperations ||
6494        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6495     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6496
6497   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6498   // but UINT_TO_FP is legal on this target, try to convert.
6499   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6500       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6501     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6502     if (DAG.SignBitIsZero(N0))
6503       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6504   }
6505
6506   // The next optimizations are desireable only if SELECT_CC can be lowered.
6507   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6508   // having to say they don't support SELECT_CC on every type the DAG knows
6509   // about, since there is no way to mark an opcode illegal at all value types
6510   // (See also visitSELECT)
6511   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6512     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6513     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6514         !VT.isVector() &&
6515         (!LegalOperations ||
6516          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6517       SDValue Ops[] =
6518         { N0.getOperand(0), N0.getOperand(1),
6519           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6520           N0.getOperand(2) };
6521       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6522     }
6523
6524     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6525     //      (select_cc x, y, 1.0, 0.0,, cc)
6526     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6527         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6528         (!LegalOperations ||
6529          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6530       SDValue Ops[] =
6531         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6532           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6533           N0.getOperand(0).getOperand(2) };
6534       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6535     }
6536   }
6537
6538   return SDValue();
6539 }
6540
6541 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6542   SDValue N0 = N->getOperand(0);
6543   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6544   EVT VT = N->getValueType(0);
6545   EVT OpVT = N0.getValueType();
6546
6547   // fold (uint_to_fp c1) -> c1fp
6548   if (N0C &&
6549       // ...but only if the target supports immediate floating-point values
6550       (!LegalOperations ||
6551        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6552     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6553
6554   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6555   // but SINT_TO_FP is legal on this target, try to convert.
6556   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6557       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6558     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6559     if (DAG.SignBitIsZero(N0))
6560       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6561   }
6562
6563   // The next optimizations are desireable only if SELECT_CC can be lowered.
6564   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6565   // having to say they don't support SELECT_CC on every type the DAG knows
6566   // about, since there is no way to mark an opcode illegal at all value types
6567   // (See also visitSELECT)
6568   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6569     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6570
6571     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6572         (!LegalOperations ||
6573          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6574       SDValue Ops[] =
6575         { N0.getOperand(0), N0.getOperand(1),
6576           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6577           N0.getOperand(2) };
6578       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6579     }
6580   }
6581
6582   return SDValue();
6583 }
6584
6585 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6586   SDValue N0 = N->getOperand(0);
6587   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6588   EVT VT = N->getValueType(0);
6589
6590   // fold (fp_to_sint c1fp) -> c1
6591   if (N0CFP)
6592     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6593
6594   return SDValue();
6595 }
6596
6597 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6598   SDValue N0 = N->getOperand(0);
6599   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6600   EVT VT = N->getValueType(0);
6601
6602   // fold (fp_to_uint c1fp) -> c1
6603   if (N0CFP)
6604     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6605
6606   return SDValue();
6607 }
6608
6609 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6610   SDValue N0 = N->getOperand(0);
6611   SDValue N1 = N->getOperand(1);
6612   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6613   EVT VT = N->getValueType(0);
6614
6615   // fold (fp_round c1fp) -> c1fp
6616   if (N0CFP)
6617     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6618
6619   // fold (fp_round (fp_extend x)) -> x
6620   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6621     return N0.getOperand(0);
6622
6623   // fold (fp_round (fp_round x)) -> (fp_round x)
6624   if (N0.getOpcode() == ISD::FP_ROUND) {
6625     // This is a value preserving truncation if both round's are.
6626     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6627                    N0.getNode()->getConstantOperandVal(1) == 1;
6628     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6629                        DAG.getIntPtrConstant(IsTrunc));
6630   }
6631
6632   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6633   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6634     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6635                               N0.getOperand(0), N1);
6636     AddToWorkList(Tmp.getNode());
6637     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6638                        Tmp, N0.getOperand(1));
6639   }
6640
6641   return SDValue();
6642 }
6643
6644 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6645   SDValue N0 = N->getOperand(0);
6646   EVT VT = N->getValueType(0);
6647   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6648   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6649
6650   // fold (fp_round_inreg c1fp) -> c1fp
6651   if (N0CFP && isTypeLegal(EVT)) {
6652     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6653     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6654   }
6655
6656   return SDValue();
6657 }
6658
6659 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6660   SDValue N0 = N->getOperand(0);
6661   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6662   EVT VT = N->getValueType(0);
6663
6664   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6665   if (N->hasOneUse() &&
6666       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6667     return SDValue();
6668
6669   // fold (fp_extend c1fp) -> c1fp
6670   if (N0CFP)
6671     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6672
6673   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6674   // value of X.
6675   if (N0.getOpcode() == ISD::FP_ROUND
6676       && N0.getNode()->getConstantOperandVal(1) == 1) {
6677     SDValue In = N0.getOperand(0);
6678     if (In.getValueType() == VT) return In;
6679     if (VT.bitsLT(In.getValueType()))
6680       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6681                          In, N0.getOperand(1));
6682     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6683   }
6684
6685   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6686   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6687       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6688        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6689     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6690     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6691                                      LN0->getChain(),
6692                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6693                                      N0.getValueType(),
6694                                      LN0->isVolatile(), LN0->isNonTemporal(),
6695                                      LN0->getAlignment());
6696     CombineTo(N, ExtLoad);
6697     CombineTo(N0.getNode(),
6698               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6699                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6700               ExtLoad.getValue(1));
6701     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6702   }
6703
6704   return SDValue();
6705 }
6706
6707 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6708   SDValue N0 = N->getOperand(0);
6709   EVT VT = N->getValueType(0);
6710
6711   if (VT.isVector()) {
6712     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6713     if (FoldedVOp.getNode()) return FoldedVOp;
6714   }
6715
6716   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6717                          &DAG.getTarget().Options))
6718     return GetNegatedExpression(N0, DAG, LegalOperations);
6719
6720   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6721   // constant pool values.
6722   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6723       !VT.isVector() &&
6724       N0.getNode()->hasOneUse() &&
6725       N0.getOperand(0).getValueType().isInteger()) {
6726     SDValue Int = N0.getOperand(0);
6727     EVT IntVT = Int.getValueType();
6728     if (IntVT.isInteger() && !IntVT.isVector()) {
6729       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6730               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6731       AddToWorkList(Int.getNode());
6732       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6733                          VT, Int);
6734     }
6735   }
6736
6737   // (fneg (fmul c, x)) -> (fmul -c, x)
6738   if (N0.getOpcode() == ISD::FMUL) {
6739     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6740     if (CFP1)
6741       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6742                          N0.getOperand(0),
6743                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6744                                      N0.getOperand(1)));
6745   }
6746
6747   return SDValue();
6748 }
6749
6750 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6751   SDValue N0 = N->getOperand(0);
6752   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6753   EVT VT = N->getValueType(0);
6754
6755   // fold (fceil c1) -> fceil(c1)
6756   if (N0CFP)
6757     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6758
6759   return SDValue();
6760 }
6761
6762 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6763   SDValue N0 = N->getOperand(0);
6764   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6765   EVT VT = N->getValueType(0);
6766
6767   // fold (ftrunc c1) -> ftrunc(c1)
6768   if (N0CFP)
6769     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6770
6771   return SDValue();
6772 }
6773
6774 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6775   SDValue N0 = N->getOperand(0);
6776   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6777   EVT VT = N->getValueType(0);
6778
6779   // fold (ffloor c1) -> ffloor(c1)
6780   if (N0CFP)
6781     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6782
6783   return SDValue();
6784 }
6785
6786 SDValue DAGCombiner::visitFABS(SDNode *N) {
6787   SDValue N0 = N->getOperand(0);
6788   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6789   EVT VT = N->getValueType(0);
6790
6791   if (VT.isVector()) {
6792     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6793     if (FoldedVOp.getNode()) return FoldedVOp;
6794   }
6795
6796   // fold (fabs c1) -> fabs(c1)
6797   if (N0CFP)
6798     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6799   // fold (fabs (fabs x)) -> (fabs x)
6800   if (N0.getOpcode() == ISD::FABS)
6801     return N->getOperand(0);
6802   // fold (fabs (fneg x)) -> (fabs x)
6803   // fold (fabs (fcopysign x, y)) -> (fabs x)
6804   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6805     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6806
6807   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6808   // constant pool values.
6809   if (!TLI.isFAbsFree(VT) &&
6810       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6811       N0.getOperand(0).getValueType().isInteger() &&
6812       !N0.getOperand(0).getValueType().isVector()) {
6813     SDValue Int = N0.getOperand(0);
6814     EVT IntVT = Int.getValueType();
6815     if (IntVT.isInteger() && !IntVT.isVector()) {
6816       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6817              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6818       AddToWorkList(Int.getNode());
6819       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6820                          N->getValueType(0), Int);
6821     }
6822   }
6823
6824   return SDValue();
6825 }
6826
6827 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6828   SDValue Chain = N->getOperand(0);
6829   SDValue N1 = N->getOperand(1);
6830   SDValue N2 = N->getOperand(2);
6831
6832   // If N is a constant we could fold this into a fallthrough or unconditional
6833   // branch. However that doesn't happen very often in normal code, because
6834   // Instcombine/SimplifyCFG should have handled the available opportunities.
6835   // If we did this folding here, it would be necessary to update the
6836   // MachineBasicBlock CFG, which is awkward.
6837
6838   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6839   // on the target.
6840   if (N1.getOpcode() == ISD::SETCC &&
6841       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6842                                    N1.getOperand(0).getValueType())) {
6843     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6844                        Chain, N1.getOperand(2),
6845                        N1.getOperand(0), N1.getOperand(1), N2);
6846   }
6847
6848   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6849       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6850        (N1.getOperand(0).hasOneUse() &&
6851         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6852     SDNode *Trunc = 0;
6853     if (N1.getOpcode() == ISD::TRUNCATE) {
6854       // Look pass the truncate.
6855       Trunc = N1.getNode();
6856       N1 = N1.getOperand(0);
6857     }
6858
6859     // Match this pattern so that we can generate simpler code:
6860     //
6861     //   %a = ...
6862     //   %b = and i32 %a, 2
6863     //   %c = srl i32 %b, 1
6864     //   brcond i32 %c ...
6865     //
6866     // into
6867     //
6868     //   %a = ...
6869     //   %b = and i32 %a, 2
6870     //   %c = setcc eq %b, 0
6871     //   brcond %c ...
6872     //
6873     // This applies only when the AND constant value has one bit set and the
6874     // SRL constant is equal to the log2 of the AND constant. The back-end is
6875     // smart enough to convert the result into a TEST/JMP sequence.
6876     SDValue Op0 = N1.getOperand(0);
6877     SDValue Op1 = N1.getOperand(1);
6878
6879     if (Op0.getOpcode() == ISD::AND &&
6880         Op1.getOpcode() == ISD::Constant) {
6881       SDValue AndOp1 = Op0.getOperand(1);
6882
6883       if (AndOp1.getOpcode() == ISD::Constant) {
6884         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6885
6886         if (AndConst.isPowerOf2() &&
6887             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6888           SDValue SetCC =
6889             DAG.getSetCC(SDLoc(N),
6890                          getSetCCResultType(Op0.getValueType()),
6891                          Op0, DAG.getConstant(0, Op0.getValueType()),
6892                          ISD::SETNE);
6893
6894           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6895                                           MVT::Other, Chain, SetCC, N2);
6896           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6897           // will convert it back to (X & C1) >> C2.
6898           CombineTo(N, NewBRCond, false);
6899           // Truncate is dead.
6900           if (Trunc) {
6901             removeFromWorkList(Trunc);
6902             DAG.DeleteNode(Trunc);
6903           }
6904           // Replace the uses of SRL with SETCC
6905           WorkListRemover DeadNodes(*this);
6906           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6907           removeFromWorkList(N1.getNode());
6908           DAG.DeleteNode(N1.getNode());
6909           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6910         }
6911       }
6912     }
6913
6914     if (Trunc)
6915       // Restore N1 if the above transformation doesn't match.
6916       N1 = N->getOperand(1);
6917   }
6918
6919   // Transform br(xor(x, y)) -> br(x != y)
6920   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6921   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6922     SDNode *TheXor = N1.getNode();
6923     SDValue Op0 = TheXor->getOperand(0);
6924     SDValue Op1 = TheXor->getOperand(1);
6925     if (Op0.getOpcode() == Op1.getOpcode()) {
6926       // Avoid missing important xor optimizations.
6927       SDValue Tmp = visitXOR(TheXor);
6928       if (Tmp.getNode()) {
6929         if (Tmp.getNode() != TheXor) {
6930           DEBUG(dbgs() << "\nReplacing.8 ";
6931                 TheXor->dump(&DAG);
6932                 dbgs() << "\nWith: ";
6933                 Tmp.getNode()->dump(&DAG);
6934                 dbgs() << '\n');
6935           WorkListRemover DeadNodes(*this);
6936           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6937           removeFromWorkList(TheXor);
6938           DAG.DeleteNode(TheXor);
6939           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6940                              MVT::Other, Chain, Tmp, N2);
6941         }
6942
6943         // visitXOR has changed XOR's operands or replaced the XOR completely,
6944         // bail out.
6945         return SDValue(N, 0);
6946       }
6947     }
6948
6949     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6950       bool Equal = false;
6951       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6952         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6953             Op0.getOpcode() == ISD::XOR) {
6954           TheXor = Op0.getNode();
6955           Equal = true;
6956         }
6957
6958       EVT SetCCVT = N1.getValueType();
6959       if (LegalTypes)
6960         SetCCVT = getSetCCResultType(SetCCVT);
6961       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
6962                                    SetCCVT,
6963                                    Op0, Op1,
6964                                    Equal ? ISD::SETEQ : ISD::SETNE);
6965       // Replace the uses of XOR with SETCC
6966       WorkListRemover DeadNodes(*this);
6967       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6968       removeFromWorkList(N1.getNode());
6969       DAG.DeleteNode(N1.getNode());
6970       return DAG.getNode(ISD::BRCOND, SDLoc(N),
6971                          MVT::Other, Chain, SetCC, N2);
6972     }
6973   }
6974
6975   return SDValue();
6976 }
6977
6978 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6979 //
6980 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6981   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6982   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6983
6984   // If N is a constant we could fold this into a fallthrough or unconditional
6985   // branch. However that doesn't happen very often in normal code, because
6986   // Instcombine/SimplifyCFG should have handled the available opportunities.
6987   // If we did this folding here, it would be necessary to update the
6988   // MachineBasicBlock CFG, which is awkward.
6989
6990   // Use SimplifySetCC to simplify SETCC's.
6991   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
6992                                CondLHS, CondRHS, CC->get(), SDLoc(N),
6993                                false);
6994   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6995
6996   // fold to a simpler setcc
6997   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6998     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6999                        N->getOperand(0), Simp.getOperand(2),
7000                        Simp.getOperand(0), Simp.getOperand(1),
7001                        N->getOperand(4));
7002
7003   return SDValue();
7004 }
7005
7006 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7007 /// uses N as its base pointer and that N may be folded in the load / store
7008 /// addressing mode.
7009 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7010                                     SelectionDAG &DAG,
7011                                     const TargetLowering &TLI) {
7012   EVT VT;
7013   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7014     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7015       return false;
7016     VT = Use->getValueType(0);
7017   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7018     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7019       return false;
7020     VT = ST->getValue().getValueType();
7021   } else
7022     return false;
7023
7024   TargetLowering::AddrMode AM;
7025   if (N->getOpcode() == ISD::ADD) {
7026     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7027     if (Offset)
7028       // [reg +/- imm]
7029       AM.BaseOffs = Offset->getSExtValue();
7030     else
7031       // [reg +/- reg]
7032       AM.Scale = 1;
7033   } else if (N->getOpcode() == ISD::SUB) {
7034     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7035     if (Offset)
7036       // [reg +/- imm]
7037       AM.BaseOffs = -Offset->getSExtValue();
7038     else
7039       // [reg +/- reg]
7040       AM.Scale = 1;
7041   } else
7042     return false;
7043
7044   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7045 }
7046
7047 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7048 /// pre-indexed load / store when the base pointer is an add or subtract
7049 /// and it has other uses besides the load / store. After the
7050 /// transformation, the new indexed load / store has effectively folded
7051 /// the add / subtract in and all of its other uses are redirected to the
7052 /// new load / store.
7053 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7054   if (Level < AfterLegalizeDAG)
7055     return false;
7056
7057   bool isLoad = true;
7058   SDValue Ptr;
7059   EVT VT;
7060   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7061     if (LD->isIndexed())
7062       return false;
7063     VT = LD->getMemoryVT();
7064     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7065         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7066       return false;
7067     Ptr = LD->getBasePtr();
7068   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7069     if (ST->isIndexed())
7070       return false;
7071     VT = ST->getMemoryVT();
7072     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7073         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7074       return false;
7075     Ptr = ST->getBasePtr();
7076     isLoad = false;
7077   } else {
7078     return false;
7079   }
7080
7081   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7082   // out.  There is no reason to make this a preinc/predec.
7083   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7084       Ptr.getNode()->hasOneUse())
7085     return false;
7086
7087   // Ask the target to do addressing mode selection.
7088   SDValue BasePtr;
7089   SDValue Offset;
7090   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7091   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7092     return false;
7093
7094   // Backends without true r+i pre-indexed forms may need to pass a
7095   // constant base with a variable offset so that constant coercion
7096   // will work with the patterns in canonical form.
7097   bool Swapped = false;
7098   if (isa<ConstantSDNode>(BasePtr)) {
7099     std::swap(BasePtr, Offset);
7100     Swapped = true;
7101   }
7102
7103   // Don't create a indexed load / store with zero offset.
7104   if (isa<ConstantSDNode>(Offset) &&
7105       cast<ConstantSDNode>(Offset)->isNullValue())
7106     return false;
7107
7108   // Try turning it into a pre-indexed load / store except when:
7109   // 1) The new base ptr is a frame index.
7110   // 2) If N is a store and the new base ptr is either the same as or is a
7111   //    predecessor of the value being stored.
7112   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7113   //    that would create a cycle.
7114   // 4) All uses are load / store ops that use it as old base ptr.
7115
7116   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7117   // (plus the implicit offset) to a register to preinc anyway.
7118   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7119     return false;
7120
7121   // Check #2.
7122   if (!isLoad) {
7123     SDValue Val = cast<StoreSDNode>(N)->getValue();
7124     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7125       return false;
7126   }
7127
7128   // If the offset is a constant, there may be other adds of constants that
7129   // can be folded with this one. We should do this to avoid having to keep
7130   // a copy of the original base pointer.
7131   SmallVector<SDNode *, 16> OtherUses;
7132   if (isa<ConstantSDNode>(Offset))
7133     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7134          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7135       SDNode *Use = *I;
7136       if (Use == Ptr.getNode())
7137         continue;
7138
7139       if (Use->isPredecessorOf(N))
7140         continue;
7141
7142       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7143         OtherUses.clear();
7144         break;
7145       }
7146
7147       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7148       if (Op1.getNode() == BasePtr.getNode())
7149         std::swap(Op0, Op1);
7150       assert(Op0.getNode() == BasePtr.getNode() &&
7151              "Use of ADD/SUB but not an operand");
7152
7153       if (!isa<ConstantSDNode>(Op1)) {
7154         OtherUses.clear();
7155         break;
7156       }
7157
7158       // FIXME: In some cases, we can be smarter about this.
7159       if (Op1.getValueType() != Offset.getValueType()) {
7160         OtherUses.clear();
7161         break;
7162       }
7163
7164       OtherUses.push_back(Use);
7165     }
7166
7167   if (Swapped)
7168     std::swap(BasePtr, Offset);
7169
7170   // Now check for #3 and #4.
7171   bool RealUse = false;
7172
7173   // Caches for hasPredecessorHelper
7174   SmallPtrSet<const SDNode *, 32> Visited;
7175   SmallVector<const SDNode *, 16> Worklist;
7176
7177   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7178          E = Ptr.getNode()->use_end(); I != E; ++I) {
7179     SDNode *Use = *I;
7180     if (Use == N)
7181       continue;
7182     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7183       return false;
7184
7185     // If Ptr may be folded in addressing mode of other use, then it's
7186     // not profitable to do this transformation.
7187     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7188       RealUse = true;
7189   }
7190
7191   if (!RealUse)
7192     return false;
7193
7194   SDValue Result;
7195   if (isLoad)
7196     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7197                                 BasePtr, Offset, AM);
7198   else
7199     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7200                                  BasePtr, Offset, AM);
7201   ++PreIndexedNodes;
7202   ++NodesCombined;
7203   DEBUG(dbgs() << "\nReplacing.4 ";
7204         N->dump(&DAG);
7205         dbgs() << "\nWith: ";
7206         Result.getNode()->dump(&DAG);
7207         dbgs() << '\n');
7208   WorkListRemover DeadNodes(*this);
7209   if (isLoad) {
7210     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7211     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7212   } else {
7213     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7214   }
7215
7216   // Finally, since the node is now dead, remove it from the graph.
7217   DAG.DeleteNode(N);
7218
7219   if (Swapped)
7220     std::swap(BasePtr, Offset);
7221
7222   // Replace other uses of BasePtr that can be updated to use Ptr
7223   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7224     unsigned OffsetIdx = 1;
7225     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7226       OffsetIdx = 0;
7227     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7228            BasePtr.getNode() && "Expected BasePtr operand");
7229
7230     // We need to replace ptr0 in the following expression:
7231     //   x0 * offset0 + y0 * ptr0 = t0
7232     // knowing that
7233     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7234     //
7235     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7236     // indexed load/store and the expresion that needs to be re-written.
7237     //
7238     // Therefore, we have:
7239     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7240
7241     ConstantSDNode *CN =
7242       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7243     int X0, X1, Y0, Y1;
7244     APInt Offset0 = CN->getAPIntValue();
7245     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7246
7247     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7248     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7249     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7250     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7251
7252     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7253
7254     APInt CNV = Offset0;
7255     if (X0 < 0) CNV = -CNV;
7256     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7257     else CNV = CNV - Offset1;
7258
7259     // We can now generate the new expression.
7260     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7261     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7262
7263     SDValue NewUse = DAG.getNode(Opcode,
7264                                  SDLoc(OtherUses[i]),
7265                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7266     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7267     removeFromWorkList(OtherUses[i]);
7268     DAG.DeleteNode(OtherUses[i]);
7269   }
7270
7271   // Replace the uses of Ptr with uses of the updated base value.
7272   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7273   removeFromWorkList(Ptr.getNode());
7274   DAG.DeleteNode(Ptr.getNode());
7275
7276   return true;
7277 }
7278
7279 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7280 /// add / sub of the base pointer node into a post-indexed load / store.
7281 /// The transformation folded the add / subtract into the new indexed
7282 /// load / store effectively and all of its uses are redirected to the
7283 /// new load / store.
7284 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7285   if (Level < AfterLegalizeDAG)
7286     return false;
7287
7288   bool isLoad = true;
7289   SDValue Ptr;
7290   EVT VT;
7291   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7292     if (LD->isIndexed())
7293       return false;
7294     VT = LD->getMemoryVT();
7295     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7296         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7297       return false;
7298     Ptr = LD->getBasePtr();
7299   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7300     if (ST->isIndexed())
7301       return false;
7302     VT = ST->getMemoryVT();
7303     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7304         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7305       return false;
7306     Ptr = ST->getBasePtr();
7307     isLoad = false;
7308   } else {
7309     return false;
7310   }
7311
7312   if (Ptr.getNode()->hasOneUse())
7313     return false;
7314
7315   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7316          E = Ptr.getNode()->use_end(); I != E; ++I) {
7317     SDNode *Op = *I;
7318     if (Op == N ||
7319         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7320       continue;
7321
7322     SDValue BasePtr;
7323     SDValue Offset;
7324     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7325     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7326       // Don't create a indexed load / store with zero offset.
7327       if (isa<ConstantSDNode>(Offset) &&
7328           cast<ConstantSDNode>(Offset)->isNullValue())
7329         continue;
7330
7331       // Try turning it into a post-indexed load / store except when
7332       // 1) All uses are load / store ops that use it as base ptr (and
7333       //    it may be folded as addressing mmode).
7334       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7335       //    nor a successor of N. Otherwise, if Op is folded that would
7336       //    create a cycle.
7337
7338       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7339         continue;
7340
7341       // Check for #1.
7342       bool TryNext = false;
7343       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7344              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7345         SDNode *Use = *II;
7346         if (Use == Ptr.getNode())
7347           continue;
7348
7349         // If all the uses are load / store addresses, then don't do the
7350         // transformation.
7351         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7352           bool RealUse = false;
7353           for (SDNode::use_iterator III = Use->use_begin(),
7354                  EEE = Use->use_end(); III != EEE; ++III) {
7355             SDNode *UseUse = *III;
7356             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7357               RealUse = true;
7358           }
7359
7360           if (!RealUse) {
7361             TryNext = true;
7362             break;
7363           }
7364         }
7365       }
7366
7367       if (TryNext)
7368         continue;
7369
7370       // Check for #2
7371       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7372         SDValue Result = isLoad
7373           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7374                                BasePtr, Offset, AM)
7375           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7376                                 BasePtr, Offset, AM);
7377         ++PostIndexedNodes;
7378         ++NodesCombined;
7379         DEBUG(dbgs() << "\nReplacing.5 ";
7380               N->dump(&DAG);
7381               dbgs() << "\nWith: ";
7382               Result.getNode()->dump(&DAG);
7383               dbgs() << '\n');
7384         WorkListRemover DeadNodes(*this);
7385         if (isLoad) {
7386           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7387           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7388         } else {
7389           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7390         }
7391
7392         // Finally, since the node is now dead, remove it from the graph.
7393         DAG.DeleteNode(N);
7394
7395         // Replace the uses of Use with uses of the updated base value.
7396         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7397                                       Result.getValue(isLoad ? 1 : 0));
7398         removeFromWorkList(Op);
7399         DAG.DeleteNode(Op);
7400         return true;
7401       }
7402     }
7403   }
7404
7405   return false;
7406 }
7407
7408 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7409   LoadSDNode *LD  = cast<LoadSDNode>(N);
7410   SDValue Chain = LD->getChain();
7411   SDValue Ptr   = LD->getBasePtr();
7412
7413   // If load is not volatile and there are no uses of the loaded value (and
7414   // the updated indexed value in case of indexed loads), change uses of the
7415   // chain value into uses of the chain input (i.e. delete the dead load).
7416   if (!LD->isVolatile()) {
7417     if (N->getValueType(1) == MVT::Other) {
7418       // Unindexed loads.
7419       if (!N->hasAnyUseOfValue(0)) {
7420         // It's not safe to use the two value CombineTo variant here. e.g.
7421         // v1, chain2 = load chain1, loc
7422         // v2, chain3 = load chain2, loc
7423         // v3         = add v2, c
7424         // Now we replace use of chain2 with chain1.  This makes the second load
7425         // isomorphic to the one we are deleting, and thus makes this load live.
7426         DEBUG(dbgs() << "\nReplacing.6 ";
7427               N->dump(&DAG);
7428               dbgs() << "\nWith chain: ";
7429               Chain.getNode()->dump(&DAG);
7430               dbgs() << "\n");
7431         WorkListRemover DeadNodes(*this);
7432         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7433
7434         if (N->use_empty()) {
7435           removeFromWorkList(N);
7436           DAG.DeleteNode(N);
7437         }
7438
7439         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7440       }
7441     } else {
7442       // Indexed loads.
7443       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7444       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7445         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7446         DEBUG(dbgs() << "\nReplacing.7 ";
7447               N->dump(&DAG);
7448               dbgs() << "\nWith: ";
7449               Undef.getNode()->dump(&DAG);
7450               dbgs() << " and 2 other values\n");
7451         WorkListRemover DeadNodes(*this);
7452         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7453         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7454                                       DAG.getUNDEF(N->getValueType(1)));
7455         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7456         removeFromWorkList(N);
7457         DAG.DeleteNode(N);
7458         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7459       }
7460     }
7461   }
7462
7463   // If this load is directly stored, replace the load value with the stored
7464   // value.
7465   // TODO: Handle store large -> read small portion.
7466   // TODO: Handle TRUNCSTORE/LOADEXT
7467   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7468     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7469       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7470       if (PrevST->getBasePtr() == Ptr &&
7471           PrevST->getValue().getValueType() == N->getValueType(0))
7472       return CombineTo(N, Chain.getOperand(1), Chain);
7473     }
7474   }
7475
7476   // Try to infer better alignment information than the load already has.
7477   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7478     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7479       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7480         SDValue NewLoad =
7481                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7482                               LD->getValueType(0),
7483                               Chain, Ptr, LD->getPointerInfo(),
7484                               LD->getMemoryVT(),
7485                               LD->isVolatile(), LD->isNonTemporal(), Align);
7486         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7487       }
7488     }
7489   }
7490
7491   if (CombinerAA) {
7492     // Walk up chain skipping non-aliasing memory nodes.
7493     SDValue BetterChain = FindBetterChain(N, Chain);
7494
7495     // If there is a better chain.
7496     if (Chain != BetterChain) {
7497       SDValue ReplLoad;
7498
7499       // Replace the chain to void dependency.
7500       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7501         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7502                                BetterChain, Ptr, LD->getPointerInfo(),
7503                                LD->isVolatile(), LD->isNonTemporal(),
7504                                LD->isInvariant(), LD->getAlignment());
7505       } else {
7506         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7507                                   LD->getValueType(0),
7508                                   BetterChain, Ptr, LD->getPointerInfo(),
7509                                   LD->getMemoryVT(),
7510                                   LD->isVolatile(),
7511                                   LD->isNonTemporal(),
7512                                   LD->getAlignment());
7513       }
7514
7515       // Create token factor to keep old chain connected.
7516       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7517                                   MVT::Other, Chain, ReplLoad.getValue(1));
7518
7519       // Make sure the new and old chains are cleaned up.
7520       AddToWorkList(Token.getNode());
7521
7522       // Replace uses with load result and token factor. Don't add users
7523       // to work list.
7524       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7525     }
7526   }
7527
7528   // Try transforming N to an indexed load.
7529   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7530     return SDValue(N, 0);
7531
7532   return SDValue();
7533 }
7534
7535 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7536 /// load is having specific bytes cleared out.  If so, return the byte size
7537 /// being masked out and the shift amount.
7538 static std::pair<unsigned, unsigned>
7539 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7540   std::pair<unsigned, unsigned> Result(0, 0);
7541
7542   // Check for the structure we're looking for.
7543   if (V->getOpcode() != ISD::AND ||
7544       !isa<ConstantSDNode>(V->getOperand(1)) ||
7545       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7546     return Result;
7547
7548   // Check the chain and pointer.
7549   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7550   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7551
7552   // The store should be chained directly to the load or be an operand of a
7553   // tokenfactor.
7554   if (LD == Chain.getNode())
7555     ; // ok.
7556   else if (Chain->getOpcode() != ISD::TokenFactor)
7557     return Result; // Fail.
7558   else {
7559     bool isOk = false;
7560     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7561       if (Chain->getOperand(i).getNode() == LD) {
7562         isOk = true;
7563         break;
7564       }
7565     if (!isOk) return Result;
7566   }
7567
7568   // This only handles simple types.
7569   if (V.getValueType() != MVT::i16 &&
7570       V.getValueType() != MVT::i32 &&
7571       V.getValueType() != MVT::i64)
7572     return Result;
7573
7574   // Check the constant mask.  Invert it so that the bits being masked out are
7575   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7576   // follow the sign bit for uniformity.
7577   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7578   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7579   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7580   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7581   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7582   if (NotMaskLZ == 64) return Result;  // All zero mask.
7583
7584   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7585   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7586     return Result;
7587
7588   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7589   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7590     NotMaskLZ -= 64-V.getValueSizeInBits();
7591
7592   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7593   switch (MaskedBytes) {
7594   case 1:
7595   case 2:
7596   case 4: break;
7597   default: return Result; // All one mask, or 5-byte mask.
7598   }
7599
7600   // Verify that the first bit starts at a multiple of mask so that the access
7601   // is aligned the same as the access width.
7602   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7603
7604   Result.first = MaskedBytes;
7605   Result.second = NotMaskTZ/8;
7606   return Result;
7607 }
7608
7609
7610 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7611 /// provides a value as specified by MaskInfo.  If so, replace the specified
7612 /// store with a narrower store of truncated IVal.
7613 static SDNode *
7614 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7615                                 SDValue IVal, StoreSDNode *St,
7616                                 DAGCombiner *DC) {
7617   unsigned NumBytes = MaskInfo.first;
7618   unsigned ByteShift = MaskInfo.second;
7619   SelectionDAG &DAG = DC->getDAG();
7620
7621   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7622   // that uses this.  If not, this is not a replacement.
7623   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7624                                   ByteShift*8, (ByteShift+NumBytes)*8);
7625   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7626
7627   // Check that it is legal on the target to do this.  It is legal if the new
7628   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7629   // legalization.
7630   MVT VT = MVT::getIntegerVT(NumBytes*8);
7631   if (!DC->isTypeLegal(VT))
7632     return 0;
7633
7634   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7635   // shifted by ByteShift and truncated down to NumBytes.
7636   if (ByteShift)
7637     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7638                        DAG.getConstant(ByteShift*8,
7639                                     DC->getShiftAmountTy(IVal.getValueType())));
7640
7641   // Figure out the offset for the store and the alignment of the access.
7642   unsigned StOffset;
7643   unsigned NewAlign = St->getAlignment();
7644
7645   if (DAG.getTargetLoweringInfo().isLittleEndian())
7646     StOffset = ByteShift;
7647   else
7648     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7649
7650   SDValue Ptr = St->getBasePtr();
7651   if (StOffset) {
7652     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7653                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7654     NewAlign = MinAlign(NewAlign, StOffset);
7655   }
7656
7657   // Truncate down to the new size.
7658   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7659
7660   ++OpsNarrowed;
7661   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7662                       St->getPointerInfo().getWithOffset(StOffset),
7663                       false, false, NewAlign).getNode();
7664 }
7665
7666
7667 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7668 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7669 /// of the loaded bits, try narrowing the load and store if it would end up
7670 /// being a win for performance or code size.
7671 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7672   StoreSDNode *ST  = cast<StoreSDNode>(N);
7673   if (ST->isVolatile())
7674     return SDValue();
7675
7676   SDValue Chain = ST->getChain();
7677   SDValue Value = ST->getValue();
7678   SDValue Ptr   = ST->getBasePtr();
7679   EVT VT = Value.getValueType();
7680
7681   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7682     return SDValue();
7683
7684   unsigned Opc = Value.getOpcode();
7685
7686   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7687   // is a byte mask indicating a consecutive number of bytes, check to see if
7688   // Y is known to provide just those bytes.  If so, we try to replace the
7689   // load + replace + store sequence with a single (narrower) store, which makes
7690   // the load dead.
7691   if (Opc == ISD::OR) {
7692     std::pair<unsigned, unsigned> MaskedLoad;
7693     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7694     if (MaskedLoad.first)
7695       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7696                                                   Value.getOperand(1), ST,this))
7697         return SDValue(NewST, 0);
7698
7699     // Or is commutative, so try swapping X and Y.
7700     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7701     if (MaskedLoad.first)
7702       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7703                                                   Value.getOperand(0), ST,this))
7704         return SDValue(NewST, 0);
7705   }
7706
7707   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7708       Value.getOperand(1).getOpcode() != ISD::Constant)
7709     return SDValue();
7710
7711   SDValue N0 = Value.getOperand(0);
7712   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7713       Chain == SDValue(N0.getNode(), 1)) {
7714     LoadSDNode *LD = cast<LoadSDNode>(N0);
7715     if (LD->getBasePtr() != Ptr ||
7716         LD->getPointerInfo().getAddrSpace() !=
7717         ST->getPointerInfo().getAddrSpace())
7718       return SDValue();
7719
7720     // Find the type to narrow it the load / op / store to.
7721     SDValue N1 = Value.getOperand(1);
7722     unsigned BitWidth = N1.getValueSizeInBits();
7723     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7724     if (Opc == ISD::AND)
7725       Imm ^= APInt::getAllOnesValue(BitWidth);
7726     if (Imm == 0 || Imm.isAllOnesValue())
7727       return SDValue();
7728     unsigned ShAmt = Imm.countTrailingZeros();
7729     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7730     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7731     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7732     while (NewBW < BitWidth &&
7733            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7734              TLI.isNarrowingProfitable(VT, NewVT))) {
7735       NewBW = NextPowerOf2(NewBW);
7736       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7737     }
7738     if (NewBW >= BitWidth)
7739       return SDValue();
7740
7741     // If the lsb changed does not start at the type bitwidth boundary,
7742     // start at the previous one.
7743     if (ShAmt % NewBW)
7744       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7745     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7746                                    std::min(BitWidth, ShAmt + NewBW));
7747     if ((Imm & Mask) == Imm) {
7748       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7749       if (Opc == ISD::AND)
7750         NewImm ^= APInt::getAllOnesValue(NewBW);
7751       uint64_t PtrOff = ShAmt / 8;
7752       // For big endian targets, we need to adjust the offset to the pointer to
7753       // load the correct bytes.
7754       if (TLI.isBigEndian())
7755         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7756
7757       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7758       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7759       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7760         return SDValue();
7761
7762       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7763                                    Ptr.getValueType(), Ptr,
7764                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7765       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7766                                   LD->getChain(), NewPtr,
7767                                   LD->getPointerInfo().getWithOffset(PtrOff),
7768                                   LD->isVolatile(), LD->isNonTemporal(),
7769                                   LD->isInvariant(), NewAlign);
7770       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7771                                    DAG.getConstant(NewImm, NewVT));
7772       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7773                                    NewVal, NewPtr,
7774                                    ST->getPointerInfo().getWithOffset(PtrOff),
7775                                    false, false, NewAlign);
7776
7777       AddToWorkList(NewPtr.getNode());
7778       AddToWorkList(NewLD.getNode());
7779       AddToWorkList(NewVal.getNode());
7780       WorkListRemover DeadNodes(*this);
7781       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7782       ++OpsNarrowed;
7783       return NewST;
7784     }
7785   }
7786
7787   return SDValue();
7788 }
7789
7790 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7791 /// if the load value isn't used by any other operations, then consider
7792 /// transforming the pair to integer load / store operations if the target
7793 /// deems the transformation profitable.
7794 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7795   StoreSDNode *ST  = cast<StoreSDNode>(N);
7796   SDValue Chain = ST->getChain();
7797   SDValue Value = ST->getValue();
7798   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7799       Value.hasOneUse() &&
7800       Chain == SDValue(Value.getNode(), 1)) {
7801     LoadSDNode *LD = cast<LoadSDNode>(Value);
7802     EVT VT = LD->getMemoryVT();
7803     if (!VT.isFloatingPoint() ||
7804         VT != ST->getMemoryVT() ||
7805         LD->isNonTemporal() ||
7806         ST->isNonTemporal() ||
7807         LD->getPointerInfo().getAddrSpace() != 0 ||
7808         ST->getPointerInfo().getAddrSpace() != 0)
7809       return SDValue();
7810
7811     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7812     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7813         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7814         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7815         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7816       return SDValue();
7817
7818     unsigned LDAlign = LD->getAlignment();
7819     unsigned STAlign = ST->getAlignment();
7820     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7821     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7822     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7823       return SDValue();
7824
7825     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7826                                 LD->getChain(), LD->getBasePtr(),
7827                                 LD->getPointerInfo(),
7828                                 false, false, false, LDAlign);
7829
7830     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7831                                  NewLD, ST->getBasePtr(),
7832                                  ST->getPointerInfo(),
7833                                  false, false, STAlign);
7834
7835     AddToWorkList(NewLD.getNode());
7836     AddToWorkList(NewST.getNode());
7837     WorkListRemover DeadNodes(*this);
7838     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7839     ++LdStFP2Int;
7840     return NewST;
7841   }
7842
7843   return SDValue();
7844 }
7845
7846 /// Helper struct to parse and store a memory address as base + index + offset.
7847 /// We ignore sign extensions when it is safe to do so.
7848 /// The following two expressions are not equivalent. To differentiate we need
7849 /// to store whether there was a sign extension involved in the index
7850 /// computation.
7851 ///  (load (i64 add (i64 copyfromreg %c)
7852 ///                 (i64 signextend (add (i8 load %index)
7853 ///                                      (i8 1))))
7854 /// vs
7855 ///
7856 /// (load (i64 add (i64 copyfromreg %c)
7857 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7858 ///                                         (i32 1)))))
7859 struct BaseIndexOffset {
7860   SDValue Base;
7861   SDValue Index;
7862   int64_t Offset;
7863   bool IsIndexSignExt;
7864
7865   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7866
7867   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7868                   bool IsIndexSignExt) :
7869     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7870
7871   bool equalBaseIndex(const BaseIndexOffset &Other) {
7872     return Other.Base == Base && Other.Index == Index &&
7873       Other.IsIndexSignExt == IsIndexSignExt;
7874   }
7875
7876   /// Parses tree in Ptr for base, index, offset addresses.
7877   static BaseIndexOffset match(SDValue Ptr) {
7878     bool IsIndexSignExt = false;
7879
7880     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7881     // instruction, then it could be just the BASE or everything else we don't
7882     // know how to handle. Just use Ptr as BASE and give up.
7883     if (Ptr->getOpcode() != ISD::ADD)
7884       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7885
7886     // We know that we have at least an ADD instruction. Try to pattern match
7887     // the simple case of BASE + OFFSET.
7888     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7889       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7890       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7891                               IsIndexSignExt);
7892     }
7893
7894     // Inside a loop the current BASE pointer is calculated using an ADD and a
7895     // MUL instruction. In this case Ptr is the actual BASE pointer.
7896     // (i64 add (i64 %array_ptr)
7897     //          (i64 mul (i64 %induction_var)
7898     //                   (i64 %element_size)))
7899     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7900       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7901
7902     // Look at Base + Index + Offset cases.
7903     SDValue Base = Ptr->getOperand(0);
7904     SDValue IndexOffset = Ptr->getOperand(1);
7905
7906     // Skip signextends.
7907     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7908       IndexOffset = IndexOffset->getOperand(0);
7909       IsIndexSignExt = true;
7910     }
7911
7912     // Either the case of Base + Index (no offset) or something else.
7913     if (IndexOffset->getOpcode() != ISD::ADD)
7914       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7915
7916     // Now we have the case of Base + Index + offset.
7917     SDValue Index = IndexOffset->getOperand(0);
7918     SDValue Offset = IndexOffset->getOperand(1);
7919
7920     if (!isa<ConstantSDNode>(Offset))
7921       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7922
7923     // Ignore signextends.
7924     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7925       Index = Index->getOperand(0);
7926       IsIndexSignExt = true;
7927     } else IsIndexSignExt = false;
7928
7929     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7930     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7931   }
7932 };
7933
7934 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7935 /// is located in a sequence of memory operations connected by a chain.
7936 struct MemOpLink {
7937   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7938     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7939   // Ptr to the mem node.
7940   LSBaseSDNode *MemNode;
7941   // Offset from the base ptr.
7942   int64_t OffsetFromBase;
7943   // What is the sequence number of this mem node.
7944   // Lowest mem operand in the DAG starts at zero.
7945   unsigned SequenceNum;
7946 };
7947
7948 /// Sorts store nodes in a link according to their offset from a shared
7949 // base ptr.
7950 struct ConsecutiveMemoryChainSorter {
7951   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7952     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7953   }
7954 };
7955
7956 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7957   EVT MemVT = St->getMemoryVT();
7958   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7959   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7960     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7961
7962   // Don't merge vectors into wider inputs.
7963   if (MemVT.isVector() || !MemVT.isSimple())
7964     return false;
7965
7966   // Perform an early exit check. Do not bother looking at stored values that
7967   // are not constants or loads.
7968   SDValue StoredVal = St->getValue();
7969   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7970   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7971       !IsLoadSrc)
7972     return false;
7973
7974   // Only look at ends of store sequences.
7975   SDValue Chain = SDValue(St, 1);
7976   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7977     return false;
7978
7979   // This holds the base pointer, index, and the offset in bytes from the base
7980   // pointer.
7981   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7982
7983   // We must have a base and an offset.
7984   if (!BasePtr.Base.getNode())
7985     return false;
7986
7987   // Do not handle stores to undef base pointers.
7988   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7989     return false;
7990
7991   // Save the LoadSDNodes that we find in the chain.
7992   // We need to make sure that these nodes do not interfere with
7993   // any of the store nodes.
7994   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7995
7996   // Save the StoreSDNodes that we find in the chain.
7997   SmallVector<MemOpLink, 8> StoreNodes;
7998
7999   // Walk up the chain and look for nodes with offsets from the same
8000   // base pointer. Stop when reaching an instruction with a different kind
8001   // or instruction which has a different base pointer.
8002   unsigned Seq = 0;
8003   StoreSDNode *Index = St;
8004   while (Index) {
8005     // If the chain has more than one use, then we can't reorder the mem ops.
8006     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8007       break;
8008
8009     // Find the base pointer and offset for this memory node.
8010     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8011
8012     // Check that the base pointer is the same as the original one.
8013     if (!Ptr.equalBaseIndex(BasePtr))
8014       break;
8015
8016     // Check that the alignment is the same.
8017     if (Index->getAlignment() != St->getAlignment())
8018       break;
8019
8020     // The memory operands must not be volatile.
8021     if (Index->isVolatile() || Index->isIndexed())
8022       break;
8023
8024     // No truncation.
8025     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8026       if (St->isTruncatingStore())
8027         break;
8028
8029     // The stored memory type must be the same.
8030     if (Index->getMemoryVT() != MemVT)
8031       break;
8032
8033     // We do not allow unaligned stores because we want to prevent overriding
8034     // stores.
8035     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8036       break;
8037
8038     // We found a potential memory operand to merge.
8039     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8040
8041     // Find the next memory operand in the chain. If the next operand in the
8042     // chain is a store then move up and continue the scan with the next
8043     // memory operand. If the next operand is a load save it and use alias
8044     // information to check if it interferes with anything.
8045     SDNode *NextInChain = Index->getChain().getNode();
8046     while (1) {
8047       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8048         // We found a store node. Use it for the next iteration.
8049         Index = STn;
8050         break;
8051       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8052         // Save the load node for later. Continue the scan.
8053         AliasLoadNodes.push_back(Ldn);
8054         NextInChain = Ldn->getChain().getNode();
8055         continue;
8056       } else {
8057         Index = NULL;
8058         break;
8059       }
8060     }
8061   }
8062
8063   // Check if there is anything to merge.
8064   if (StoreNodes.size() < 2)
8065     return false;
8066
8067   // Sort the memory operands according to their distance from the base pointer.
8068   std::sort(StoreNodes.begin(), StoreNodes.end(),
8069             ConsecutiveMemoryChainSorter());
8070
8071   // Scan the memory operations on the chain and find the first non-consecutive
8072   // store memory address.
8073   unsigned LastConsecutiveStore = 0;
8074   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8075   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8076
8077     // Check that the addresses are consecutive starting from the second
8078     // element in the list of stores.
8079     if (i > 0) {
8080       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8081       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8082         break;
8083     }
8084
8085     bool Alias = false;
8086     // Check if this store interferes with any of the loads that we found.
8087     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8088       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8089         Alias = true;
8090         break;
8091       }
8092     // We found a load that alias with this store. Stop the sequence.
8093     if (Alias)
8094       break;
8095
8096     // Mark this node as useful.
8097     LastConsecutiveStore = i;
8098   }
8099
8100   // The node with the lowest store address.
8101   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8102
8103   // Store the constants into memory as one consecutive store.
8104   if (!IsLoadSrc) {
8105     unsigned LastLegalType = 0;
8106     unsigned LastLegalVectorType = 0;
8107     bool NonZero = false;
8108     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8109       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8110       SDValue StoredVal = St->getValue();
8111
8112       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8113         NonZero |= !C->isNullValue();
8114       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8115         NonZero |= !C->getConstantFPValue()->isNullValue();
8116       } else {
8117         // Non constant.
8118         break;
8119       }
8120
8121       // Find a legal type for the constant store.
8122       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8123       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8124       if (TLI.isTypeLegal(StoreTy))
8125         LastLegalType = i+1;
8126       // Or check whether a truncstore is legal.
8127       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8128                TargetLowering::TypePromoteInteger) {
8129         EVT LegalizedStoredValueTy =
8130           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8131         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8132           LastLegalType = i+1;
8133       }
8134
8135       // Find a legal type for the vector store.
8136       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8137       if (TLI.isTypeLegal(Ty))
8138         LastLegalVectorType = i + 1;
8139     }
8140
8141     // We only use vectors if the constant is known to be zero and the
8142     // function is not marked with the noimplicitfloat attribute.
8143     if (NonZero || NoVectors)
8144       LastLegalVectorType = 0;
8145
8146     // Check if we found a legal integer type to store.
8147     if (LastLegalType == 0 && LastLegalVectorType == 0)
8148       return false;
8149
8150     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8151     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8152
8153     // Make sure we have something to merge.
8154     if (NumElem < 2)
8155       return false;
8156
8157     unsigned EarliestNodeUsed = 0;
8158     for (unsigned i=0; i < NumElem; ++i) {
8159       // Find a chain for the new wide-store operand. Notice that some
8160       // of the store nodes that we found may not be selected for inclusion
8161       // in the wide store. The chain we use needs to be the chain of the
8162       // earliest store node which is *used* and replaced by the wide store.
8163       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8164         EarliestNodeUsed = i;
8165     }
8166
8167     // The earliest Node in the DAG.
8168     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8169     SDLoc DL(StoreNodes[0].MemNode);
8170
8171     SDValue StoredVal;
8172     if (UseVector) {
8173       // Find a legal type for the vector store.
8174       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8175       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8176       StoredVal = DAG.getConstant(0, Ty);
8177     } else {
8178       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8179       APInt StoreInt(StoreBW, 0);
8180
8181       // Construct a single integer constant which is made of the smaller
8182       // constant inputs.
8183       bool IsLE = TLI.isLittleEndian();
8184       for (unsigned i = 0; i < NumElem ; ++i) {
8185         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8186         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8187         SDValue Val = St->getValue();
8188         StoreInt<<=ElementSizeBytes*8;
8189         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8190           StoreInt|=C->getAPIntValue().zext(StoreBW);
8191         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8192           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8193         } else {
8194           assert(false && "Invalid constant element type");
8195         }
8196       }
8197
8198       // Create the new Load and Store operations.
8199       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8200       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8201     }
8202
8203     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8204                                     FirstInChain->getBasePtr(),
8205                                     FirstInChain->getPointerInfo(),
8206                                     false, false,
8207                                     FirstInChain->getAlignment());
8208
8209     // Replace the first store with the new store
8210     CombineTo(EarliestOp, NewStore);
8211     // Erase all other stores.
8212     for (unsigned i = 0; i < NumElem ; ++i) {
8213       if (StoreNodes[i].MemNode == EarliestOp)
8214         continue;
8215       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8216       // ReplaceAllUsesWith will replace all uses that existed when it was
8217       // called, but graph optimizations may cause new ones to appear. For
8218       // example, the case in pr14333 looks like
8219       //
8220       //  St's chain -> St -> another store -> X
8221       //
8222       // And the only difference from St to the other store is the chain.
8223       // When we change it's chain to be St's chain they become identical,
8224       // get CSEed and the net result is that X is now a use of St.
8225       // Since we know that St is redundant, just iterate.
8226       while (!St->use_empty())
8227         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8228       removeFromWorkList(St);
8229       DAG.DeleteNode(St);
8230     }
8231
8232     return true;
8233   }
8234
8235   // Below we handle the case of multiple consecutive stores that
8236   // come from multiple consecutive loads. We merge them into a single
8237   // wide load and a single wide store.
8238
8239   // Look for load nodes which are used by the stored values.
8240   SmallVector<MemOpLink, 8> LoadNodes;
8241
8242   // Find acceptable loads. Loads need to have the same chain (token factor),
8243   // must not be zext, volatile, indexed, and they must be consecutive.
8244   BaseIndexOffset LdBasePtr;
8245   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8246     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8247     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8248     if (!Ld) break;
8249
8250     // Loads must only have one use.
8251     if (!Ld->hasNUsesOfValue(1, 0))
8252       break;
8253
8254     // Check that the alignment is the same as the stores.
8255     if (Ld->getAlignment() != St->getAlignment())
8256       break;
8257
8258     // The memory operands must not be volatile.
8259     if (Ld->isVolatile() || Ld->isIndexed())
8260       break;
8261
8262     // We do not accept ext loads.
8263     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8264       break;
8265
8266     // The stored memory type must be the same.
8267     if (Ld->getMemoryVT() != MemVT)
8268       break;
8269
8270     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8271     // If this is not the first ptr that we check.
8272     if (LdBasePtr.Base.getNode()) {
8273       // The base ptr must be the same.
8274       if (!LdPtr.equalBaseIndex(LdBasePtr))
8275         break;
8276     } else {
8277       // Check that all other base pointers are the same as this one.
8278       LdBasePtr = LdPtr;
8279     }
8280
8281     // We found a potential memory operand to merge.
8282     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8283   }
8284
8285   if (LoadNodes.size() < 2)
8286     return false;
8287
8288   // Scan the memory operations on the chain and find the first non-consecutive
8289   // load memory address. These variables hold the index in the store node
8290   // array.
8291   unsigned LastConsecutiveLoad = 0;
8292   // This variable refers to the size and not index in the array.
8293   unsigned LastLegalVectorType = 0;
8294   unsigned LastLegalIntegerType = 0;
8295   StartAddress = LoadNodes[0].OffsetFromBase;
8296   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8297   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8298     // All loads much share the same chain.
8299     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8300       break;
8301
8302     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8303     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8304       break;
8305     LastConsecutiveLoad = i;
8306
8307     // Find a legal type for the vector store.
8308     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8309     if (TLI.isTypeLegal(StoreTy))
8310       LastLegalVectorType = i + 1;
8311
8312     // Find a legal type for the integer store.
8313     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8314     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8315     if (TLI.isTypeLegal(StoreTy))
8316       LastLegalIntegerType = i + 1;
8317     // Or check whether a truncstore and extload is legal.
8318     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8319              TargetLowering::TypePromoteInteger) {
8320       EVT LegalizedStoredValueTy =
8321         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8322       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8323           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8324           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8325           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8326         LastLegalIntegerType = i+1;
8327     }
8328   }
8329
8330   // Only use vector types if the vector type is larger than the integer type.
8331   // If they are the same, use integers.
8332   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8333   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8334
8335   // We add +1 here because the LastXXX variables refer to location while
8336   // the NumElem refers to array/index size.
8337   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8338   NumElem = std::min(LastLegalType, NumElem);
8339
8340   if (NumElem < 2)
8341     return false;
8342
8343   // The earliest Node in the DAG.
8344   unsigned EarliestNodeUsed = 0;
8345   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8346   for (unsigned i=1; i<NumElem; ++i) {
8347     // Find a chain for the new wide-store operand. Notice that some
8348     // of the store nodes that we found may not be selected for inclusion
8349     // in the wide store. The chain we use needs to be the chain of the
8350     // earliest store node which is *used* and replaced by the wide store.
8351     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8352       EarliestNodeUsed = i;
8353   }
8354
8355   // Find if it is better to use vectors or integers to load and store
8356   // to memory.
8357   EVT JointMemOpVT;
8358   if (UseVectorTy) {
8359     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8360   } else {
8361     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8362     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8363   }
8364
8365   SDLoc LoadDL(LoadNodes[0].MemNode);
8366   SDLoc StoreDL(StoreNodes[0].MemNode);
8367
8368   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8369   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8370                                 FirstLoad->getChain(),
8371                                 FirstLoad->getBasePtr(),
8372                                 FirstLoad->getPointerInfo(),
8373                                 false, false, false,
8374                                 FirstLoad->getAlignment());
8375
8376   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8377                                   FirstInChain->getBasePtr(),
8378                                   FirstInChain->getPointerInfo(), false, false,
8379                                   FirstInChain->getAlignment());
8380
8381   // Replace one of the loads with the new load.
8382   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8383   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8384                                 SDValue(NewLoad.getNode(), 1));
8385
8386   // Remove the rest of the load chains.
8387   for (unsigned i = 1; i < NumElem ; ++i) {
8388     // Replace all chain users of the old load nodes with the chain of the new
8389     // load node.
8390     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8391     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8392   }
8393
8394   // Replace the first store with the new store.
8395   CombineTo(EarliestOp, NewStore);
8396   // Erase all other stores.
8397   for (unsigned i = 0; i < NumElem ; ++i) {
8398     // Remove all Store nodes.
8399     if (StoreNodes[i].MemNode == EarliestOp)
8400       continue;
8401     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8402     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8403     removeFromWorkList(St);
8404     DAG.DeleteNode(St);
8405   }
8406
8407   return true;
8408 }
8409
8410 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8411   StoreSDNode *ST  = cast<StoreSDNode>(N);
8412   SDValue Chain = ST->getChain();
8413   SDValue Value = ST->getValue();
8414   SDValue Ptr   = ST->getBasePtr();
8415
8416   // If this is a store of a bit convert, store the input value if the
8417   // resultant store does not need a higher alignment than the original.
8418   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8419       ST->isUnindexed()) {
8420     unsigned OrigAlign = ST->getAlignment();
8421     EVT SVT = Value.getOperand(0).getValueType();
8422     unsigned Align = TLI.getDataLayout()->
8423       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8424     if (Align <= OrigAlign &&
8425         ((!LegalOperations && !ST->isVolatile()) ||
8426          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8427       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8428                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8429                           ST->isNonTemporal(), OrigAlign);
8430   }
8431
8432   // Turn 'store undef, Ptr' -> nothing.
8433   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8434     return Chain;
8435
8436   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8437   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8438     // NOTE: If the original store is volatile, this transform must not increase
8439     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8440     // processor operation but an i64 (which is not legal) requires two.  So the
8441     // transform should not be done in this case.
8442     if (Value.getOpcode() != ISD::TargetConstantFP) {
8443       SDValue Tmp;
8444       switch (CFP->getSimpleValueType(0).SimpleTy) {
8445       default: llvm_unreachable("Unknown FP type");
8446       case MVT::f16:    // We don't do this for these yet.
8447       case MVT::f80:
8448       case MVT::f128:
8449       case MVT::ppcf128:
8450         break;
8451       case MVT::f32:
8452         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8453             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8454           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8455                               bitcastToAPInt().getZExtValue(), MVT::i32);
8456           return DAG.getStore(Chain, SDLoc(N), Tmp,
8457                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8458                               ST->isNonTemporal(), ST->getAlignment());
8459         }
8460         break;
8461       case MVT::f64:
8462         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8463              !ST->isVolatile()) ||
8464             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8465           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8466                                 getZExtValue(), MVT::i64);
8467           return DAG.getStore(Chain, SDLoc(N), Tmp,
8468                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8469                               ST->isNonTemporal(), ST->getAlignment());
8470         }
8471
8472         if (!ST->isVolatile() &&
8473             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8474           // Many FP stores are not made apparent until after legalize, e.g. for
8475           // argument passing.  Since this is so common, custom legalize the
8476           // 64-bit integer store into two 32-bit stores.
8477           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8478           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8479           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8480           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8481
8482           unsigned Alignment = ST->getAlignment();
8483           bool isVolatile = ST->isVolatile();
8484           bool isNonTemporal = ST->isNonTemporal();
8485
8486           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8487                                      Ptr, ST->getPointerInfo(),
8488                                      isVolatile, isNonTemporal,
8489                                      ST->getAlignment());
8490           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8491                             DAG.getConstant(4, Ptr.getValueType()));
8492           Alignment = MinAlign(Alignment, 4U);
8493           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8494                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8495                                      isVolatile, isNonTemporal,
8496                                      Alignment);
8497           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8498                              St0, St1);
8499         }
8500
8501         break;
8502       }
8503     }
8504   }
8505
8506   // Try to infer better alignment information than the store already has.
8507   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8508     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8509       if (Align > ST->getAlignment())
8510         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8511                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8512                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8513     }
8514   }
8515
8516   // Try transforming a pair floating point load / store ops to integer
8517   // load / store ops.
8518   SDValue NewST = TransformFPLoadStorePair(N);
8519   if (NewST.getNode())
8520     return NewST;
8521
8522   if (CombinerAA) {
8523     // Walk up chain skipping non-aliasing memory nodes.
8524     SDValue BetterChain = FindBetterChain(N, Chain);
8525
8526     // If there is a better chain.
8527     if (Chain != BetterChain) {
8528       SDValue ReplStore;
8529
8530       // Replace the chain to avoid dependency.
8531       if (ST->isTruncatingStore()) {
8532         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8533                                       ST->getPointerInfo(),
8534                                       ST->getMemoryVT(), ST->isVolatile(),
8535                                       ST->isNonTemporal(), ST->getAlignment());
8536       } else {
8537         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8538                                  ST->getPointerInfo(),
8539                                  ST->isVolatile(), ST->isNonTemporal(),
8540                                  ST->getAlignment());
8541       }
8542
8543       // Create token to keep both nodes around.
8544       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8545                                   MVT::Other, Chain, ReplStore);
8546
8547       // Make sure the new and old chains are cleaned up.
8548       AddToWorkList(Token.getNode());
8549
8550       // Don't add users to work list.
8551       return CombineTo(N, Token, false);
8552     }
8553   }
8554
8555   // Try transforming N to an indexed store.
8556   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8557     return SDValue(N, 0);
8558
8559   // FIXME: is there such a thing as a truncating indexed store?
8560   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8561       Value.getValueType().isInteger()) {
8562     // See if we can simplify the input to this truncstore with knowledge that
8563     // only the low bits are being used.  For example:
8564     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8565     SDValue Shorter =
8566       GetDemandedBits(Value,
8567                       APInt::getLowBitsSet(
8568                         Value.getValueType().getScalarType().getSizeInBits(),
8569                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8570     AddToWorkList(Value.getNode());
8571     if (Shorter.getNode())
8572       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8573                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8574                                ST->isVolatile(), ST->isNonTemporal(),
8575                                ST->getAlignment());
8576
8577     // Otherwise, see if we can simplify the operation with
8578     // SimplifyDemandedBits, which only works if the value has a single use.
8579     if (SimplifyDemandedBits(Value,
8580                         APInt::getLowBitsSet(
8581                           Value.getValueType().getScalarType().getSizeInBits(),
8582                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8583       return SDValue(N, 0);
8584   }
8585
8586   // If this is a load followed by a store to the same location, then the store
8587   // is dead/noop.
8588   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8589     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8590         ST->isUnindexed() && !ST->isVolatile() &&
8591         // There can't be any side effects between the load and store, such as
8592         // a call or store.
8593         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8594       // The store is dead, remove it.
8595       return Chain;
8596     }
8597   }
8598
8599   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8600   // truncating store.  We can do this even if this is already a truncstore.
8601   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8602       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8603       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8604                             ST->getMemoryVT())) {
8605     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8606                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8607                              ST->isVolatile(), ST->isNonTemporal(),
8608                              ST->getAlignment());
8609   }
8610
8611   // Only perform this optimization before the types are legal, because we
8612   // don't want to perform this optimization on every DAGCombine invocation.
8613   if (!LegalTypes) {
8614     bool EverChanged = false;
8615
8616     do {
8617       // There can be multiple store sequences on the same chain.
8618       // Keep trying to merge store sequences until we are unable to do so
8619       // or until we merge the last store on the chain.
8620       bool Changed = MergeConsecutiveStores(ST);
8621       EverChanged |= Changed;
8622       if (!Changed) break;
8623     } while (ST->getOpcode() != ISD::DELETED_NODE);
8624
8625     if (EverChanged)
8626       return SDValue(N, 0);
8627   }
8628
8629   return ReduceLoadOpStoreWidth(N);
8630 }
8631
8632 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8633   SDValue InVec = N->getOperand(0);
8634   SDValue InVal = N->getOperand(1);
8635   SDValue EltNo = N->getOperand(2);
8636   SDLoc dl(N);
8637
8638   // If the inserted element is an UNDEF, just use the input vector.
8639   if (InVal.getOpcode() == ISD::UNDEF)
8640     return InVec;
8641
8642   EVT VT = InVec.getValueType();
8643
8644   // If we can't generate a legal BUILD_VECTOR, exit
8645   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8646     return SDValue();
8647
8648   // Check that we know which element is being inserted
8649   if (!isa<ConstantSDNode>(EltNo))
8650     return SDValue();
8651   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8652
8653   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8654   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8655   // vector elements.
8656   SmallVector<SDValue, 8> Ops;
8657   // Do not combine these two vectors if the output vector will not replace
8658   // the input vector.
8659   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8660     Ops.append(InVec.getNode()->op_begin(),
8661                InVec.getNode()->op_end());
8662   } else if (InVec.getOpcode() == ISD::UNDEF) {
8663     unsigned NElts = VT.getVectorNumElements();
8664     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8665   } else {
8666     return SDValue();
8667   }
8668
8669   // Insert the element
8670   if (Elt < Ops.size()) {
8671     // All the operands of BUILD_VECTOR must have the same type;
8672     // we enforce that here.
8673     EVT OpVT = Ops[0].getValueType();
8674     if (InVal.getValueType() != OpVT)
8675       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8676                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8677                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8678     Ops[Elt] = InVal;
8679   }
8680
8681   // Return the new vector
8682   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8683                      VT, &Ops[0], Ops.size());
8684 }
8685
8686 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8687   // (vextract (scalar_to_vector val, 0) -> val
8688   SDValue InVec = N->getOperand(0);
8689   EVT VT = InVec.getValueType();
8690   EVT NVT = N->getValueType(0);
8691
8692   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8693     // Check if the result type doesn't match the inserted element type. A
8694     // SCALAR_TO_VECTOR may truncate the inserted element and the
8695     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8696     SDValue InOp = InVec.getOperand(0);
8697     if (InOp.getValueType() != NVT) {
8698       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8699       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8700     }
8701     return InOp;
8702   }
8703
8704   SDValue EltNo = N->getOperand(1);
8705   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8706
8707   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8708   // We only perform this optimization before the op legalization phase because
8709   // we may introduce new vector instructions which are not backed by TD
8710   // patterns. For example on AVX, extracting elements from a wide vector
8711   // without using extract_subvector.
8712   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8713       && ConstEltNo && !LegalOperations) {
8714     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8715     int NumElem = VT.getVectorNumElements();
8716     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8717     // Find the new index to extract from.
8718     int OrigElt = SVOp->getMaskElt(Elt);
8719
8720     // Extracting an undef index is undef.
8721     if (OrigElt == -1)
8722       return DAG.getUNDEF(NVT);
8723
8724     // Select the right vector half to extract from.
8725     if (OrigElt < NumElem) {
8726       InVec = InVec->getOperand(0);
8727     } else {
8728       InVec = InVec->getOperand(1);
8729       OrigElt -= NumElem;
8730     }
8731
8732     EVT IndexTy = TLI.getVectorIdxTy();
8733     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8734                        InVec, DAG.getConstant(OrigElt, IndexTy));
8735   }
8736
8737   // Perform only after legalization to ensure build_vector / vector_shuffle
8738   // optimizations have already been done.
8739   if (!LegalOperations) return SDValue();
8740
8741   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8742   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8743   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8744
8745   if (ConstEltNo) {
8746     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8747     bool NewLoad = false;
8748     bool BCNumEltsChanged = false;
8749     EVT ExtVT = VT.getVectorElementType();
8750     EVT LVT = ExtVT;
8751
8752     // If the result of load has to be truncated, then it's not necessarily
8753     // profitable.
8754     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8755       return SDValue();
8756
8757     if (InVec.getOpcode() == ISD::BITCAST) {
8758       // Don't duplicate a load with other uses.
8759       if (!InVec.hasOneUse())
8760         return SDValue();
8761
8762       EVT BCVT = InVec.getOperand(0).getValueType();
8763       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8764         return SDValue();
8765       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8766         BCNumEltsChanged = true;
8767       InVec = InVec.getOperand(0);
8768       ExtVT = BCVT.getVectorElementType();
8769       NewLoad = true;
8770     }
8771
8772     LoadSDNode *LN0 = NULL;
8773     const ShuffleVectorSDNode *SVN = NULL;
8774     if (ISD::isNormalLoad(InVec.getNode())) {
8775       LN0 = cast<LoadSDNode>(InVec);
8776     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8777                InVec.getOperand(0).getValueType() == ExtVT &&
8778                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8779       // Don't duplicate a load with other uses.
8780       if (!InVec.hasOneUse())
8781         return SDValue();
8782
8783       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8784     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8785       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8786       // =>
8787       // (load $addr+1*size)
8788
8789       // Don't duplicate a load with other uses.
8790       if (!InVec.hasOneUse())
8791         return SDValue();
8792
8793       // If the bit convert changed the number of elements, it is unsafe
8794       // to examine the mask.
8795       if (BCNumEltsChanged)
8796         return SDValue();
8797
8798       // Select the input vector, guarding against out of range extract vector.
8799       unsigned NumElems = VT.getVectorNumElements();
8800       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8801       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8802
8803       if (InVec.getOpcode() == ISD::BITCAST) {
8804         // Don't duplicate a load with other uses.
8805         if (!InVec.hasOneUse())
8806           return SDValue();
8807
8808         InVec = InVec.getOperand(0);
8809       }
8810       if (ISD::isNormalLoad(InVec.getNode())) {
8811         LN0 = cast<LoadSDNode>(InVec);
8812         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8813       }
8814     }
8815
8816     // Make sure we found a non-volatile load and the extractelement is
8817     // the only use.
8818     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8819       return SDValue();
8820
8821     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8822     if (Elt == -1)
8823       return DAG.getUNDEF(LVT);
8824
8825     unsigned Align = LN0->getAlignment();
8826     if (NewLoad) {
8827       // Check the resultant load doesn't need a higher alignment than the
8828       // original load.
8829       unsigned NewAlign =
8830         TLI.getDataLayout()
8831             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8832
8833       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8834         return SDValue();
8835
8836       Align = NewAlign;
8837     }
8838
8839     SDValue NewPtr = LN0->getBasePtr();
8840     unsigned PtrOff = 0;
8841
8842     if (Elt) {
8843       PtrOff = LVT.getSizeInBits() * Elt / 8;
8844       EVT PtrType = NewPtr.getValueType();
8845       if (TLI.isBigEndian())
8846         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8847       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8848                            DAG.getConstant(PtrOff, PtrType));
8849     }
8850
8851     // The replacement we need to do here is a little tricky: we need to
8852     // replace an extractelement of a load with a load.
8853     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8854     // Note that this replacement assumes that the extractvalue is the only
8855     // use of the load; that's okay because we don't want to perform this
8856     // transformation in other cases anyway.
8857     SDValue Load;
8858     SDValue Chain;
8859     if (NVT.bitsGT(LVT)) {
8860       // If the result type of vextract is wider than the load, then issue an
8861       // extending load instead.
8862       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8863         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8864       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8865                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8866                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8867       Chain = Load.getValue(1);
8868     } else {
8869       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8870                          LN0->getPointerInfo().getWithOffset(PtrOff),
8871                          LN0->isVolatile(), LN0->isNonTemporal(),
8872                          LN0->isInvariant(), Align);
8873       Chain = Load.getValue(1);
8874       if (NVT.bitsLT(LVT))
8875         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8876       else
8877         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8878     }
8879     WorkListRemover DeadNodes(*this);
8880     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8881     SDValue To[] = { Load, Chain };
8882     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8883     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8884     // worklist explicitly as well.
8885     AddToWorkList(Load.getNode());
8886     AddUsersToWorkList(Load.getNode()); // Add users too
8887     // Make sure to revisit this node to clean it up; it will usually be dead.
8888     AddToWorkList(N);
8889     return SDValue(N, 0);
8890   }
8891
8892   return SDValue();
8893 }
8894
8895 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8896 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8897   // We perform this optimization post type-legalization because
8898   // the type-legalizer often scalarizes integer-promoted vectors.
8899   // Performing this optimization before may create bit-casts which
8900   // will be type-legalized to complex code sequences.
8901   // We perform this optimization only before the operation legalizer because we
8902   // may introduce illegal operations.
8903   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8904     return SDValue();
8905
8906   unsigned NumInScalars = N->getNumOperands();
8907   SDLoc dl(N);
8908   EVT VT = N->getValueType(0);
8909
8910   // Check to see if this is a BUILD_VECTOR of a bunch of values
8911   // which come from any_extend or zero_extend nodes. If so, we can create
8912   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8913   // optimizations. We do not handle sign-extend because we can't fill the sign
8914   // using shuffles.
8915   EVT SourceType = MVT::Other;
8916   bool AllAnyExt = true;
8917
8918   for (unsigned i = 0; i != NumInScalars; ++i) {
8919     SDValue In = N->getOperand(i);
8920     // Ignore undef inputs.
8921     if (In.getOpcode() == ISD::UNDEF) continue;
8922
8923     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8924     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8925
8926     // Abort if the element is not an extension.
8927     if (!ZeroExt && !AnyExt) {
8928       SourceType = MVT::Other;
8929       break;
8930     }
8931
8932     // The input is a ZeroExt or AnyExt. Check the original type.
8933     EVT InTy = In.getOperand(0).getValueType();
8934
8935     // Check that all of the widened source types are the same.
8936     if (SourceType == MVT::Other)
8937       // First time.
8938       SourceType = InTy;
8939     else if (InTy != SourceType) {
8940       // Multiple income types. Abort.
8941       SourceType = MVT::Other;
8942       break;
8943     }
8944
8945     // Check if all of the extends are ANY_EXTENDs.
8946     AllAnyExt &= AnyExt;
8947   }
8948
8949   // In order to have valid types, all of the inputs must be extended from the
8950   // same source type and all of the inputs must be any or zero extend.
8951   // Scalar sizes must be a power of two.
8952   EVT OutScalarTy = VT.getScalarType();
8953   bool ValidTypes = SourceType != MVT::Other &&
8954                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8955                  isPowerOf2_32(SourceType.getSizeInBits());
8956
8957   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8958   // turn into a single shuffle instruction.
8959   if (!ValidTypes)
8960     return SDValue();
8961
8962   bool isLE = TLI.isLittleEndian();
8963   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8964   assert(ElemRatio > 1 && "Invalid element size ratio");
8965   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8966                                DAG.getConstant(0, SourceType);
8967
8968   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8969   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8970
8971   // Populate the new build_vector
8972   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8973     SDValue Cast = N->getOperand(i);
8974     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8975             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8976             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8977     SDValue In;
8978     if (Cast.getOpcode() == ISD::UNDEF)
8979       In = DAG.getUNDEF(SourceType);
8980     else
8981       In = Cast->getOperand(0);
8982     unsigned Index = isLE ? (i * ElemRatio) :
8983                             (i * ElemRatio + (ElemRatio - 1));
8984
8985     assert(Index < Ops.size() && "Invalid index");
8986     Ops[Index] = In;
8987   }
8988
8989   // The type of the new BUILD_VECTOR node.
8990   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8991   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8992          "Invalid vector size");
8993   // Check if the new vector type is legal.
8994   if (!isTypeLegal(VecVT)) return SDValue();
8995
8996   // Make the new BUILD_VECTOR.
8997   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8998
8999   // The new BUILD_VECTOR node has the potential to be further optimized.
9000   AddToWorkList(BV.getNode());
9001   // Bitcast to the desired type.
9002   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9003 }
9004
9005 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9006   EVT VT = N->getValueType(0);
9007
9008   unsigned NumInScalars = N->getNumOperands();
9009   SDLoc dl(N);
9010
9011   EVT SrcVT = MVT::Other;
9012   unsigned Opcode = ISD::DELETED_NODE;
9013   unsigned NumDefs = 0;
9014
9015   for (unsigned i = 0; i != NumInScalars; ++i) {
9016     SDValue In = N->getOperand(i);
9017     unsigned Opc = In.getOpcode();
9018
9019     if (Opc == ISD::UNDEF)
9020       continue;
9021
9022     // If all scalar values are floats and converted from integers.
9023     if (Opcode == ISD::DELETED_NODE &&
9024         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9025       Opcode = Opc;
9026     }
9027
9028     if (Opc != Opcode)
9029       return SDValue();
9030
9031     EVT InVT = In.getOperand(0).getValueType();
9032
9033     // If all scalar values are typed differently, bail out. It's chosen to
9034     // simplify BUILD_VECTOR of integer types.
9035     if (SrcVT == MVT::Other)
9036       SrcVT = InVT;
9037     if (SrcVT != InVT)
9038       return SDValue();
9039     NumDefs++;
9040   }
9041
9042   // If the vector has just one element defined, it's not worth to fold it into
9043   // a vectorized one.
9044   if (NumDefs < 2)
9045     return SDValue();
9046
9047   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9048          && "Should only handle conversion from integer to float.");
9049   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9050
9051   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9052
9053   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9054     return SDValue();
9055
9056   SmallVector<SDValue, 8> Opnds;
9057   for (unsigned i = 0; i != NumInScalars; ++i) {
9058     SDValue In = N->getOperand(i);
9059
9060     if (In.getOpcode() == ISD::UNDEF)
9061       Opnds.push_back(DAG.getUNDEF(SrcVT));
9062     else
9063       Opnds.push_back(In.getOperand(0));
9064   }
9065   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9066                            &Opnds[0], Opnds.size());
9067   AddToWorkList(BV.getNode());
9068
9069   return DAG.getNode(Opcode, dl, VT, BV);
9070 }
9071
9072 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9073   unsigned NumInScalars = N->getNumOperands();
9074   SDLoc dl(N);
9075   EVT VT = N->getValueType(0);
9076
9077   // A vector built entirely of undefs is undef.
9078   if (ISD::allOperandsUndef(N))
9079     return DAG.getUNDEF(VT);
9080
9081   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9082   if (V.getNode())
9083     return V;
9084
9085   V = reduceBuildVecConvertToConvertBuildVec(N);
9086   if (V.getNode())
9087     return V;
9088
9089   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9090   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9091   // at most two distinct vectors, turn this into a shuffle node.
9092
9093   // May only combine to shuffle after legalize if shuffle is legal.
9094   if (LegalOperations &&
9095       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9096     return SDValue();
9097
9098   SDValue VecIn1, VecIn2;
9099   for (unsigned i = 0; i != NumInScalars; ++i) {
9100     // Ignore undef inputs.
9101     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9102
9103     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9104     // constant index, bail out.
9105     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9106         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9107       VecIn1 = VecIn2 = SDValue(0, 0);
9108       break;
9109     }
9110
9111     // We allow up to two distinct input vectors.
9112     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9113     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9114       continue;
9115
9116     if (VecIn1.getNode() == 0) {
9117       VecIn1 = ExtractedFromVec;
9118     } else if (VecIn2.getNode() == 0) {
9119       VecIn2 = ExtractedFromVec;
9120     } else {
9121       // Too many inputs.
9122       VecIn1 = VecIn2 = SDValue(0, 0);
9123       break;
9124     }
9125   }
9126
9127     // If everything is good, we can make a shuffle operation.
9128   if (VecIn1.getNode()) {
9129     SmallVector<int, 8> Mask;
9130     for (unsigned i = 0; i != NumInScalars; ++i) {
9131       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9132         Mask.push_back(-1);
9133         continue;
9134       }
9135
9136       // If extracting from the first vector, just use the index directly.
9137       SDValue Extract = N->getOperand(i);
9138       SDValue ExtVal = Extract.getOperand(1);
9139       if (Extract.getOperand(0) == VecIn1) {
9140         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9141         if (ExtIndex > VT.getVectorNumElements())
9142           return SDValue();
9143
9144         Mask.push_back(ExtIndex);
9145         continue;
9146       }
9147
9148       // Otherwise, use InIdx + VecSize
9149       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9150       Mask.push_back(Idx+NumInScalars);
9151     }
9152
9153     // We can't generate a shuffle node with mismatched input and output types.
9154     // Attempt to transform a single input vector to the correct type.
9155     if ((VT != VecIn1.getValueType())) {
9156       // We don't support shuffeling between TWO values of different types.
9157       if (VecIn2.getNode() != 0)
9158         return SDValue();
9159
9160       // We only support widening of vectors which are half the size of the
9161       // output registers. For example XMM->YMM widening on X86 with AVX.
9162       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9163         return SDValue();
9164
9165       // If the input vector type has a different base type to the output
9166       // vector type, bail out.
9167       if (VecIn1.getValueType().getVectorElementType() !=
9168           VT.getVectorElementType())
9169         return SDValue();
9170
9171       // Widen the input vector by adding undef values.
9172       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9173                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9174     }
9175
9176     // If VecIn2 is unused then change it to undef.
9177     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9178
9179     // Check that we were able to transform all incoming values to the same
9180     // type.
9181     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9182         VecIn1.getValueType() != VT)
9183           return SDValue();
9184
9185     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9186     if (!isTypeLegal(VT))
9187       return SDValue();
9188
9189     // Return the new VECTOR_SHUFFLE node.
9190     SDValue Ops[2];
9191     Ops[0] = VecIn1;
9192     Ops[1] = VecIn2;
9193     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9194   }
9195
9196   return SDValue();
9197 }
9198
9199 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9200   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9201   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9202   // inputs come from at most two distinct vectors, turn this into a shuffle
9203   // node.
9204
9205   // If we only have one input vector, we don't need to do any concatenation.
9206   if (N->getNumOperands() == 1)
9207     return N->getOperand(0);
9208
9209   // Check if all of the operands are undefs.
9210   if (ISD::allOperandsUndef(N))
9211     return DAG.getUNDEF(N->getValueType(0));
9212
9213   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9214   // nodes often generate nop CONCAT_VECTOR nodes.
9215   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9216   // place the incoming vectors at the exact same location.
9217   SDValue SingleSource = SDValue();
9218   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9219
9220   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9221     SDValue Op = N->getOperand(i);
9222
9223     if (Op.getOpcode() == ISD::UNDEF)
9224       continue;
9225
9226     // Check if this is the identity extract:
9227     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9228       return SDValue();
9229
9230     // Find the single incoming vector for the extract_subvector.
9231     if (SingleSource.getNode()) {
9232       if (Op.getOperand(0) != SingleSource)
9233         return SDValue();
9234     } else {
9235       SingleSource = Op.getOperand(0);
9236
9237       // Check the source type is the same as the type of the result.
9238       // If not, this concat may extend the vector, so we can not
9239       // optimize it away.
9240       if (SingleSource.getValueType() != N->getValueType(0))
9241         return SDValue();
9242     }
9243
9244     unsigned IdentityIndex = i * PartNumElem;
9245     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9246     // The extract index must be constant.
9247     if (!CS)
9248       return SDValue();
9249
9250     // Check that we are reading from the identity index.
9251     if (CS->getZExtValue() != IdentityIndex)
9252       return SDValue();
9253   }
9254
9255   if (SingleSource.getNode())
9256     return SingleSource;
9257
9258   return SDValue();
9259 }
9260
9261 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9262   EVT NVT = N->getValueType(0);
9263   SDValue V = N->getOperand(0);
9264
9265   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9266     // Combine:
9267     //    (extract_subvec (concat V1, V2, ...), i)
9268     // Into:
9269     //    Vi if possible
9270     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9271     if (V->getOperand(0).getValueType() != NVT)
9272       return SDValue();
9273     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9274     unsigned NumElems = NVT.getVectorNumElements();
9275     assert((Idx % NumElems) == 0 &&
9276            "IDX in concat is not a multiple of the result vector length.");
9277     return V->getOperand(Idx / NumElems);
9278   }
9279
9280   // Skip bitcasting
9281   if (V->getOpcode() == ISD::BITCAST)
9282     V = V.getOperand(0);
9283
9284   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9285     SDLoc dl(N);
9286     // Handle only simple case where vector being inserted and vector
9287     // being extracted are of same type, and are half size of larger vectors.
9288     EVT BigVT = V->getOperand(0).getValueType();
9289     EVT SmallVT = V->getOperand(1).getValueType();
9290     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9291       return SDValue();
9292
9293     // Only handle cases where both indexes are constants with the same type.
9294     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9295     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9296
9297     if (InsIdx && ExtIdx &&
9298         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9299         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9300       // Combine:
9301       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9302       // Into:
9303       //    indices are equal or bit offsets are equal => V1
9304       //    otherwise => (extract_subvec V1, ExtIdx)
9305       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9306           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9307         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9308       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9309                          DAG.getNode(ISD::BITCAST, dl,
9310                                      N->getOperand(0).getValueType(),
9311                                      V->getOperand(0)), N->getOperand(1));
9312     }
9313   }
9314
9315   return SDValue();
9316 }
9317
9318 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9319 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9320   EVT VT = N->getValueType(0);
9321   unsigned NumElts = VT.getVectorNumElements();
9322
9323   SDValue N0 = N->getOperand(0);
9324   SDValue N1 = N->getOperand(1);
9325   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9326
9327   SmallVector<SDValue, 4> Ops;
9328   EVT ConcatVT = N0.getOperand(0).getValueType();
9329   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9330   unsigned NumConcats = NumElts / NumElemsPerConcat;
9331
9332   // Look at every vector that's inserted. We're looking for exact
9333   // subvector-sized copies from a concatenated vector
9334   for (unsigned I = 0; I != NumConcats; ++I) {
9335     // Make sure we're dealing with a copy.
9336     unsigned Begin = I * NumElemsPerConcat;
9337     bool AllUndef = true, NoUndef = true;
9338     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9339       if (SVN->getMaskElt(J) >= 0)
9340         AllUndef = false;
9341       else
9342         NoUndef = false;
9343     }
9344
9345     if (NoUndef) {
9346       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9347         return SDValue();
9348
9349       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9350         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9351           return SDValue();
9352
9353       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9354       if (FirstElt < N0.getNumOperands())
9355         Ops.push_back(N0.getOperand(FirstElt));
9356       else
9357         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9358
9359     } else if (AllUndef) {
9360       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9361     } else { // Mixed with general masks and undefs, can't do optimization.
9362       return SDValue();
9363     }
9364   }
9365
9366   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9367                      Ops.size());
9368 }
9369
9370 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9371   EVT VT = N->getValueType(0);
9372   unsigned NumElts = VT.getVectorNumElements();
9373
9374   SDValue N0 = N->getOperand(0);
9375   SDValue N1 = N->getOperand(1);
9376
9377   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9378
9379   // Canonicalize shuffle undef, undef -> undef
9380   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9381     return DAG.getUNDEF(VT);
9382
9383   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9384
9385   // Canonicalize shuffle v, v -> v, undef
9386   if (N0 == N1) {
9387     SmallVector<int, 8> NewMask;
9388     for (unsigned i = 0; i != NumElts; ++i) {
9389       int Idx = SVN->getMaskElt(i);
9390       if (Idx >= (int)NumElts) Idx -= NumElts;
9391       NewMask.push_back(Idx);
9392     }
9393     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9394                                 &NewMask[0]);
9395   }
9396
9397   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9398   if (N0.getOpcode() == ISD::UNDEF) {
9399     SmallVector<int, 8> NewMask;
9400     for (unsigned i = 0; i != NumElts; ++i) {
9401       int Idx = SVN->getMaskElt(i);
9402       if (Idx >= 0) {
9403         if (Idx >= (int)NumElts)
9404           Idx -= NumElts;
9405         else
9406           Idx = -1; // remove reference to lhs
9407       }
9408       NewMask.push_back(Idx);
9409     }
9410     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9411                                 &NewMask[0]);
9412   }
9413
9414   // Remove references to rhs if it is undef
9415   if (N1.getOpcode() == ISD::UNDEF) {
9416     bool Changed = false;
9417     SmallVector<int, 8> NewMask;
9418     for (unsigned i = 0; i != NumElts; ++i) {
9419       int Idx = SVN->getMaskElt(i);
9420       if (Idx >= (int)NumElts) {
9421         Idx = -1;
9422         Changed = true;
9423       }
9424       NewMask.push_back(Idx);
9425     }
9426     if (Changed)
9427       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9428   }
9429
9430   // If it is a splat, check if the argument vector is another splat or a
9431   // build_vector with all scalar elements the same.
9432   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9433     SDNode *V = N0.getNode();
9434
9435     // If this is a bit convert that changes the element type of the vector but
9436     // not the number of vector elements, look through it.  Be careful not to
9437     // look though conversions that change things like v4f32 to v2f64.
9438     if (V->getOpcode() == ISD::BITCAST) {
9439       SDValue ConvInput = V->getOperand(0);
9440       if (ConvInput.getValueType().isVector() &&
9441           ConvInput.getValueType().getVectorNumElements() == NumElts)
9442         V = ConvInput.getNode();
9443     }
9444
9445     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9446       assert(V->getNumOperands() == NumElts &&
9447              "BUILD_VECTOR has wrong number of operands");
9448       SDValue Base;
9449       bool AllSame = true;
9450       for (unsigned i = 0; i != NumElts; ++i) {
9451         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9452           Base = V->getOperand(i);
9453           break;
9454         }
9455       }
9456       // Splat of <u, u, u, u>, return <u, u, u, u>
9457       if (!Base.getNode())
9458         return N0;
9459       for (unsigned i = 0; i != NumElts; ++i) {
9460         if (V->getOperand(i) != Base) {
9461           AllSame = false;
9462           break;
9463         }
9464       }
9465       // Splat of <x, x, x, x>, return <x, x, x, x>
9466       if (AllSame)
9467         return N0;
9468     }
9469   }
9470
9471   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9472       Level < AfterLegalizeVectorOps &&
9473       (N1.getOpcode() == ISD::UNDEF ||
9474       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9475        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9476     SDValue V = partitionShuffleOfConcats(N, DAG);
9477
9478     if (V.getNode())
9479       return V;
9480   }
9481
9482   // If this shuffle node is simply a swizzle of another shuffle node,
9483   // and it reverses the swizzle of the previous shuffle then we can
9484   // optimize shuffle(shuffle(x, undef), undef) -> x.
9485   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9486       N1.getOpcode() == ISD::UNDEF) {
9487
9488     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9489
9490     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9491     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9492       return SDValue();
9493
9494     // The incoming shuffle must be of the same type as the result of the
9495     // current shuffle.
9496     assert(OtherSV->getOperand(0).getValueType() == VT &&
9497            "Shuffle types don't match");
9498
9499     for (unsigned i = 0; i != NumElts; ++i) {
9500       int Idx = SVN->getMaskElt(i);
9501       assert(Idx < (int)NumElts && "Index references undef operand");
9502       // Next, this index comes from the first value, which is the incoming
9503       // shuffle. Adopt the incoming index.
9504       if (Idx >= 0)
9505         Idx = OtherSV->getMaskElt(Idx);
9506
9507       // The combined shuffle must map each index to itself.
9508       if (Idx >= 0 && (unsigned)Idx != i)
9509         return SDValue();
9510     }
9511
9512     return OtherSV->getOperand(0);
9513   }
9514
9515   return SDValue();
9516 }
9517
9518 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9519 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9520 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9521 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9522 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9523   EVT VT = N->getValueType(0);
9524   SDLoc dl(N);
9525   SDValue LHS = N->getOperand(0);
9526   SDValue RHS = N->getOperand(1);
9527   if (N->getOpcode() == ISD::AND) {
9528     if (RHS.getOpcode() == ISD::BITCAST)
9529       RHS = RHS.getOperand(0);
9530     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9531       SmallVector<int, 8> Indices;
9532       unsigned NumElts = RHS.getNumOperands();
9533       for (unsigned i = 0; i != NumElts; ++i) {
9534         SDValue Elt = RHS.getOperand(i);
9535         if (!isa<ConstantSDNode>(Elt))
9536           return SDValue();
9537
9538         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9539           Indices.push_back(i);
9540         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9541           Indices.push_back(NumElts);
9542         else
9543           return SDValue();
9544       }
9545
9546       // Let's see if the target supports this vector_shuffle.
9547       EVT RVT = RHS.getValueType();
9548       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9549         return SDValue();
9550
9551       // Return the new VECTOR_SHUFFLE node.
9552       EVT EltVT = RVT.getVectorElementType();
9553       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9554                                      DAG.getConstant(0, EltVT));
9555       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9556                                  RVT, &ZeroOps[0], ZeroOps.size());
9557       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9558       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9559       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9560     }
9561   }
9562
9563   return SDValue();
9564 }
9565
9566 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9567 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9568   assert(N->getValueType(0).isVector() &&
9569          "SimplifyVBinOp only works on vectors!");
9570
9571   SDValue LHS = N->getOperand(0);
9572   SDValue RHS = N->getOperand(1);
9573   SDValue Shuffle = XformToShuffleWithZero(N);
9574   if (Shuffle.getNode()) return Shuffle;
9575
9576   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9577   // this operation.
9578   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9579       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9580     SmallVector<SDValue, 8> Ops;
9581     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9582       SDValue LHSOp = LHS.getOperand(i);
9583       SDValue RHSOp = RHS.getOperand(i);
9584       // If these two elements can't be folded, bail out.
9585       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9586            LHSOp.getOpcode() != ISD::Constant &&
9587            LHSOp.getOpcode() != ISD::ConstantFP) ||
9588           (RHSOp.getOpcode() != ISD::UNDEF &&
9589            RHSOp.getOpcode() != ISD::Constant &&
9590            RHSOp.getOpcode() != ISD::ConstantFP))
9591         break;
9592
9593       // Can't fold divide by zero.
9594       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9595           N->getOpcode() == ISD::FDIV) {
9596         if ((RHSOp.getOpcode() == ISD::Constant &&
9597              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9598             (RHSOp.getOpcode() == ISD::ConstantFP &&
9599              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9600           break;
9601       }
9602
9603       EVT VT = LHSOp.getValueType();
9604       EVT RVT = RHSOp.getValueType();
9605       if (RVT != VT) {
9606         // Integer BUILD_VECTOR operands may have types larger than the element
9607         // size (e.g., when the element type is not legal).  Prior to type
9608         // legalization, the types may not match between the two BUILD_VECTORS.
9609         // Truncate one of the operands to make them match.
9610         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9611           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9612         } else {
9613           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9614           VT = RVT;
9615         }
9616       }
9617       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9618                                    LHSOp, RHSOp);
9619       if (FoldOp.getOpcode() != ISD::UNDEF &&
9620           FoldOp.getOpcode() != ISD::Constant &&
9621           FoldOp.getOpcode() != ISD::ConstantFP)
9622         break;
9623       Ops.push_back(FoldOp);
9624       AddToWorkList(FoldOp.getNode());
9625     }
9626
9627     if (Ops.size() == LHS.getNumOperands())
9628       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9629                          LHS.getValueType(), &Ops[0], Ops.size());
9630   }
9631
9632   return SDValue();
9633 }
9634
9635 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9636 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9637   assert(N->getValueType(0).isVector() &&
9638          "SimplifyVUnaryOp only works on vectors!");
9639
9640   SDValue N0 = N->getOperand(0);
9641
9642   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9643     return SDValue();
9644
9645   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9646   SmallVector<SDValue, 8> Ops;
9647   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9648     SDValue Op = N0.getOperand(i);
9649     if (Op.getOpcode() != ISD::UNDEF &&
9650         Op.getOpcode() != ISD::ConstantFP)
9651       break;
9652     EVT EltVT = Op.getValueType();
9653     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9654     if (FoldOp.getOpcode() != ISD::UNDEF &&
9655         FoldOp.getOpcode() != ISD::ConstantFP)
9656       break;
9657     Ops.push_back(FoldOp);
9658     AddToWorkList(FoldOp.getNode());
9659   }
9660
9661   if (Ops.size() != N0.getNumOperands())
9662     return SDValue();
9663
9664   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9665                      N0.getValueType(), &Ops[0], Ops.size());
9666 }
9667
9668 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9669                                     SDValue N1, SDValue N2){
9670   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9671
9672   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9673                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9674
9675   // If we got a simplified select_cc node back from SimplifySelectCC, then
9676   // break it down into a new SETCC node, and a new SELECT node, and then return
9677   // the SELECT node, since we were called with a SELECT node.
9678   if (SCC.getNode()) {
9679     // Check to see if we got a select_cc back (to turn into setcc/select).
9680     // Otherwise, just return whatever node we got back, like fabs.
9681     if (SCC.getOpcode() == ISD::SELECT_CC) {
9682       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9683                                   N0.getValueType(),
9684                                   SCC.getOperand(0), SCC.getOperand(1),
9685                                   SCC.getOperand(4));
9686       AddToWorkList(SETCC.getNode());
9687       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9688                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9689     }
9690
9691     return SCC;
9692   }
9693   return SDValue();
9694 }
9695
9696 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9697 /// are the two values being selected between, see if we can simplify the
9698 /// select.  Callers of this should assume that TheSelect is deleted if this
9699 /// returns true.  As such, they should return the appropriate thing (e.g. the
9700 /// node) back to the top-level of the DAG combiner loop to avoid it being
9701 /// looked at.
9702 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9703                                     SDValue RHS) {
9704
9705   // Cannot simplify select with vector condition
9706   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9707
9708   // If this is a select from two identical things, try to pull the operation
9709   // through the select.
9710   if (LHS.getOpcode() != RHS.getOpcode() ||
9711       !LHS.hasOneUse() || !RHS.hasOneUse())
9712     return false;
9713
9714   // If this is a load and the token chain is identical, replace the select
9715   // of two loads with a load through a select of the address to load from.
9716   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9717   // constants have been dropped into the constant pool.
9718   if (LHS.getOpcode() == ISD::LOAD) {
9719     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9720     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9721
9722     // Token chains must be identical.
9723     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9724         // Do not let this transformation reduce the number of volatile loads.
9725         LLD->isVolatile() || RLD->isVolatile() ||
9726         // If this is an EXTLOAD, the VT's must match.
9727         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9728         // If this is an EXTLOAD, the kind of extension must match.
9729         (LLD->getExtensionType() != RLD->getExtensionType() &&
9730          // The only exception is if one of the extensions is anyext.
9731          LLD->getExtensionType() != ISD::EXTLOAD &&
9732          RLD->getExtensionType() != ISD::EXTLOAD) ||
9733         // FIXME: this discards src value information.  This is
9734         // over-conservative. It would be beneficial to be able to remember
9735         // both potential memory locations.  Since we are discarding
9736         // src value info, don't do the transformation if the memory
9737         // locations are not in the default address space.
9738         LLD->getPointerInfo().getAddrSpace() != 0 ||
9739         RLD->getPointerInfo().getAddrSpace() != 0 ||
9740         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9741                                       LLD->getBasePtr().getValueType()))
9742       return false;
9743
9744     // Check that the select condition doesn't reach either load.  If so,
9745     // folding this will induce a cycle into the DAG.  If not, this is safe to
9746     // xform, so create a select of the addresses.
9747     SDValue Addr;
9748     if (TheSelect->getOpcode() == ISD::SELECT) {
9749       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9750       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9751           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9752         return false;
9753       // The loads must not depend on one another.
9754       if (LLD->isPredecessorOf(RLD) ||
9755           RLD->isPredecessorOf(LLD))
9756         return false;
9757       Addr = DAG.getSelect(SDLoc(TheSelect),
9758                            LLD->getBasePtr().getValueType(),
9759                            TheSelect->getOperand(0), LLD->getBasePtr(),
9760                            RLD->getBasePtr());
9761     } else {  // Otherwise SELECT_CC
9762       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9763       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9764
9765       if ((LLD->hasAnyUseOfValue(1) &&
9766            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9767           (RLD->hasAnyUseOfValue(1) &&
9768            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9769         return false;
9770
9771       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9772                          LLD->getBasePtr().getValueType(),
9773                          TheSelect->getOperand(0),
9774                          TheSelect->getOperand(1),
9775                          LLD->getBasePtr(), RLD->getBasePtr(),
9776                          TheSelect->getOperand(4));
9777     }
9778
9779     SDValue Load;
9780     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9781       Load = DAG.getLoad(TheSelect->getValueType(0),
9782                          SDLoc(TheSelect),
9783                          // FIXME: Discards pointer info.
9784                          LLD->getChain(), Addr, MachinePointerInfo(),
9785                          LLD->isVolatile(), LLD->isNonTemporal(),
9786                          LLD->isInvariant(), LLD->getAlignment());
9787     } else {
9788       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9789                             RLD->getExtensionType() : LLD->getExtensionType(),
9790                             SDLoc(TheSelect),
9791                             TheSelect->getValueType(0),
9792                             // FIXME: Discards pointer info.
9793                             LLD->getChain(), Addr, MachinePointerInfo(),
9794                             LLD->getMemoryVT(), LLD->isVolatile(),
9795                             LLD->isNonTemporal(), LLD->getAlignment());
9796     }
9797
9798     // Users of the select now use the result of the load.
9799     CombineTo(TheSelect, Load);
9800
9801     // Users of the old loads now use the new load's chain.  We know the
9802     // old-load value is dead now.
9803     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9804     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9805     return true;
9806   }
9807
9808   return false;
9809 }
9810
9811 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9812 /// where 'cond' is the comparison specified by CC.
9813 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9814                                       SDValue N2, SDValue N3,
9815                                       ISD::CondCode CC, bool NotExtCompare) {
9816   // (x ? y : y) -> y.
9817   if (N2 == N3) return N2;
9818
9819   EVT VT = N2.getValueType();
9820   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9821   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9822   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9823
9824   // Determine if the condition we're dealing with is constant
9825   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9826                               N0, N1, CC, DL, false);
9827   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9828   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9829
9830   // fold select_cc true, x, y -> x
9831   if (SCCC && !SCCC->isNullValue())
9832     return N2;
9833   // fold select_cc false, x, y -> y
9834   if (SCCC && SCCC->isNullValue())
9835     return N3;
9836
9837   // Check to see if we can simplify the select into an fabs node
9838   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9839     // Allow either -0.0 or 0.0
9840     if (CFP->getValueAPF().isZero()) {
9841       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9842       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9843           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9844           N2 == N3.getOperand(0))
9845         return DAG.getNode(ISD::FABS, DL, VT, N0);
9846
9847       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9848       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9849           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9850           N2.getOperand(0) == N3)
9851         return DAG.getNode(ISD::FABS, DL, VT, N3);
9852     }
9853   }
9854
9855   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9856   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9857   // in it.  This is a win when the constant is not otherwise available because
9858   // it replaces two constant pool loads with one.  We only do this if the FP
9859   // type is known to be legal, because if it isn't, then we are before legalize
9860   // types an we want the other legalization to happen first (e.g. to avoid
9861   // messing with soft float) and if the ConstantFP is not legal, because if
9862   // it is legal, we may not need to store the FP constant in a constant pool.
9863   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9864     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9865       if (TLI.isTypeLegal(N2.getValueType()) &&
9866           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9867            TargetLowering::Legal) &&
9868           // If both constants have multiple uses, then we won't need to do an
9869           // extra load, they are likely around in registers for other users.
9870           (TV->hasOneUse() || FV->hasOneUse())) {
9871         Constant *Elts[] = {
9872           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9873           const_cast<ConstantFP*>(TV->getConstantFPValue())
9874         };
9875         Type *FPTy = Elts[0]->getType();
9876         const DataLayout &TD = *TLI.getDataLayout();
9877
9878         // Create a ConstantArray of the two constants.
9879         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9880         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9881                                             TD.getPrefTypeAlignment(FPTy));
9882         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9883
9884         // Get the offsets to the 0 and 1 element of the array so that we can
9885         // select between them.
9886         SDValue Zero = DAG.getIntPtrConstant(0);
9887         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9888         SDValue One = DAG.getIntPtrConstant(EltSize);
9889
9890         SDValue Cond = DAG.getSetCC(DL,
9891                                     getSetCCResultType(N0.getValueType()),
9892                                     N0, N1, CC);
9893         AddToWorkList(Cond.getNode());
9894         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9895                                           Cond, One, Zero);
9896         AddToWorkList(CstOffset.getNode());
9897         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9898                             CstOffset);
9899         AddToWorkList(CPIdx.getNode());
9900         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9901                            MachinePointerInfo::getConstantPool(), false,
9902                            false, false, Alignment);
9903
9904       }
9905     }
9906
9907   // Check to see if we can perform the "gzip trick", transforming
9908   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9909   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9910       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9911        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9912     EVT XType = N0.getValueType();
9913     EVT AType = N2.getValueType();
9914     if (XType.bitsGE(AType)) {
9915       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9916       // single-bit constant.
9917       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9918         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9919         ShCtV = XType.getSizeInBits()-ShCtV-1;
9920         SDValue ShCt = DAG.getConstant(ShCtV,
9921                                        getShiftAmountTy(N0.getValueType()));
9922         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9923                                     XType, N0, ShCt);
9924         AddToWorkList(Shift.getNode());
9925
9926         if (XType.bitsGT(AType)) {
9927           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9928           AddToWorkList(Shift.getNode());
9929         }
9930
9931         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9932       }
9933
9934       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9935                                   XType, N0,
9936                                   DAG.getConstant(XType.getSizeInBits()-1,
9937                                          getShiftAmountTy(N0.getValueType())));
9938       AddToWorkList(Shift.getNode());
9939
9940       if (XType.bitsGT(AType)) {
9941         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9942         AddToWorkList(Shift.getNode());
9943       }
9944
9945       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9946     }
9947   }
9948
9949   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9950   // where y is has a single bit set.
9951   // A plaintext description would be, we can turn the SELECT_CC into an AND
9952   // when the condition can be materialized as an all-ones register.  Any
9953   // single bit-test can be materialized as an all-ones register with
9954   // shift-left and shift-right-arith.
9955   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9956       N0->getValueType(0) == VT &&
9957       N1C && N1C->isNullValue() &&
9958       N2C && N2C->isNullValue()) {
9959     SDValue AndLHS = N0->getOperand(0);
9960     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9961     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9962       // Shift the tested bit over the sign bit.
9963       APInt AndMask = ConstAndRHS->getAPIntValue();
9964       SDValue ShlAmt =
9965         DAG.getConstant(AndMask.countLeadingZeros(),
9966                         getShiftAmountTy(AndLHS.getValueType()));
9967       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
9968
9969       // Now arithmetic right shift it all the way over, so the result is either
9970       // all-ones, or zero.
9971       SDValue ShrAmt =
9972         DAG.getConstant(AndMask.getBitWidth()-1,
9973                         getShiftAmountTy(Shl.getValueType()));
9974       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
9975
9976       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9977     }
9978   }
9979
9980   // fold select C, 16, 0 -> shl C, 4
9981   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9982     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9983       TargetLowering::ZeroOrOneBooleanContent) {
9984
9985     // If the caller doesn't want us to simplify this into a zext of a compare,
9986     // don't do it.
9987     if (NotExtCompare && N2C->getAPIntValue() == 1)
9988       return SDValue();
9989
9990     // Get a SetCC of the condition
9991     // NOTE: Don't create a SETCC if it's not legal on this target.
9992     if (!LegalOperations ||
9993         TLI.isOperationLegal(ISD::SETCC,
9994           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9995       SDValue Temp, SCC;
9996       // cast from setcc result type to select result type
9997       if (LegalTypes) {
9998         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
9999                             N0, N1, CC);
10000         if (N2.getValueType().bitsLT(SCC.getValueType()))
10001           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10002                                         N2.getValueType());
10003         else
10004           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10005                              N2.getValueType(), SCC);
10006       } else {
10007         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10008         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10009                            N2.getValueType(), SCC);
10010       }
10011
10012       AddToWorkList(SCC.getNode());
10013       AddToWorkList(Temp.getNode());
10014
10015       if (N2C->getAPIntValue() == 1)
10016         return Temp;
10017
10018       // shl setcc result by log2 n2c
10019       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10020                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10021                                          getShiftAmountTy(Temp.getValueType())));
10022     }
10023   }
10024
10025   // Check to see if this is the equivalent of setcc
10026   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10027   // otherwise, go ahead with the folds.
10028   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10029     EVT XType = N0.getValueType();
10030     if (!LegalOperations ||
10031         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10032       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10033       if (Res.getValueType() != VT)
10034         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10035       return Res;
10036     }
10037
10038     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10039     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10040         (!LegalOperations ||
10041          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10042       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10043       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10044                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10045                                        getShiftAmountTy(Ctlz.getValueType())));
10046     }
10047     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10048     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10049       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10050                                   XType, DAG.getConstant(0, XType), N0);
10051       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10052       return DAG.getNode(ISD::SRL, DL, XType,
10053                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10054                          DAG.getConstant(XType.getSizeInBits()-1,
10055                                          getShiftAmountTy(XType)));
10056     }
10057     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10058     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10059       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10060                                  DAG.getConstant(XType.getSizeInBits()-1,
10061                                          getShiftAmountTy(N0.getValueType())));
10062       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10063     }
10064   }
10065
10066   // Check to see if this is an integer abs.
10067   // select_cc setg[te] X,  0,  X, -X ->
10068   // select_cc setgt    X, -1,  X, -X ->
10069   // select_cc setl[te] X,  0, -X,  X ->
10070   // select_cc setlt    X,  1, -X,  X ->
10071   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10072   if (N1C) {
10073     ConstantSDNode *SubC = NULL;
10074     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10075          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10076         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10077       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10078     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10079               (N1C->isOne() && CC == ISD::SETLT)) &&
10080              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10081       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10082
10083     EVT XType = N0.getValueType();
10084     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10085       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10086                                   N0,
10087                                   DAG.getConstant(XType.getSizeInBits()-1,
10088                                          getShiftAmountTy(N0.getValueType())));
10089       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10090                                 XType, N0, Shift);
10091       AddToWorkList(Shift.getNode());
10092       AddToWorkList(Add.getNode());
10093       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10094     }
10095   }
10096
10097   return SDValue();
10098 }
10099
10100 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10101 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10102                                    SDValue N1, ISD::CondCode Cond,
10103                                    SDLoc DL, bool foldBooleans) {
10104   TargetLowering::DAGCombinerInfo
10105     DagCombineInfo(DAG, Level, false, this);
10106   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10107 }
10108
10109 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10110 /// return a DAG expression to select that will generate the same value by
10111 /// multiplying by a magic number.  See:
10112 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10113 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10114   std::vector<SDNode*> Built;
10115   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10116
10117   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10118        ii != ee; ++ii)
10119     AddToWorkList(*ii);
10120   return S;
10121 }
10122
10123 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10124 /// return a DAG expression to select that will generate the same value by
10125 /// multiplying by a magic number.  See:
10126 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10127 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10128   std::vector<SDNode*> Built;
10129   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10130
10131   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10132        ii != ee; ++ii)
10133     AddToWorkList(*ii);
10134   return S;
10135 }
10136
10137 /// FindBaseOffset - Return true if base is a frame index, which is known not
10138 // to alias with anything but itself.  Provides base object and offset as
10139 // results.
10140 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10141                            const GlobalValue *&GV, const void *&CV) {
10142   // Assume it is a primitive operation.
10143   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10144
10145   // If it's an adding a simple constant then integrate the offset.
10146   if (Base.getOpcode() == ISD::ADD) {
10147     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10148       Base = Base.getOperand(0);
10149       Offset += C->getZExtValue();
10150     }
10151   }
10152
10153   // Return the underlying GlobalValue, and update the Offset.  Return false
10154   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10155   // by multiple nodes with different offsets.
10156   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10157     GV = G->getGlobal();
10158     Offset += G->getOffset();
10159     return false;
10160   }
10161
10162   // Return the underlying Constant value, and update the Offset.  Return false
10163   // for ConstantSDNodes since the same constant pool entry may be represented
10164   // by multiple nodes with different offsets.
10165   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10166     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10167                                          : (const void *)C->getConstVal();
10168     Offset += C->getOffset();
10169     return false;
10170   }
10171   // If it's any of the following then it can't alias with anything but itself.
10172   return isa<FrameIndexSDNode>(Base);
10173 }
10174
10175 /// isAlias - Return true if there is any possibility that the two addresses
10176 /// overlap.
10177 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10178                           const Value *SrcValue1, int SrcValueOffset1,
10179                           unsigned SrcValueAlign1,
10180                           const MDNode *TBAAInfo1,
10181                           SDValue Ptr2, int64_t Size2,
10182                           const Value *SrcValue2, int SrcValueOffset2,
10183                           unsigned SrcValueAlign2,
10184                           const MDNode *TBAAInfo2) const {
10185   // If they are the same then they must be aliases.
10186   if (Ptr1 == Ptr2) return true;
10187
10188   // Gather base node and offset information.
10189   SDValue Base1, Base2;
10190   int64_t Offset1, Offset2;
10191   const GlobalValue *GV1, *GV2;
10192   const void *CV1, *CV2;
10193   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10194   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10195
10196   // If they have a same base address then check to see if they overlap.
10197   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10198     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10199
10200   // It is possible for different frame indices to alias each other, mostly
10201   // when tail call optimization reuses return address slots for arguments.
10202   // To catch this case, look up the actual index of frame indices to compute
10203   // the real alias relationship.
10204   if (isFrameIndex1 && isFrameIndex2) {
10205     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10206     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10207     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10208     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10209   }
10210
10211   // Otherwise, if we know what the bases are, and they aren't identical, then
10212   // we know they cannot alias.
10213   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10214     return false;
10215
10216   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10217   // compared to the size and offset of the access, we may be able to prove they
10218   // do not alias.  This check is conservative for now to catch cases created by
10219   // splitting vector types.
10220   if ((SrcValueAlign1 == SrcValueAlign2) &&
10221       (SrcValueOffset1 != SrcValueOffset2) &&
10222       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10223     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10224     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10225
10226     // There is no overlap between these relatively aligned accesses of similar
10227     // size, return no alias.
10228     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10229       return false;
10230   }
10231
10232   if (CombinerGlobalAA) {
10233     // Use alias analysis information.
10234     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10235     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10236     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10237     AliasAnalysis::AliasResult AAResult =
10238       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10239                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10240     if (AAResult == AliasAnalysis::NoAlias)
10241       return false;
10242   }
10243
10244   // Otherwise we have to assume they alias.
10245   return true;
10246 }
10247
10248 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10249   SDValue Ptr0, Ptr1;
10250   int64_t Size0, Size1;
10251   const Value *SrcValue0, *SrcValue1;
10252   int SrcValueOffset0, SrcValueOffset1;
10253   unsigned SrcValueAlign0, SrcValueAlign1;
10254   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10255   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10256                 SrcValueAlign0, SrcTBAAInfo0);
10257   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10258                 SrcValueAlign1, SrcTBAAInfo1);
10259   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10260                  SrcValueAlign0, SrcTBAAInfo0,
10261                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10262                  SrcValueAlign1, SrcTBAAInfo1);
10263 }
10264
10265 /// FindAliasInfo - Extracts the relevant alias information from the memory
10266 /// node.  Returns true if the operand was a load.
10267 bool DAGCombiner::FindAliasInfo(SDNode *N,
10268                                 SDValue &Ptr, int64_t &Size,
10269                                 const Value *&SrcValue,
10270                                 int &SrcValueOffset,
10271                                 unsigned &SrcValueAlign,
10272                                 const MDNode *&TBAAInfo) const {
10273   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10274
10275   Ptr = LS->getBasePtr();
10276   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10277   SrcValue = LS->getSrcValue();
10278   SrcValueOffset = LS->getSrcValueOffset();
10279   SrcValueAlign = LS->getOriginalAlignment();
10280   TBAAInfo = LS->getTBAAInfo();
10281   return isa<LoadSDNode>(LS);
10282 }
10283
10284 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10285 /// looking for aliasing nodes and adding them to the Aliases vector.
10286 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10287                                    SmallVectorImpl<SDValue> &Aliases) {
10288   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10289   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10290
10291   // Get alias information for node.
10292   SDValue Ptr;
10293   int64_t Size;
10294   const Value *SrcValue;
10295   int SrcValueOffset;
10296   unsigned SrcValueAlign;
10297   const MDNode *SrcTBAAInfo;
10298   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10299                               SrcValueAlign, SrcTBAAInfo);
10300
10301   // Starting off.
10302   Chains.push_back(OriginalChain);
10303   unsigned Depth = 0;
10304
10305   // Look at each chain and determine if it is an alias.  If so, add it to the
10306   // aliases list.  If not, then continue up the chain looking for the next
10307   // candidate.
10308   while (!Chains.empty()) {
10309     SDValue Chain = Chains.back();
10310     Chains.pop_back();
10311
10312     // For TokenFactor nodes, look at each operand and only continue up the
10313     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10314     // find more and revert to original chain since the xform is unlikely to be
10315     // profitable.
10316     //
10317     // FIXME: The depth check could be made to return the last non-aliasing
10318     // chain we found before we hit a tokenfactor rather than the original
10319     // chain.
10320     if (Depth > 6 || Aliases.size() == 2) {
10321       Aliases.clear();
10322       Aliases.push_back(OriginalChain);
10323       break;
10324     }
10325
10326     // Don't bother if we've been before.
10327     if (!Visited.insert(Chain.getNode()))
10328       continue;
10329
10330     switch (Chain.getOpcode()) {
10331     case ISD::EntryToken:
10332       // Entry token is ideal chain operand, but handled in FindBetterChain.
10333       break;
10334
10335     case ISD::LOAD:
10336     case ISD::STORE: {
10337       // Get alias information for Chain.
10338       SDValue OpPtr;
10339       int64_t OpSize;
10340       const Value *OpSrcValue;
10341       int OpSrcValueOffset;
10342       unsigned OpSrcValueAlign;
10343       const MDNode *OpSrcTBAAInfo;
10344       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10345                                     OpSrcValue, OpSrcValueOffset,
10346                                     OpSrcValueAlign,
10347                                     OpSrcTBAAInfo);
10348
10349       // If chain is alias then stop here.
10350       if (!(IsLoad && IsOpLoad) &&
10351           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10352                   SrcTBAAInfo,
10353                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10354                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10355         Aliases.push_back(Chain);
10356       } else {
10357         // Look further up the chain.
10358         Chains.push_back(Chain.getOperand(0));
10359         ++Depth;
10360       }
10361       break;
10362     }
10363
10364     case ISD::TokenFactor:
10365       // We have to check each of the operands of the token factor for "small"
10366       // token factors, so we queue them up.  Adding the operands to the queue
10367       // (stack) in reverse order maintains the original order and increases the
10368       // likelihood that getNode will find a matching token factor (CSE.)
10369       if (Chain.getNumOperands() > 16) {
10370         Aliases.push_back(Chain);
10371         break;
10372       }
10373       for (unsigned n = Chain.getNumOperands(); n;)
10374         Chains.push_back(Chain.getOperand(--n));
10375       ++Depth;
10376       break;
10377
10378     default:
10379       // For all other instructions we will just have to take what we can get.
10380       Aliases.push_back(Chain);
10381       break;
10382     }
10383   }
10384 }
10385
10386 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10387 /// for a better chain (aliasing node.)
10388 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10389   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10390
10391   // Accumulate all the aliases to this node.
10392   GatherAllAliases(N, OldChain, Aliases);
10393
10394   // If no operands then chain to entry token.
10395   if (Aliases.size() == 0)
10396     return DAG.getEntryNode();
10397
10398   // If a single operand then chain to it.  We don't need to revisit it.
10399   if (Aliases.size() == 1)
10400     return Aliases[0];
10401
10402   // Construct a custom tailored token factor.
10403   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10404                      &Aliases[0], Aliases.size());
10405 }
10406
10407 // SelectionDAG::Combine - This is the entry point for the file.
10408 //
10409 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10410                            CodeGenOpt::Level OptLevel) {
10411   /// run - This is the main entry point to this class.
10412   ///
10413   DAGCombiner(*this, AA, OptLevel).Run(Level);
10414 }