05a58b1c1b2224ab0ef56046c4cba4b5ea94ecbf
[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(SmallVector<SDNode*, 4> SetCCs,
158                          SDValue Trunc, SDValue ExtLoad, DebugLoc 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, DebugLoc 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(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
256     SDValue SimplifySelectCC(DebugLoc 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                           DebugLoc 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, DebugLoc 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                           SmallVector<SDValue, 8> &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       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
330     }
331
332     /// isTypeLegal - This method returns true if we are running before type
333     /// legalization or if the specified VT is legal.
334     bool isTypeLegal(const EVT &VT) {
335       if (!LegalTypes) return true;
336       return TLI.isTypeLegal(VT);
337     }
338   };
339 }
340
341
342 namespace {
343 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
344 /// nodes from the worklist.
345 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
346   DAGCombiner &DC;
347 public:
348   explicit WorkListRemover(DAGCombiner &dc)
349     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
350
351   virtual void NodeDeleted(SDNode *N, SDNode *E) {
352     DC.removeFromWorkList(N);
353   }
354 };
355 }
356
357 //===----------------------------------------------------------------------===//
358 //  TargetLowering::DAGCombinerInfo implementation
359 //===----------------------------------------------------------------------===//
360
361 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
362   ((DAGCombiner*)DC)->AddToWorkList(N);
363 }
364
365 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
366   ((DAGCombiner*)DC)->removeFromWorkList(N);
367 }
368
369 SDValue TargetLowering::DAGCombinerInfo::
370 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
371   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
372 }
373
374 SDValue TargetLowering::DAGCombinerInfo::
375 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
376   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
377 }
378
379
380 SDValue TargetLowering::DAGCombinerInfo::
381 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
382   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
383 }
384
385 void TargetLowering::DAGCombinerInfo::
386 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
387   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
388 }
389
390 //===----------------------------------------------------------------------===//
391 // Helper Functions
392 //===----------------------------------------------------------------------===//
393
394 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
395 /// specified expression for the same cost as the expression itself, or 2 if we
396 /// can compute the negated form more cheaply than the expression itself.
397 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
398                                const TargetLowering &TLI,
399                                const TargetOptions *Options,
400                                unsigned Depth = 0) {
401   // fneg is removable even if it has multiple uses.
402   if (Op.getOpcode() == ISD::FNEG) return 2;
403
404   // Don't allow anything with multiple uses.
405   if (!Op.hasOneUse()) return 0;
406
407   // Don't recurse exponentially.
408   if (Depth > 6) return 0;
409
410   switch (Op.getOpcode()) {
411   default: return false;
412   case ISD::ConstantFP:
413     // Don't invert constant FP values after legalize.  The negated constant
414     // isn't necessarily legal.
415     return LegalOperations ? 0 : 1;
416   case ISD::FADD:
417     // FIXME: determine better conditions for this xform.
418     if (!Options->UnsafeFPMath) return 0;
419
420     // After operation legalization, it might not be legal to create new FSUBs.
421     if (LegalOperations &&
422         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
423       return 0;
424
425     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
426     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
427                                     Options, Depth + 1))
428       return V;
429     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
430     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
431                               Depth + 1);
432   case ISD::FSUB:
433     // We can't turn -(A-B) into B-A when we honor signed zeros.
434     if (!Options->UnsafeFPMath) return 0;
435
436     // fold (fneg (fsub A, B)) -> (fsub B, A)
437     return 1;
438
439   case ISD::FMUL:
440   case ISD::FDIV:
441     if (Options->HonorSignDependentRoundingFPMath()) return 0;
442
443     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
444     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
445                                     Options, Depth + 1))
446       return V;
447
448     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
449                               Depth + 1);
450
451   case ISD::FP_EXTEND:
452   case ISD::FP_ROUND:
453   case ISD::FSIN:
454     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
455                               Depth + 1);
456   }
457 }
458
459 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
460 /// returns the newly negated expression.
461 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
462                                     bool LegalOperations, unsigned Depth = 0) {
463   // fneg is removable even if it has multiple uses.
464   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
465
466   // Don't allow anything with multiple uses.
467   assert(Op.hasOneUse() && "Unknown reuse!");
468
469   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
470   switch (Op.getOpcode()) {
471   default: llvm_unreachable("Unknown code");
472   case ISD::ConstantFP: {
473     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
474     V.changeSign();
475     return DAG.getConstantFP(V, Op.getValueType());
476   }
477   case ISD::FADD:
478     // FIXME: determine better conditions for this xform.
479     assert(DAG.getTarget().Options.UnsafeFPMath);
480
481     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
482     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
483                            DAG.getTargetLoweringInfo(),
484                            &DAG.getTarget().Options, Depth+1))
485       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
486                          GetNegatedExpression(Op.getOperand(0), DAG,
487                                               LegalOperations, Depth+1),
488                          Op.getOperand(1));
489     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
491                        GetNegatedExpression(Op.getOperand(1), DAG,
492                                             LegalOperations, Depth+1),
493                        Op.getOperand(0));
494   case ISD::FSUB:
495     // We can't turn -(A-B) into B-A when we honor signed zeros.
496     assert(DAG.getTarget().Options.UnsafeFPMath);
497
498     // fold (fneg (fsub 0, B)) -> B
499     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
500       if (N0CFP->getValueAPF().isZero())
501         return Op.getOperand(1);
502
503     // fold (fneg (fsub A, B)) -> (fsub B, A)
504     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
505                        Op.getOperand(1), Op.getOperand(0));
506
507   case ISD::FMUL:
508   case ISD::FDIV:
509     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
510
511     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
512     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513                            DAG.getTargetLoweringInfo(),
514                            &DAG.getTarget().Options, Depth+1))
515       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
516                          GetNegatedExpression(Op.getOperand(0), DAG,
517                                               LegalOperations, Depth+1),
518                          Op.getOperand(1));
519
520     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
521     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
522                        Op.getOperand(0),
523                        GetNegatedExpression(Op.getOperand(1), DAG,
524                                             LegalOperations, Depth+1));
525
526   case ISD::FP_EXTEND:
527   case ISD::FSIN:
528     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
529                        GetNegatedExpression(Op.getOperand(0), DAG,
530                                             LegalOperations, Depth+1));
531   case ISD::FP_ROUND:
532       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
533                          GetNegatedExpression(Op.getOperand(0), DAG,
534                                               LegalOperations, Depth+1),
535                          Op.getOperand(1));
536   }
537 }
538
539
540 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
541 // that selects between the values 1 and 0, making it equivalent to a setcc.
542 // Also, set the incoming LHS, RHS, and CC references to the appropriate
543 // nodes based on the type of node we are checking.  This simplifies life a
544 // bit for the callers.
545 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
546                               SDValue &CC) {
547   if (N.getOpcode() == ISD::SETCC) {
548     LHS = N.getOperand(0);
549     RHS = N.getOperand(1);
550     CC  = N.getOperand(2);
551     return true;
552   }
553   if (N.getOpcode() == ISD::SELECT_CC &&
554       N.getOperand(2).getOpcode() == ISD::Constant &&
555       N.getOperand(3).getOpcode() == ISD::Constant &&
556       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
557       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
558     LHS = N.getOperand(0);
559     RHS = N.getOperand(1);
560     CC  = N.getOperand(4);
561     return true;
562   }
563   return false;
564 }
565
566 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
567 // one use.  If this is true, it allows the users to invert the operation for
568 // free when it is profitable to do so.
569 static bool isOneUseSetCC(SDValue N) {
570   SDValue N0, N1, N2;
571   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
572     return true;
573   return false;
574 }
575
576 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
577                                     SDValue N0, SDValue N1) {
578   EVT VT = N0.getValueType();
579   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
580     if (isa<ConstantSDNode>(N1)) {
581       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
582       SDValue OpNode =
583         DAG.FoldConstantArithmetic(Opc, VT,
584                                    cast<ConstantSDNode>(N0.getOperand(1)),
585                                    cast<ConstantSDNode>(N1));
586       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
587     }
588     if (N0.hasOneUse()) {
589       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
590       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
591                                    N0.getOperand(0), N1);
592       AddToWorkList(OpNode.getNode());
593       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
594     }
595   }
596
597   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
598     if (isa<ConstantSDNode>(N0)) {
599       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
600       SDValue OpNode =
601         DAG.FoldConstantArithmetic(Opc, VT,
602                                    cast<ConstantSDNode>(N1.getOperand(1)),
603                                    cast<ConstantSDNode>(N0));
604       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
605     }
606     if (N1.hasOneUse()) {
607       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
608       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
609                                    N1.getOperand(0), N0);
610       AddToWorkList(OpNode.getNode());
611       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
612     }
613   }
614
615   return SDValue();
616 }
617
618 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
619                                bool AddTo) {
620   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
621   ++NodesCombined;
622   DEBUG(dbgs() << "\nReplacing.1 ";
623         N->dump(&DAG);
624         dbgs() << "\nWith: ";
625         To[0].getNode()->dump(&DAG);
626         dbgs() << " and " << NumTo-1 << " other values\n";
627         for (unsigned i = 0, e = NumTo; i != e; ++i)
628           assert((!To[i].getNode() ||
629                   N->getValueType(i) == To[i].getValueType()) &&
630                  "Cannot combine value to value of different type!"));
631   WorkListRemover DeadNodes(*this);
632   DAG.ReplaceAllUsesWith(N, To);
633   if (AddTo) {
634     // Push the new nodes and any users onto the worklist
635     for (unsigned i = 0, e = NumTo; i != e; ++i) {
636       if (To[i].getNode()) {
637         AddToWorkList(To[i].getNode());
638         AddUsersToWorkList(To[i].getNode());
639       }
640     }
641   }
642
643   // Finally, if the node is now dead, remove it from the graph.  The node
644   // may not be dead if the replacement process recursively simplified to
645   // something else needing this node.
646   if (N->use_empty()) {
647     // Nodes can be reintroduced into the worklist.  Make sure we do not
648     // process a node that has been replaced.
649     removeFromWorkList(N);
650
651     // Finally, since the node is now dead, remove it from the graph.
652     DAG.DeleteNode(N);
653   }
654   return SDValue(N, 0);
655 }
656
657 void DAGCombiner::
658 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
659   // Replace all uses.  If any nodes become isomorphic to other nodes and
660   // are deleted, make sure to remove them from our worklist.
661   WorkListRemover DeadNodes(*this);
662   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
663
664   // Push the new node and any (possibly new) users onto the worklist.
665   AddToWorkList(TLO.New.getNode());
666   AddUsersToWorkList(TLO.New.getNode());
667
668   // Finally, if the node is now dead, remove it from the graph.  The node
669   // may not be dead if the replacement process recursively simplified to
670   // something else needing this node.
671   if (TLO.Old.getNode()->use_empty()) {
672     removeFromWorkList(TLO.Old.getNode());
673
674     // If the operands of this node are only used by the node, they will now
675     // be dead.  Make sure to visit them first to delete dead nodes early.
676     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
677       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
678         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
679
680     DAG.DeleteNode(TLO.Old.getNode());
681   }
682 }
683
684 /// SimplifyDemandedBits - Check the specified integer node value to see if
685 /// it can be simplified or if things it uses can be simplified by bit
686 /// propagation.  If so, return true.
687 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
688   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
689   APInt KnownZero, KnownOne;
690   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
691     return false;
692
693   // Revisit the node.
694   AddToWorkList(Op.getNode());
695
696   // Replace the old value with the new one.
697   ++NodesCombined;
698   DEBUG(dbgs() << "\nReplacing.2 ";
699         TLO.Old.getNode()->dump(&DAG);
700         dbgs() << "\nWith: ";
701         TLO.New.getNode()->dump(&DAG);
702         dbgs() << '\n');
703
704   CommitTargetLoweringOpt(TLO);
705   return true;
706 }
707
708 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
709   DebugLoc dl = Load->getDebugLoc();
710   EVT VT = Load->getValueType(0);
711   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
712
713   DEBUG(dbgs() << "\nReplacing.9 ";
714         Load->dump(&DAG);
715         dbgs() << "\nWith: ";
716         Trunc.getNode()->dump(&DAG);
717         dbgs() << '\n');
718   WorkListRemover DeadNodes(*this);
719   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
720   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
721   removeFromWorkList(Load);
722   DAG.DeleteNode(Load);
723   AddToWorkList(Trunc.getNode());
724 }
725
726 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
727   Replace = false;
728   DebugLoc dl = Op.getDebugLoc();
729   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
730     EVT MemVT = LD->getMemoryVT();
731     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
732       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
733                                                   : ISD::EXTLOAD)
734       : LD->getExtensionType();
735     Replace = true;
736     return DAG.getExtLoad(ExtType, dl, PVT,
737                           LD->getChain(), LD->getBasePtr(),
738                           LD->getPointerInfo(),
739                           MemVT, LD->isVolatile(),
740                           LD->isNonTemporal(), LD->getAlignment());
741   }
742
743   unsigned Opc = Op.getOpcode();
744   switch (Opc) {
745   default: break;
746   case ISD::AssertSext:
747     return DAG.getNode(ISD::AssertSext, dl, PVT,
748                        SExtPromoteOperand(Op.getOperand(0), PVT),
749                        Op.getOperand(1));
750   case ISD::AssertZext:
751     return DAG.getNode(ISD::AssertZext, dl, PVT,
752                        ZExtPromoteOperand(Op.getOperand(0), PVT),
753                        Op.getOperand(1));
754   case ISD::Constant: {
755     unsigned ExtOpc =
756       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
757     return DAG.getNode(ExtOpc, dl, PVT, Op);
758   }
759   }
760
761   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
762     return SDValue();
763   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
764 }
765
766 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
767   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
768     return SDValue();
769   EVT OldVT = Op.getValueType();
770   DebugLoc dl = Op.getDebugLoc();
771   bool Replace = false;
772   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
773   if (NewOp.getNode() == 0)
774     return SDValue();
775   AddToWorkList(NewOp.getNode());
776
777   if (Replace)
778     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
779   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
780                      DAG.getValueType(OldVT));
781 }
782
783 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
784   EVT OldVT = Op.getValueType();
785   DebugLoc dl = Op.getDebugLoc();
786   bool Replace = false;
787   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
788   if (NewOp.getNode() == 0)
789     return SDValue();
790   AddToWorkList(NewOp.getNode());
791
792   if (Replace)
793     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
794   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
795 }
796
797 /// PromoteIntBinOp - Promote the specified integer binary operation if the
798 /// target indicates it is beneficial. e.g. On x86, it's usually better to
799 /// promote i16 operations to i32 since i16 instructions are longer.
800 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
801   if (!LegalOperations)
802     return SDValue();
803
804   EVT VT = Op.getValueType();
805   if (VT.isVector() || !VT.isInteger())
806     return SDValue();
807
808   // If operation type is 'undesirable', e.g. i16 on x86, consider
809   // promoting it.
810   unsigned Opc = Op.getOpcode();
811   if (TLI.isTypeDesirableForOp(Opc, VT))
812     return SDValue();
813
814   EVT PVT = VT;
815   // Consult target whether it is a good idea to promote this operation and
816   // what's the right type to promote it to.
817   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
818     assert(PVT != VT && "Don't know what type to promote to!");
819
820     bool Replace0 = false;
821     SDValue N0 = Op.getOperand(0);
822     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
823     if (NN0.getNode() == 0)
824       return SDValue();
825
826     bool Replace1 = false;
827     SDValue N1 = Op.getOperand(1);
828     SDValue NN1;
829     if (N0 == N1)
830       NN1 = NN0;
831     else {
832       NN1 = PromoteOperand(N1, PVT, Replace1);
833       if (NN1.getNode() == 0)
834         return SDValue();
835     }
836
837     AddToWorkList(NN0.getNode());
838     if (NN1.getNode())
839       AddToWorkList(NN1.getNode());
840
841     if (Replace0)
842       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
843     if (Replace1)
844       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
845
846     DEBUG(dbgs() << "\nPromoting ";
847           Op.getNode()->dump(&DAG));
848     DebugLoc dl = Op.getDebugLoc();
849     return DAG.getNode(ISD::TRUNCATE, dl, VT,
850                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
851   }
852   return SDValue();
853 }
854
855 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
856 /// target indicates it is beneficial. e.g. On x86, it's usually better to
857 /// promote i16 operations to i32 since i16 instructions are longer.
858 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
859   if (!LegalOperations)
860     return SDValue();
861
862   EVT VT = Op.getValueType();
863   if (VT.isVector() || !VT.isInteger())
864     return SDValue();
865
866   // If operation type is 'undesirable', e.g. i16 on x86, consider
867   // promoting it.
868   unsigned Opc = Op.getOpcode();
869   if (TLI.isTypeDesirableForOp(Opc, VT))
870     return SDValue();
871
872   EVT PVT = VT;
873   // Consult target whether it is a good idea to promote this operation and
874   // what's the right type to promote it to.
875   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
876     assert(PVT != VT && "Don't know what type to promote to!");
877
878     bool Replace = false;
879     SDValue N0 = Op.getOperand(0);
880     if (Opc == ISD::SRA)
881       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
882     else if (Opc == ISD::SRL)
883       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
884     else
885       N0 = PromoteOperand(N0, PVT, Replace);
886     if (N0.getNode() == 0)
887       return SDValue();
888
889     AddToWorkList(N0.getNode());
890     if (Replace)
891       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
892
893     DEBUG(dbgs() << "\nPromoting ";
894           Op.getNode()->dump(&DAG));
895     DebugLoc dl = Op.getDebugLoc();
896     return DAG.getNode(ISD::TRUNCATE, dl, VT,
897                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
898   }
899   return SDValue();
900 }
901
902 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
903   if (!LegalOperations)
904     return SDValue();
905
906   EVT VT = Op.getValueType();
907   if (VT.isVector() || !VT.isInteger())
908     return SDValue();
909
910   // If operation type is 'undesirable', e.g. i16 on x86, consider
911   // promoting it.
912   unsigned Opc = Op.getOpcode();
913   if (TLI.isTypeDesirableForOp(Opc, VT))
914     return SDValue();
915
916   EVT PVT = VT;
917   // Consult target whether it is a good idea to promote this operation and
918   // what's the right type to promote it to.
919   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
920     assert(PVT != VT && "Don't know what type to promote to!");
921     // fold (aext (aext x)) -> (aext x)
922     // fold (aext (zext x)) -> (zext x)
923     // fold (aext (sext x)) -> (sext x)
924     DEBUG(dbgs() << "\nPromoting ";
925           Op.getNode()->dump(&DAG));
926     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
927   }
928   return SDValue();
929 }
930
931 bool DAGCombiner::PromoteLoad(SDValue Op) {
932   if (!LegalOperations)
933     return false;
934
935   EVT VT = Op.getValueType();
936   if (VT.isVector() || !VT.isInteger())
937     return false;
938
939   // If operation type is 'undesirable', e.g. i16 on x86, consider
940   // promoting it.
941   unsigned Opc = Op.getOpcode();
942   if (TLI.isTypeDesirableForOp(Opc, VT))
943     return false;
944
945   EVT PVT = VT;
946   // Consult target whether it is a good idea to promote this operation and
947   // what's the right type to promote it to.
948   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
949     assert(PVT != VT && "Don't know what type to promote to!");
950
951     DebugLoc dl = Op.getDebugLoc();
952     SDNode *N = Op.getNode();
953     LoadSDNode *LD = cast<LoadSDNode>(N);
954     EVT MemVT = LD->getMemoryVT();
955     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
956       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
957                                                   : ISD::EXTLOAD)
958       : LD->getExtensionType();
959     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
960                                    LD->getChain(), LD->getBasePtr(),
961                                    LD->getPointerInfo(),
962                                    MemVT, LD->isVolatile(),
963                                    LD->isNonTemporal(), LD->getAlignment());
964     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
965
966     DEBUG(dbgs() << "\nPromoting ";
967           N->dump(&DAG);
968           dbgs() << "\nTo: ";
969           Result.getNode()->dump(&DAG);
970           dbgs() << '\n');
971     WorkListRemover DeadNodes(*this);
972     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
973     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
974     removeFromWorkList(N);
975     DAG.DeleteNode(N);
976     AddToWorkList(Result.getNode());
977     return true;
978   }
979   return false;
980 }
981
982
983 //===----------------------------------------------------------------------===//
984 //  Main DAG Combiner implementation
985 //===----------------------------------------------------------------------===//
986
987 void DAGCombiner::Run(CombineLevel AtLevel) {
988   // set the instance variables, so that the various visit routines may use it.
989   Level = AtLevel;
990   LegalOperations = Level >= AfterLegalizeVectorOps;
991   LegalTypes = Level >= AfterLegalizeTypes;
992
993   // Add all the dag nodes to the worklist.
994   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
995        E = DAG.allnodes_end(); I != E; ++I)
996     AddToWorkList(I);
997
998   // Create a dummy node (which is not added to allnodes), that adds a reference
999   // to the root node, preventing it from being deleted, and tracking any
1000   // changes of the root.
1001   HandleSDNode Dummy(DAG.getRoot());
1002
1003   // The root of the dag may dangle to deleted nodes until the dag combiner is
1004   // done.  Set it to null to avoid confusion.
1005   DAG.setRoot(SDValue());
1006
1007   // while the worklist isn't empty, find a node and
1008   // try and combine it.
1009   while (!WorkListContents.empty()) {
1010     SDNode *N;
1011     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1012     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1013     // worklist *should* contain, and check the node we want to visit is should
1014     // actually be visited.
1015     do {
1016       N = WorkListOrder.pop_back_val();
1017     } while (!WorkListContents.erase(N));
1018
1019     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1020     // N is deleted from the DAG, since they too may now be dead or may have a
1021     // reduced number of uses, allowing other xforms.
1022     if (N->use_empty() && N != &Dummy) {
1023       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1024         AddToWorkList(N->getOperand(i).getNode());
1025
1026       DAG.DeleteNode(N);
1027       continue;
1028     }
1029
1030     SDValue RV = combine(N);
1031
1032     if (RV.getNode() == 0)
1033       continue;
1034
1035     ++NodesCombined;
1036
1037     // If we get back the same node we passed in, rather than a new node or
1038     // zero, we know that the node must have defined multiple values and
1039     // CombineTo was used.  Since CombineTo takes care of the worklist
1040     // mechanics for us, we have no work to do in this case.
1041     if (RV.getNode() == N)
1042       continue;
1043
1044     assert(N->getOpcode() != ISD::DELETED_NODE &&
1045            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1046            "Node was deleted but visit returned new node!");
1047
1048     DEBUG(dbgs() << "\nReplacing.3 ";
1049           N->dump(&DAG);
1050           dbgs() << "\nWith: ";
1051           RV.getNode()->dump(&DAG);
1052           dbgs() << '\n');
1053
1054     // Transfer debug value.
1055     DAG.TransferDbgValues(SDValue(N, 0), RV);
1056     WorkListRemover DeadNodes(*this);
1057     if (N->getNumValues() == RV.getNode()->getNumValues())
1058       DAG.ReplaceAllUsesWith(N, RV.getNode());
1059     else {
1060       assert(N->getValueType(0) == RV.getValueType() &&
1061              N->getNumValues() == 1 && "Type mismatch");
1062       SDValue OpV = RV;
1063       DAG.ReplaceAllUsesWith(N, &OpV);
1064     }
1065
1066     // Push the new node and any users onto the worklist
1067     AddToWorkList(RV.getNode());
1068     AddUsersToWorkList(RV.getNode());
1069
1070     // Add any uses of the old node to the worklist in case this node is the
1071     // last one that uses them.  They may become dead after this node is
1072     // deleted.
1073     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1074       AddToWorkList(N->getOperand(i).getNode());
1075
1076     // Finally, if the node is now dead, remove it from the graph.  The node
1077     // may not be dead if the replacement process recursively simplified to
1078     // something else needing this node.
1079     if (N->use_empty()) {
1080       // Nodes can be reintroduced into the worklist.  Make sure we do not
1081       // process a node that has been replaced.
1082       removeFromWorkList(N);
1083
1084       // Finally, since the node is now dead, remove it from the graph.
1085       DAG.DeleteNode(N);
1086     }
1087   }
1088
1089   // If the root changed (e.g. it was a dead load, update the root).
1090   DAG.setRoot(Dummy.getValue());
1091   DAG.RemoveDeadNodes();
1092 }
1093
1094 SDValue DAGCombiner::visit(SDNode *N) {
1095   switch (N->getOpcode()) {
1096   default: break;
1097   case ISD::TokenFactor:        return visitTokenFactor(N);
1098   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1099   case ISD::ADD:                return visitADD(N);
1100   case ISD::SUB:                return visitSUB(N);
1101   case ISD::ADDC:               return visitADDC(N);
1102   case ISD::SUBC:               return visitSUBC(N);
1103   case ISD::ADDE:               return visitADDE(N);
1104   case ISD::SUBE:               return visitSUBE(N);
1105   case ISD::MUL:                return visitMUL(N);
1106   case ISD::SDIV:               return visitSDIV(N);
1107   case ISD::UDIV:               return visitUDIV(N);
1108   case ISD::SREM:               return visitSREM(N);
1109   case ISD::UREM:               return visitUREM(N);
1110   case ISD::MULHU:              return visitMULHU(N);
1111   case ISD::MULHS:              return visitMULHS(N);
1112   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1113   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1114   case ISD::SMULO:              return visitSMULO(N);
1115   case ISD::UMULO:              return visitUMULO(N);
1116   case ISD::SDIVREM:            return visitSDIVREM(N);
1117   case ISD::UDIVREM:            return visitUDIVREM(N);
1118   case ISD::AND:                return visitAND(N);
1119   case ISD::OR:                 return visitOR(N);
1120   case ISD::XOR:                return visitXOR(N);
1121   case ISD::SHL:                return visitSHL(N);
1122   case ISD::SRA:                return visitSRA(N);
1123   case ISD::SRL:                return visitSRL(N);
1124   case ISD::CTLZ:               return visitCTLZ(N);
1125   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1126   case ISD::CTTZ:               return visitCTTZ(N);
1127   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1128   case ISD::CTPOP:              return visitCTPOP(N);
1129   case ISD::SELECT:             return visitSELECT(N);
1130   case ISD::VSELECT:            return visitVSELECT(N);
1131   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1132   case ISD::SETCC:              return visitSETCC(N);
1133   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1134   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1135   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1136   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1137   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1138   case ISD::BITCAST:            return visitBITCAST(N);
1139   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1140   case ISD::FADD:               return visitFADD(N);
1141   case ISD::FSUB:               return visitFSUB(N);
1142   case ISD::FMUL:               return visitFMUL(N);
1143   case ISD::FMA:                return visitFMA(N);
1144   case ISD::FDIV:               return visitFDIV(N);
1145   case ISD::FREM:               return visitFREM(N);
1146   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1147   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1148   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1149   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1150   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1151   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1152   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1153   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1154   case ISD::FNEG:               return visitFNEG(N);
1155   case ISD::FABS:               return visitFABS(N);
1156   case ISD::FFLOOR:             return visitFFLOOR(N);
1157   case ISD::FCEIL:              return visitFCEIL(N);
1158   case ISD::FTRUNC:             return visitFTRUNC(N);
1159   case ISD::BRCOND:             return visitBRCOND(N);
1160   case ISD::BR_CC:              return visitBR_CC(N);
1161   case ISD::LOAD:               return visitLOAD(N);
1162   case ISD::STORE:              return visitSTORE(N);
1163   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1164   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1165   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1166   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1167   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1168   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1169   }
1170   return SDValue();
1171 }
1172
1173 SDValue DAGCombiner::combine(SDNode *N) {
1174   SDValue RV = visit(N);
1175
1176   // If nothing happened, try a target-specific DAG combine.
1177   if (RV.getNode() == 0) {
1178     assert(N->getOpcode() != ISD::DELETED_NODE &&
1179            "Node was deleted but visit returned NULL!");
1180
1181     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1182         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1183
1184       // Expose the DAG combiner to the target combiner impls.
1185       TargetLowering::DAGCombinerInfo
1186         DagCombineInfo(DAG, Level, false, this);
1187
1188       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1189     }
1190   }
1191
1192   // If nothing happened still, try promoting the operation.
1193   if (RV.getNode() == 0) {
1194     switch (N->getOpcode()) {
1195     default: break;
1196     case ISD::ADD:
1197     case ISD::SUB:
1198     case ISD::MUL:
1199     case ISD::AND:
1200     case ISD::OR:
1201     case ISD::XOR:
1202       RV = PromoteIntBinOp(SDValue(N, 0));
1203       break;
1204     case ISD::SHL:
1205     case ISD::SRA:
1206     case ISD::SRL:
1207       RV = PromoteIntShiftOp(SDValue(N, 0));
1208       break;
1209     case ISD::SIGN_EXTEND:
1210     case ISD::ZERO_EXTEND:
1211     case ISD::ANY_EXTEND:
1212       RV = PromoteExtend(SDValue(N, 0));
1213       break;
1214     case ISD::LOAD:
1215       if (PromoteLoad(SDValue(N, 0)))
1216         RV = SDValue(N, 0);
1217       break;
1218     }
1219   }
1220
1221   // If N is a commutative binary node, try commuting it to enable more
1222   // sdisel CSE.
1223   if (RV.getNode() == 0 &&
1224       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1225       N->getNumValues() == 1) {
1226     SDValue N0 = N->getOperand(0);
1227     SDValue N1 = N->getOperand(1);
1228
1229     // Constant operands are canonicalized to RHS.
1230     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1231       SDValue Ops[] = { N1, N0 };
1232       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1233                                             Ops, 2);
1234       if (CSENode)
1235         return SDValue(CSENode, 0);
1236     }
1237   }
1238
1239   return RV;
1240 }
1241
1242 /// getInputChainForNode - Given a node, return its input chain if it has one,
1243 /// otherwise return a null sd operand.
1244 static SDValue getInputChainForNode(SDNode *N) {
1245   if (unsigned NumOps = N->getNumOperands()) {
1246     if (N->getOperand(0).getValueType() == MVT::Other)
1247       return N->getOperand(0);
1248     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1249       return N->getOperand(NumOps-1);
1250     for (unsigned i = 1; i < NumOps-1; ++i)
1251       if (N->getOperand(i).getValueType() == MVT::Other)
1252         return N->getOperand(i);
1253   }
1254   return SDValue();
1255 }
1256
1257 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1258   // If N has two operands, where one has an input chain equal to the other,
1259   // the 'other' chain is redundant.
1260   if (N->getNumOperands() == 2) {
1261     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1262       return N->getOperand(0);
1263     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1264       return N->getOperand(1);
1265   }
1266
1267   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1268   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1269   SmallPtrSet<SDNode*, 16> SeenOps;
1270   bool Changed = false;             // If we should replace this token factor.
1271
1272   // Start out with this token factor.
1273   TFs.push_back(N);
1274
1275   // Iterate through token factors.  The TFs grows when new token factors are
1276   // encountered.
1277   for (unsigned i = 0; i < TFs.size(); ++i) {
1278     SDNode *TF = TFs[i];
1279
1280     // Check each of the operands.
1281     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1282       SDValue Op = TF->getOperand(i);
1283
1284       switch (Op.getOpcode()) {
1285       case ISD::EntryToken:
1286         // Entry tokens don't need to be added to the list. They are
1287         // rededundant.
1288         Changed = true;
1289         break;
1290
1291       case ISD::TokenFactor:
1292         if (Op.hasOneUse() &&
1293             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1294           // Queue up for processing.
1295           TFs.push_back(Op.getNode());
1296           // Clean up in case the token factor is removed.
1297           AddToWorkList(Op.getNode());
1298           Changed = true;
1299           break;
1300         }
1301         // Fall thru
1302
1303       default:
1304         // Only add if it isn't already in the list.
1305         if (SeenOps.insert(Op.getNode()))
1306           Ops.push_back(Op);
1307         else
1308           Changed = true;
1309         break;
1310       }
1311     }
1312   }
1313
1314   SDValue Result;
1315
1316   // If we've change things around then replace token factor.
1317   if (Changed) {
1318     if (Ops.empty()) {
1319       // The entry token is the only possible outcome.
1320       Result = DAG.getEntryNode();
1321     } else {
1322       // New and improved token factor.
1323       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1324                            MVT::Other, &Ops[0], Ops.size());
1325     }
1326
1327     // Don't add users to work list.
1328     return CombineTo(N, Result, false);
1329   }
1330
1331   return Result;
1332 }
1333
1334 /// MERGE_VALUES can always be eliminated.
1335 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1336   WorkListRemover DeadNodes(*this);
1337   // Replacing results may cause a different MERGE_VALUES to suddenly
1338   // be CSE'd with N, and carry its uses with it. Iterate until no
1339   // uses remain, to ensure that the node can be safely deleted.
1340   // First add the users of this node to the work list so that they
1341   // can be tried again once they have new operands.
1342   AddUsersToWorkList(N);
1343   do {
1344     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1345       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1346   } while (!N->use_empty());
1347   removeFromWorkList(N);
1348   DAG.DeleteNode(N);
1349   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1350 }
1351
1352 static
1353 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1354                               SelectionDAG &DAG) {
1355   EVT VT = N0.getValueType();
1356   SDValue N00 = N0.getOperand(0);
1357   SDValue N01 = N0.getOperand(1);
1358   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1359
1360   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1361       isa<ConstantSDNode>(N00.getOperand(1))) {
1362     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1363     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1364                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1365                                  N00.getOperand(0), N01),
1366                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1367                                  N00.getOperand(1), N01));
1368     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1369   }
1370
1371   return SDValue();
1372 }
1373
1374 SDValue DAGCombiner::visitADD(SDNode *N) {
1375   SDValue N0 = N->getOperand(0);
1376   SDValue N1 = N->getOperand(1);
1377   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1378   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1379   EVT VT = N0.getValueType();
1380
1381   // fold vector ops
1382   if (VT.isVector()) {
1383     SDValue FoldedVOp = SimplifyVBinOp(N);
1384     if (FoldedVOp.getNode()) return FoldedVOp;
1385
1386     // fold (add x, 0) -> x, vector edition
1387     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1388       return N0;
1389     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1390       return N1;
1391   }
1392
1393   // fold (add x, undef) -> undef
1394   if (N0.getOpcode() == ISD::UNDEF)
1395     return N0;
1396   if (N1.getOpcode() == ISD::UNDEF)
1397     return N1;
1398   // fold (add c1, c2) -> c1+c2
1399   if (N0C && N1C)
1400     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1401   // canonicalize constant to RHS
1402   if (N0C && !N1C)
1403     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1404   // fold (add x, 0) -> x
1405   if (N1C && N1C->isNullValue())
1406     return N0;
1407   // fold (add Sym, c) -> Sym+c
1408   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1409     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1410         GA->getOpcode() == ISD::GlobalAddress)
1411       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1412                                   GA->getOffset() +
1413                                     (uint64_t)N1C->getSExtValue());
1414   // fold ((c1-A)+c2) -> (c1+c2)-A
1415   if (N1C && N0.getOpcode() == ISD::SUB)
1416     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1417       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1418                          DAG.getConstant(N1C->getAPIntValue()+
1419                                          N0C->getAPIntValue(), VT),
1420                          N0.getOperand(1));
1421   // reassociate add
1422   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1423   if (RADD.getNode() != 0)
1424     return RADD;
1425   // fold ((0-A) + B) -> B-A
1426   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1427       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1428     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1429   // fold (A + (0-B)) -> A-B
1430   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1431       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1432     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1433   // fold (A+(B-A)) -> B
1434   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1435     return N1.getOperand(0);
1436   // fold ((B-A)+A) -> B
1437   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1438     return N0.getOperand(0);
1439   // fold (A+(B-(A+C))) to (B-C)
1440   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1441       N0 == N1.getOperand(1).getOperand(0))
1442     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1443                        N1.getOperand(1).getOperand(1));
1444   // fold (A+(B-(C+A))) to (B-C)
1445   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1446       N0 == N1.getOperand(1).getOperand(1))
1447     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1448                        N1.getOperand(1).getOperand(0));
1449   // fold (A+((B-A)+or-C)) to (B+or-C)
1450   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1451       N1.getOperand(0).getOpcode() == ISD::SUB &&
1452       N0 == N1.getOperand(0).getOperand(1))
1453     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1454                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1455
1456   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1457   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1458     SDValue N00 = N0.getOperand(0);
1459     SDValue N01 = N0.getOperand(1);
1460     SDValue N10 = N1.getOperand(0);
1461     SDValue N11 = N1.getOperand(1);
1462
1463     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1464       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1465                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1466                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1467   }
1468
1469   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1470     return SDValue(N, 0);
1471
1472   // fold (a+b) -> (a|b) iff a and b share no bits.
1473   if (VT.isInteger() && !VT.isVector()) {
1474     APInt LHSZero, LHSOne;
1475     APInt RHSZero, RHSOne;
1476     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1477
1478     if (LHSZero.getBoolValue()) {
1479       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1480
1481       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1482       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1483       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1484         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1485     }
1486   }
1487
1488   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1489   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1490     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1491     if (Result.getNode()) return Result;
1492   }
1493   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1494     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1495     if (Result.getNode()) return Result;
1496   }
1497
1498   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1499   if (N1.getOpcode() == ISD::SHL &&
1500       N1.getOperand(0).getOpcode() == ISD::SUB)
1501     if (ConstantSDNode *C =
1502           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1503       if (C->getAPIntValue() == 0)
1504         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1505                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1506                                        N1.getOperand(0).getOperand(1),
1507                                        N1.getOperand(1)));
1508   if (N0.getOpcode() == ISD::SHL &&
1509       N0.getOperand(0).getOpcode() == ISD::SUB)
1510     if (ConstantSDNode *C =
1511           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1512       if (C->getAPIntValue() == 0)
1513         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1514                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1515                                        N0.getOperand(0).getOperand(1),
1516                                        N0.getOperand(1)));
1517
1518   if (N1.getOpcode() == ISD::AND) {
1519     SDValue AndOp0 = N1.getOperand(0);
1520     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1521     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1522     unsigned DestBits = VT.getScalarType().getSizeInBits();
1523
1524     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1525     // and similar xforms where the inner op is either ~0 or 0.
1526     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1527       DebugLoc DL = N->getDebugLoc();
1528       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1529     }
1530   }
1531
1532   // add (sext i1), X -> sub X, (zext i1)
1533   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1534       N0.getOperand(0).getValueType() == MVT::i1 &&
1535       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1536     DebugLoc DL = N->getDebugLoc();
1537     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1538     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1539   }
1540
1541   return SDValue();
1542 }
1543
1544 SDValue DAGCombiner::visitADDC(SDNode *N) {
1545   SDValue N0 = N->getOperand(0);
1546   SDValue N1 = N->getOperand(1);
1547   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1548   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1549   EVT VT = N0.getValueType();
1550
1551   // If the flag result is dead, turn this into an ADD.
1552   if (!N->hasAnyUseOfValue(1))
1553     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
1554                      DAG.getNode(ISD::CARRY_FALSE,
1555                                  N->getDebugLoc(), MVT::Glue));
1556
1557   // canonicalize constant to RHS.
1558   if (N0C && !N1C)
1559     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1560
1561   // fold (addc x, 0) -> x + no carry out
1562   if (N1C && N1C->isNullValue())
1563     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1564                                         N->getDebugLoc(), MVT::Glue));
1565
1566   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1567   APInt LHSZero, LHSOne;
1568   APInt RHSZero, RHSOne;
1569   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1570
1571   if (LHSZero.getBoolValue()) {
1572     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1573
1574     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1575     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1576     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1577       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1578                        DAG.getNode(ISD::CARRY_FALSE,
1579                                    N->getDebugLoc(), MVT::Glue));
1580   }
1581
1582   return SDValue();
1583 }
1584
1585 SDValue DAGCombiner::visitADDE(SDNode *N) {
1586   SDValue N0 = N->getOperand(0);
1587   SDValue N1 = N->getOperand(1);
1588   SDValue CarryIn = N->getOperand(2);
1589   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1591
1592   // canonicalize constant to RHS
1593   if (N0C && !N1C)
1594     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1595                        N1, N0, CarryIn);
1596
1597   // fold (adde x, y, false) -> (addc x, y)
1598   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1599     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
1600
1601   return SDValue();
1602 }
1603
1604 // Since it may not be valid to emit a fold to zero for vector initializers
1605 // check if we can before folding.
1606 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1607                              SelectionDAG &DAG, bool LegalOperations) {
1608   if (!VT.isVector()) {
1609     return DAG.getConstant(0, VT);
1610   }
1611   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1612     // Produce a vector of zeros.
1613     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1614     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1615     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1616       &Ops[0], Ops.size());
1617   }
1618   return SDValue();
1619 }
1620
1621 SDValue DAGCombiner::visitSUB(SDNode *N) {
1622   SDValue N0 = N->getOperand(0);
1623   SDValue N1 = N->getOperand(1);
1624   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1625   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1626   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1627     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1628   EVT VT = N0.getValueType();
1629
1630   // fold vector ops
1631   if (VT.isVector()) {
1632     SDValue FoldedVOp = SimplifyVBinOp(N);
1633     if (FoldedVOp.getNode()) return FoldedVOp;
1634
1635     // fold (sub x, 0) -> x, vector edition
1636     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1637       return N0;
1638   }
1639
1640   // fold (sub x, x) -> 0
1641   // FIXME: Refactor this and xor and other similar operations together.
1642   if (N0 == N1)
1643     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1644   // fold (sub c1, c2) -> c1-c2
1645   if (N0C && N1C)
1646     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1647   // fold (sub x, c) -> (add x, -c)
1648   if (N1C)
1649     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1650                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1651   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1652   if (N0C && N0C->isAllOnesValue())
1653     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1654   // fold A-(A-B) -> B
1655   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1656     return N1.getOperand(1);
1657   // fold (A+B)-A -> B
1658   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1659     return N0.getOperand(1);
1660   // fold (A+B)-B -> A
1661   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1662     return N0.getOperand(0);
1663   // fold C2-(A+C1) -> (C2-C1)-A
1664   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1665     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1666                                    VT);
1667     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
1668                        N1.getOperand(0));
1669   }
1670   // fold ((A+(B+or-C))-B) -> A+or-C
1671   if (N0.getOpcode() == ISD::ADD &&
1672       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1673        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1674       N0.getOperand(1).getOperand(0) == N1)
1675     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1676                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1677   // fold ((A+(C+B))-B) -> A+C
1678   if (N0.getOpcode() == ISD::ADD &&
1679       N0.getOperand(1).getOpcode() == ISD::ADD &&
1680       N0.getOperand(1).getOperand(1) == N1)
1681     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1682                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1683   // fold ((A-(B-C))-C) -> A-B
1684   if (N0.getOpcode() == ISD::SUB &&
1685       N0.getOperand(1).getOpcode() == ISD::SUB &&
1686       N0.getOperand(1).getOperand(1) == N1)
1687     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1688                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1689
1690   // If either operand of a sub is undef, the result is undef
1691   if (N0.getOpcode() == ISD::UNDEF)
1692     return N0;
1693   if (N1.getOpcode() == ISD::UNDEF)
1694     return N1;
1695
1696   // If the relocation model supports it, consider symbol offsets.
1697   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1698     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1699       // fold (sub Sym, c) -> Sym-c
1700       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1701         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1702                                     GA->getOffset() -
1703                                       (uint64_t)N1C->getSExtValue());
1704       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1705       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1706         if (GA->getGlobal() == GB->getGlobal())
1707           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1708                                  VT);
1709     }
1710
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719   EVT VT = N0.getValueType();
1720
1721   // If the flag result is dead, turn this into an SUB.
1722   if (!N->hasAnyUseOfValue(1))
1723     return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
1724                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1725                                  MVT::Glue));
1726
1727   // fold (subc x, x) -> 0 + no borrow
1728   if (N0 == N1)
1729     return CombineTo(N, DAG.getConstant(0, VT),
1730                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1731                                  MVT::Glue));
1732
1733   // fold (subc x, 0) -> x + no borrow
1734   if (N1C && N1C->isNullValue())
1735     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1736                                         MVT::Glue));
1737
1738   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1739   if (N0C && N0C->isAllOnesValue())
1740     return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
1741                      DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
1742                                  MVT::Glue));
1743
1744   return SDValue();
1745 }
1746
1747 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1748   SDValue N0 = N->getOperand(0);
1749   SDValue N1 = N->getOperand(1);
1750   SDValue CarryIn = N->getOperand(2);
1751
1752   // fold (sube x, y, false) -> (subc x, y)
1753   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1754     return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
1755
1756   return SDValue();
1757 }
1758
1759 SDValue DAGCombiner::visitMUL(SDNode *N) {
1760   SDValue N0 = N->getOperand(0);
1761   SDValue N1 = N->getOperand(1);
1762   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1763   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1764   EVT VT = N0.getValueType();
1765
1766   // fold vector ops
1767   if (VT.isVector()) {
1768     SDValue FoldedVOp = SimplifyVBinOp(N);
1769     if (FoldedVOp.getNode()) return FoldedVOp;
1770   }
1771
1772   // fold (mul x, undef) -> 0
1773   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1774     return DAG.getConstant(0, VT);
1775   // fold (mul c1, c2) -> c1*c2
1776   if (N0C && N1C)
1777     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1778   // canonicalize constant to RHS
1779   if (N0C && !N1C)
1780     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1781   // fold (mul x, 0) -> 0
1782   if (N1C && N1C->isNullValue())
1783     return N1;
1784   // fold (mul x, -1) -> 0-x
1785   if (N1C && N1C->isAllOnesValue())
1786     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1787                        DAG.getConstant(0, VT), N0);
1788   // fold (mul x, (1 << c)) -> x << c
1789   if (N1C && N1C->getAPIntValue().isPowerOf2())
1790     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1791                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1792                                        getShiftAmountTy(N0.getValueType())));
1793   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1794   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1795     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1796     // FIXME: If the input is something that is easily negated (e.g. a
1797     // single-use add), we should put the negate there.
1798     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1799                        DAG.getConstant(0, VT),
1800                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1801                             DAG.getConstant(Log2Val,
1802                                       getShiftAmountTy(N0.getValueType()))));
1803   }
1804   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1805   if (N1C && N0.getOpcode() == ISD::SHL &&
1806       isa<ConstantSDNode>(N0.getOperand(1))) {
1807     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1808                              N1, N0.getOperand(1));
1809     AddToWorkList(C3.getNode());
1810     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1811                        N0.getOperand(0), C3);
1812   }
1813
1814   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1815   // use.
1816   {
1817     SDValue Sh(0,0), Y(0,0);
1818     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1819     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1820         N0.getNode()->hasOneUse()) {
1821       Sh = N0; Y = N1;
1822     } else if (N1.getOpcode() == ISD::SHL &&
1823                isa<ConstantSDNode>(N1.getOperand(1)) &&
1824                N1.getNode()->hasOneUse()) {
1825       Sh = N1; Y = N0;
1826     }
1827
1828     if (Sh.getNode()) {
1829       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1830                                 Sh.getOperand(0), Y);
1831       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1832                          Mul, Sh.getOperand(1));
1833     }
1834   }
1835
1836   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1837   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1838       isa<ConstantSDNode>(N0.getOperand(1)))
1839     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1840                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1841                                    N0.getOperand(0), N1),
1842                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1843                                    N0.getOperand(1), N1));
1844
1845   // reassociate mul
1846   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1847   if (RMUL.getNode() != 0)
1848     return RMUL;
1849
1850   return SDValue();
1851 }
1852
1853 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1854   SDValue N0 = N->getOperand(0);
1855   SDValue N1 = N->getOperand(1);
1856   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1857   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1858   EVT VT = N->getValueType(0);
1859
1860   // fold vector ops
1861   if (VT.isVector()) {
1862     SDValue FoldedVOp = SimplifyVBinOp(N);
1863     if (FoldedVOp.getNode()) return FoldedVOp;
1864   }
1865
1866   // fold (sdiv c1, c2) -> c1/c2
1867   if (N0C && N1C && !N1C->isNullValue())
1868     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1869   // fold (sdiv X, 1) -> X
1870   if (N1C && N1C->getAPIntValue() == 1LL)
1871     return N0;
1872   // fold (sdiv X, -1) -> 0-X
1873   if (N1C && N1C->isAllOnesValue())
1874     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1875                        DAG.getConstant(0, VT), N0);
1876   // If we know the sign bits of both operands are zero, strength reduce to a
1877   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1878   if (!VT.isVector()) {
1879     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1880       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1881                          N0, N1);
1882   }
1883   // fold (sdiv X, pow2) -> simple ops after legalize
1884   if (N1C && !N1C->isNullValue() &&
1885       (N1C->getAPIntValue().isPowerOf2() ||
1886        (-N1C->getAPIntValue()).isPowerOf2())) {
1887     // If dividing by powers of two is cheap, then don't perform the following
1888     // fold.
1889     if (TLI.isPow2DivCheap())
1890       return SDValue();
1891
1892     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1893
1894     // Splat the sign bit into the register
1895     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1896                               DAG.getConstant(VT.getSizeInBits()-1,
1897                                        getShiftAmountTy(N0.getValueType())));
1898     AddToWorkList(SGN.getNode());
1899
1900     // Add (N0 < 0) ? abs2 - 1 : 0;
1901     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1902                               DAG.getConstant(VT.getSizeInBits() - lg2,
1903                                        getShiftAmountTy(SGN.getValueType())));
1904     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1905     AddToWorkList(SRL.getNode());
1906     AddToWorkList(ADD.getNode());    // Divide by pow2
1907     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1908                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1909
1910     // If we're dividing by a positive value, we're done.  Otherwise, we must
1911     // negate the result.
1912     if (N1C->getAPIntValue().isNonNegative())
1913       return SRA;
1914
1915     AddToWorkList(SRA.getNode());
1916     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1917                        DAG.getConstant(0, VT), SRA);
1918   }
1919
1920   // if integer divide is expensive and we satisfy the requirements, emit an
1921   // alternate sequence.
1922   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1923     SDValue Op = BuildSDIV(N);
1924     if (Op.getNode()) return Op;
1925   }
1926
1927   // undef / X -> 0
1928   if (N0.getOpcode() == ISD::UNDEF)
1929     return DAG.getConstant(0, VT);
1930   // X / undef -> undef
1931   if (N1.getOpcode() == ISD::UNDEF)
1932     return N1;
1933
1934   return SDValue();
1935 }
1936
1937 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1941   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1942   EVT VT = N->getValueType(0);
1943
1944   // fold vector ops
1945   if (VT.isVector()) {
1946     SDValue FoldedVOp = SimplifyVBinOp(N);
1947     if (FoldedVOp.getNode()) return FoldedVOp;
1948   }
1949
1950   // fold (udiv c1, c2) -> c1/c2
1951   if (N0C && N1C && !N1C->isNullValue())
1952     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1953   // fold (udiv x, (1 << c)) -> x >>u c
1954   if (N1C && N1C->getAPIntValue().isPowerOf2())
1955     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1956                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
1957                                        getShiftAmountTy(N0.getValueType())));
1958   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1959   if (N1.getOpcode() == ISD::SHL) {
1960     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1961       if (SHC->getAPIntValue().isPowerOf2()) {
1962         EVT ADDVT = N1.getOperand(1).getValueType();
1963         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1964                                   N1.getOperand(1),
1965                                   DAG.getConstant(SHC->getAPIntValue()
1966                                                                   .logBase2(),
1967                                                   ADDVT));
1968         AddToWorkList(Add.getNode());
1969         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1970       }
1971     }
1972   }
1973   // fold (udiv x, c) -> alternate
1974   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1975     SDValue Op = BuildUDIV(N);
1976     if (Op.getNode()) return Op;
1977   }
1978
1979   // undef / X -> 0
1980   if (N0.getOpcode() == ISD::UNDEF)
1981     return DAG.getConstant(0, VT);
1982   // X / undef -> undef
1983   if (N1.getOpcode() == ISD::UNDEF)
1984     return N1;
1985
1986   return SDValue();
1987 }
1988
1989 SDValue DAGCombiner::visitSREM(SDNode *N) {
1990   SDValue N0 = N->getOperand(0);
1991   SDValue N1 = N->getOperand(1);
1992   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1993   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1994   EVT VT = N->getValueType(0);
1995
1996   // fold (srem c1, c2) -> c1%c2
1997   if (N0C && N1C && !N1C->isNullValue())
1998     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1999   // If we know the sign bits of both operands are zero, strength reduce to a
2000   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2001   if (!VT.isVector()) {
2002     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2003       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
2004   }
2005
2006   // If X/C can be simplified by the division-by-constant logic, lower
2007   // X%C to the equivalent of X-X/C*C.
2008   if (N1C && !N1C->isNullValue()) {
2009     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
2010     AddToWorkList(Div.getNode());
2011     SDValue OptimizedDiv = combine(Div.getNode());
2012     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2013       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2014                                 OptimizedDiv, N1);
2015       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2016       AddToWorkList(Mul.getNode());
2017       return Sub;
2018     }
2019   }
2020
2021   // undef % X -> 0
2022   if (N0.getOpcode() == ISD::UNDEF)
2023     return DAG.getConstant(0, VT);
2024   // X % undef -> undef
2025   if (N1.getOpcode() == ISD::UNDEF)
2026     return N1;
2027
2028   return SDValue();
2029 }
2030
2031 SDValue DAGCombiner::visitUREM(SDNode *N) {
2032   SDValue N0 = N->getOperand(0);
2033   SDValue N1 = N->getOperand(1);
2034   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2035   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2036   EVT VT = N->getValueType(0);
2037
2038   // fold (urem c1, c2) -> c1%c2
2039   if (N0C && N1C && !N1C->isNullValue())
2040     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2041   // fold (urem x, pow2) -> (and x, pow2-1)
2042   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2043     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
2044                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2045   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2046   if (N1.getOpcode() == ISD::SHL) {
2047     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2048       if (SHC->getAPIntValue().isPowerOf2()) {
2049         SDValue Add =
2050           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
2051                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2052                                  VT));
2053         AddToWorkList(Add.getNode());
2054         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
2055       }
2056     }
2057   }
2058
2059   // If X/C can be simplified by the division-by-constant logic, lower
2060   // X%C to the equivalent of X-X/C*C.
2061   if (N1C && !N1C->isNullValue()) {
2062     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
2063     AddToWorkList(Div.getNode());
2064     SDValue OptimizedDiv = combine(Div.getNode());
2065     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2066       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
2067                                 OptimizedDiv, N1);
2068       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
2069       AddToWorkList(Mul.getNode());
2070       return Sub;
2071     }
2072   }
2073
2074   // undef % X -> 0
2075   if (N0.getOpcode() == ISD::UNDEF)
2076     return DAG.getConstant(0, VT);
2077   // X % undef -> undef
2078   if (N1.getOpcode() == ISD::UNDEF)
2079     return N1;
2080
2081   return SDValue();
2082 }
2083
2084 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2085   SDValue N0 = N->getOperand(0);
2086   SDValue N1 = N->getOperand(1);
2087   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2088   EVT VT = N->getValueType(0);
2089   DebugLoc DL = N->getDebugLoc();
2090
2091   // fold (mulhs x, 0) -> 0
2092   if (N1C && N1C->isNullValue())
2093     return N1;
2094   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2095   if (N1C && N1C->getAPIntValue() == 1)
2096     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
2097                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2098                                        getShiftAmountTy(N0.getValueType())));
2099   // fold (mulhs x, undef) -> 0
2100   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2101     return DAG.getConstant(0, VT);
2102
2103   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2104   // plus a shift.
2105   if (VT.isSimple() && !VT.isVector()) {
2106     MVT Simple = VT.getSimpleVT();
2107     unsigned SimpleSize = Simple.getSizeInBits();
2108     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2109     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2110       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2111       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2112       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2113       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2114             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2115       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2116     }
2117   }
2118
2119   return SDValue();
2120 }
2121
2122 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2123   SDValue N0 = N->getOperand(0);
2124   SDValue N1 = N->getOperand(1);
2125   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2126   EVT VT = N->getValueType(0);
2127   DebugLoc DL = N->getDebugLoc();
2128
2129   // fold (mulhu x, 0) -> 0
2130   if (N1C && N1C->isNullValue())
2131     return N1;
2132   // fold (mulhu x, 1) -> 0
2133   if (N1C && N1C->getAPIntValue() == 1)
2134     return DAG.getConstant(0, N0.getValueType());
2135   // fold (mulhu x, undef) -> 0
2136   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2137     return DAG.getConstant(0, VT);
2138
2139   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2140   // plus a shift.
2141   if (VT.isSimple() && !VT.isVector()) {
2142     MVT Simple = VT.getSimpleVT();
2143     unsigned SimpleSize = Simple.getSizeInBits();
2144     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2145     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2146       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2147       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2148       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2149       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2150             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2151       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2152     }
2153   }
2154
2155   return SDValue();
2156 }
2157
2158 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2159 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2160 /// that are being performed. Return true if a simplification was made.
2161 ///
2162 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2163                                                 unsigned HiOp) {
2164   // If the high half is not needed, just compute the low half.
2165   bool HiExists = N->hasAnyUseOfValue(1);
2166   if (!HiExists &&
2167       (!LegalOperations ||
2168        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2169     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2170                               N->op_begin(), N->getNumOperands());
2171     return CombineTo(N, Res, Res);
2172   }
2173
2174   // If the low half is not needed, just compute the high half.
2175   bool LoExists = N->hasAnyUseOfValue(0);
2176   if (!LoExists &&
2177       (!LegalOperations ||
2178        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2179     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2180                               N->op_begin(), N->getNumOperands());
2181     return CombineTo(N, Res, Res);
2182   }
2183
2184   // If both halves are used, return as it is.
2185   if (LoExists && HiExists)
2186     return SDValue();
2187
2188   // If the two computed results can be simplified separately, separate them.
2189   if (LoExists) {
2190     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2191                              N->op_begin(), N->getNumOperands());
2192     AddToWorkList(Lo.getNode());
2193     SDValue LoOpt = combine(Lo.getNode());
2194     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2195         (!LegalOperations ||
2196          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2197       return CombineTo(N, LoOpt, LoOpt);
2198   }
2199
2200   if (HiExists) {
2201     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2202                              N->op_begin(), N->getNumOperands());
2203     AddToWorkList(Hi.getNode());
2204     SDValue HiOpt = combine(Hi.getNode());
2205     if (HiOpt.getNode() && HiOpt != Hi &&
2206         (!LegalOperations ||
2207          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2208       return CombineTo(N, HiOpt, HiOpt);
2209   }
2210
2211   return SDValue();
2212 }
2213
2214 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2215   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2216   if (Res.getNode()) return Res;
2217
2218   EVT VT = N->getValueType(0);
2219   DebugLoc DL = N->getDebugLoc();
2220
2221   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2222   // plus a shift.
2223   if (VT.isSimple() && !VT.isVector()) {
2224     MVT Simple = VT.getSimpleVT();
2225     unsigned SimpleSize = Simple.getSizeInBits();
2226     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2227     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2228       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2229       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2230       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2231       // Compute the high part as N1.
2232       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2233             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2234       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2235       // Compute the low part as N0.
2236       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2237       return CombineTo(N, Lo, Hi);
2238     }
2239   }
2240
2241   return SDValue();
2242 }
2243
2244 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2245   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2246   if (Res.getNode()) return Res;
2247
2248   EVT VT = N->getValueType(0);
2249   DebugLoc DL = N->getDebugLoc();
2250
2251   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2252   // plus a shift.
2253   if (VT.isSimple() && !VT.isVector()) {
2254     MVT Simple = VT.getSimpleVT();
2255     unsigned SimpleSize = Simple.getSizeInBits();
2256     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2257     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2258       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2259       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2260       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2261       // Compute the high part as N1.
2262       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2263             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2264       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2265       // Compute the low part as N0.
2266       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2267       return CombineTo(N, Lo, Hi);
2268     }
2269   }
2270
2271   return SDValue();
2272 }
2273
2274 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2275   // (smulo x, 2) -> (saddo x, x)
2276   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2277     if (C2->getAPIntValue() == 2)
2278       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
2279                          N->getOperand(0), N->getOperand(0));
2280
2281   return SDValue();
2282 }
2283
2284 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2285   // (umulo x, 2) -> (uaddo x, x)
2286   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2287     if (C2->getAPIntValue() == 2)
2288       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
2289                          N->getOperand(0), N->getOperand(0));
2290
2291   return SDValue();
2292 }
2293
2294 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2295   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2296   if (Res.getNode()) return Res;
2297
2298   return SDValue();
2299 }
2300
2301 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2302   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2303   if (Res.getNode()) return Res;
2304
2305   return SDValue();
2306 }
2307
2308 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2309 /// two operands of the same opcode, try to simplify it.
2310 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2311   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2312   EVT VT = N0.getValueType();
2313   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2314
2315   // Bail early if none of these transforms apply.
2316   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2317
2318   // For each of OP in AND/OR/XOR:
2319   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2320   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2321   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2322   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2323   //
2324   // do not sink logical op inside of a vector extend, since it may combine
2325   // into a vsetcc.
2326   EVT Op0VT = N0.getOperand(0).getValueType();
2327   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2328        N0.getOpcode() == ISD::SIGN_EXTEND ||
2329        // Avoid infinite looping with PromoteIntBinOp.
2330        (N0.getOpcode() == ISD::ANY_EXTEND &&
2331         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2332        (N0.getOpcode() == ISD::TRUNCATE &&
2333         (!TLI.isZExtFree(VT, Op0VT) ||
2334          !TLI.isTruncateFree(Op0VT, VT)) &&
2335         TLI.isTypeLegal(Op0VT))) &&
2336       !VT.isVector() &&
2337       Op0VT == N1.getOperand(0).getValueType() &&
2338       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2339     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2340                                  N0.getOperand(0).getValueType(),
2341                                  N0.getOperand(0), N1.getOperand(0));
2342     AddToWorkList(ORNode.getNode());
2343     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2344   }
2345
2346   // For each of OP in SHL/SRL/SRA/AND...
2347   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2348   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2349   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2350   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2351        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2352       N0.getOperand(1) == N1.getOperand(1)) {
2353     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2354                                  N0.getOperand(0).getValueType(),
2355                                  N0.getOperand(0), N1.getOperand(0));
2356     AddToWorkList(ORNode.getNode());
2357     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2358                        ORNode, N0.getOperand(1));
2359   }
2360
2361   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2362   // Only perform this optimization after type legalization and before
2363   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2364   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2365   // we don't want to undo this promotion.
2366   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2367   // on scalars.
2368   if ((N0.getOpcode() == ISD::BITCAST ||
2369        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2370       Level == AfterLegalizeTypes) {
2371     SDValue In0 = N0.getOperand(0);
2372     SDValue In1 = N1.getOperand(0);
2373     EVT In0Ty = In0.getValueType();
2374     EVT In1Ty = In1.getValueType();
2375     DebugLoc DL = N->getDebugLoc();
2376     // If both incoming values are integers, and the original types are the
2377     // same.
2378     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2379       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2380       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2381       AddToWorkList(Op.getNode());
2382       return BC;
2383     }
2384   }
2385
2386   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2387   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2388   // If both shuffles use the same mask, and both shuffle within a single
2389   // vector, then it is worthwhile to move the swizzle after the operation.
2390   // The type-legalizer generates this pattern when loading illegal
2391   // vector types from memory. In many cases this allows additional shuffle
2392   // optimizations.
2393   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2394       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2395       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2396     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2397     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2398
2399     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2400            "Inputs to shuffles are not the same type");
2401
2402     unsigned NumElts = VT.getVectorNumElements();
2403
2404     // Check that both shuffles use the same mask. The masks are known to be of
2405     // the same length because the result vector type is the same.
2406     bool SameMask = true;
2407     for (unsigned i = 0; i != NumElts; ++i) {
2408       int Idx0 = SVN0->getMaskElt(i);
2409       int Idx1 = SVN1->getMaskElt(i);
2410       if (Idx0 != Idx1) {
2411         SameMask = false;
2412         break;
2413       }
2414     }
2415
2416     if (SameMask) {
2417       SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
2418                                N0.getOperand(0), N1.getOperand(0));
2419       AddToWorkList(Op.getNode());
2420       return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
2421                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2422     }
2423   }
2424
2425   return SDValue();
2426 }
2427
2428 SDValue DAGCombiner::visitAND(SDNode *N) {
2429   SDValue N0 = N->getOperand(0);
2430   SDValue N1 = N->getOperand(1);
2431   SDValue LL, LR, RL, RR, CC0, CC1;
2432   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2433   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2434   EVT VT = N1.getValueType();
2435   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2436
2437   // fold vector ops
2438   if (VT.isVector()) {
2439     SDValue FoldedVOp = SimplifyVBinOp(N);
2440     if (FoldedVOp.getNode()) return FoldedVOp;
2441
2442     // fold (and x, 0) -> 0, vector edition
2443     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2444       return N0;
2445     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2446       return N1;
2447
2448     // fold (and x, -1) -> x, vector edition
2449     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2450       return N1;
2451     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2452       return N0;
2453   }
2454
2455   // fold (and x, undef) -> 0
2456   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2457     return DAG.getConstant(0, VT);
2458   // fold (and c1, c2) -> c1&c2
2459   if (N0C && N1C)
2460     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2461   // canonicalize constant to RHS
2462   if (N0C && !N1C)
2463     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2464   // fold (and x, -1) -> x
2465   if (N1C && N1C->isAllOnesValue())
2466     return N0;
2467   // if (and x, c) is known to be zero, return 0
2468   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2469                                    APInt::getAllOnesValue(BitWidth)))
2470     return DAG.getConstant(0, VT);
2471   // reassociate and
2472   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2473   if (RAND.getNode() != 0)
2474     return RAND;
2475   // fold (and (or x, C), D) -> D if (C & D) == D
2476   if (N1C && N0.getOpcode() == ISD::OR)
2477     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2478       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2479         return N1;
2480   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2481   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2482     SDValue N0Op0 = N0.getOperand(0);
2483     APInt Mask = ~N1C->getAPIntValue();
2484     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2485     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2486       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2487                                  N0.getValueType(), N0Op0);
2488
2489       // Replace uses of the AND with uses of the Zero extend node.
2490       CombineTo(N, Zext);
2491
2492       // We actually want to replace all uses of the any_extend with the
2493       // zero_extend, to avoid duplicating things.  This will later cause this
2494       // AND to be folded.
2495       CombineTo(N0.getNode(), Zext);
2496       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2497     }
2498   }
2499   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) -> 
2500   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2501   // already be zero by virtue of the width of the base type of the load.
2502   //
2503   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2504   // more cases.
2505   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2506        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2507       N0.getOpcode() == ISD::LOAD) {
2508     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2509                                          N0 : N0.getOperand(0) );
2510
2511     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2512     // This can be a pure constant or a vector splat, in which case we treat the
2513     // vector as a scalar and use the splat value.
2514     APInt Constant = APInt::getNullValue(1);
2515     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2516       Constant = C->getAPIntValue();
2517     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2518       APInt SplatValue, SplatUndef;
2519       unsigned SplatBitSize;
2520       bool HasAnyUndefs;
2521       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2522                                              SplatBitSize, HasAnyUndefs);
2523       if (IsSplat) {
2524         // Undef bits can contribute to a possible optimisation if set, so
2525         // set them.
2526         SplatValue |= SplatUndef;
2527
2528         // The splat value may be something like "0x00FFFFFF", which means 0 for
2529         // the first vector value and FF for the rest, repeating. We need a mask
2530         // that will apply equally to all members of the vector, so AND all the
2531         // lanes of the constant together.
2532         EVT VT = Vector->getValueType(0);
2533         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2534
2535         // If the splat value has been compressed to a bitlength lower
2536         // than the size of the vector lane, we need to re-expand it to
2537         // the lane size.
2538         if (BitWidth > SplatBitSize)
2539           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2540                SplatBitSize < BitWidth;
2541                SplatBitSize = SplatBitSize * 2)
2542             SplatValue |= SplatValue.shl(SplatBitSize);
2543
2544         Constant = APInt::getAllOnesValue(BitWidth);
2545         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2546           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2547       }
2548     }
2549
2550     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2551     // actually legal and isn't going to get expanded, else this is a false
2552     // optimisation.
2553     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2554                                                     Load->getMemoryVT());
2555
2556     // Resize the constant to the same size as the original memory access before
2557     // extension. If it is still the AllOnesValue then this AND is completely
2558     // unneeded.
2559     Constant =
2560       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2561
2562     bool B;
2563     switch (Load->getExtensionType()) {
2564     default: B = false; break;
2565     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2566     case ISD::ZEXTLOAD:
2567     case ISD::NON_EXTLOAD: B = true; break;
2568     }
2569
2570     if (B && Constant.isAllOnesValue()) {
2571       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2572       // preserve semantics once we get rid of the AND.
2573       SDValue NewLoad(Load, 0);
2574       if (Load->getExtensionType() == ISD::EXTLOAD) {
2575         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2576                               Load->getValueType(0), Load->getDebugLoc(),
2577                               Load->getChain(), Load->getBasePtr(),
2578                               Load->getOffset(), Load->getMemoryVT(),
2579                               Load->getMemOperand());
2580         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2581         if (Load->getNumValues() == 3) {
2582           // PRE/POST_INC loads have 3 values.
2583           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2584                            NewLoad.getValue(2) };
2585           CombineTo(Load, To, 3, true);
2586         } else {
2587           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2588         }
2589       }
2590
2591       // Fold the AND away, taking care not to fold to the old load node if we
2592       // replaced it.
2593       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2594
2595       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2596     }
2597   }
2598   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2599   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2600     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2601     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2602
2603     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2604         LL.getValueType().isInteger()) {
2605       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2606       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2607         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2608                                      LR.getValueType(), LL, RL);
2609         AddToWorkList(ORNode.getNode());
2610         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2611       }
2612       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2613       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2614         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2615                                       LR.getValueType(), LL, RL);
2616         AddToWorkList(ANDNode.getNode());
2617         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2618       }
2619       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2620       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2621         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2622                                      LR.getValueType(), LL, RL);
2623         AddToWorkList(ORNode.getNode());
2624         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2625       }
2626     }
2627     // canonicalize equivalent to ll == rl
2628     if (LL == RR && LR == RL) {
2629       Op1 = ISD::getSetCCSwappedOperands(Op1);
2630       std::swap(RL, RR);
2631     }
2632     if (LL == RL && LR == RR) {
2633       bool isInteger = LL.getValueType().isInteger();
2634       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2635       if (Result != ISD::SETCC_INVALID &&
2636           (!LegalOperations ||
2637            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2638             TLI.isOperationLegal(ISD::SETCC,
2639                             TLI.getSetCCResultType(N0.getSimpleValueType())))))
2640         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2641                             LL, LR, Result);
2642     }
2643   }
2644
2645   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2646   if (N0.getOpcode() == N1.getOpcode()) {
2647     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2648     if (Tmp.getNode()) return Tmp;
2649   }
2650
2651   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2652   // fold (and (sra)) -> (and (srl)) when possible.
2653   if (!VT.isVector() &&
2654       SimplifyDemandedBits(SDValue(N, 0)))
2655     return SDValue(N, 0);
2656
2657   // fold (zext_inreg (extload x)) -> (zextload x)
2658   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2659     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2660     EVT MemVT = LN0->getMemoryVT();
2661     // If we zero all the possible extended bits, then we can turn this into
2662     // a zextload if we are running before legalize or the operation is legal.
2663     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2664     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2665                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2666         ((!LegalOperations && !LN0->isVolatile()) ||
2667          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2668       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2669                                        LN0->getChain(), LN0->getBasePtr(),
2670                                        LN0->getPointerInfo(), MemVT,
2671                                        LN0->isVolatile(), LN0->isNonTemporal(),
2672                                        LN0->getAlignment());
2673       AddToWorkList(N);
2674       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2675       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2676     }
2677   }
2678   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2679   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2680       N0.hasOneUse()) {
2681     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2682     EVT MemVT = LN0->getMemoryVT();
2683     // If we zero all the possible extended bits, then we can turn this into
2684     // a zextload if we are running before legalize or the operation is legal.
2685     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2686     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2687                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2688         ((!LegalOperations && !LN0->isVolatile()) ||
2689          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2690       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2691                                        LN0->getChain(),
2692                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2693                                        MemVT,
2694                                        LN0->isVolatile(), LN0->isNonTemporal(),
2695                                        LN0->getAlignment());
2696       AddToWorkList(N);
2697       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2698       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2699     }
2700   }
2701
2702   // fold (and (load x), 255) -> (zextload x, i8)
2703   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2704   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2705   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2706               (N0.getOpcode() == ISD::ANY_EXTEND &&
2707                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2708     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2709     LoadSDNode *LN0 = HasAnyExt
2710       ? cast<LoadSDNode>(N0.getOperand(0))
2711       : cast<LoadSDNode>(N0);
2712     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2713         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2714       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2715       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2716         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2717         EVT LoadedVT = LN0->getMemoryVT();
2718
2719         if (ExtVT == LoadedVT &&
2720             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2721           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2722
2723           SDValue NewLoad =
2724             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2725                            LN0->getChain(), LN0->getBasePtr(),
2726                            LN0->getPointerInfo(),
2727                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2728                            LN0->getAlignment());
2729           AddToWorkList(N);
2730           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2731           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2732         }
2733
2734         // Do not change the width of a volatile load.
2735         // Do not generate loads of non-round integer types since these can
2736         // be expensive (and would be wrong if the type is not byte sized).
2737         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2738             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2739           EVT PtrType = LN0->getOperand(1).getValueType();
2740
2741           unsigned Alignment = LN0->getAlignment();
2742           SDValue NewPtr = LN0->getBasePtr();
2743
2744           // For big endian targets, we need to add an offset to the pointer
2745           // to load the correct bytes.  For little endian systems, we merely
2746           // need to read fewer bytes from the same pointer.
2747           if (TLI.isBigEndian()) {
2748             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2749             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2750             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2751             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2752                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2753             Alignment = MinAlign(Alignment, PtrOff);
2754           }
2755
2756           AddToWorkList(NewPtr.getNode());
2757
2758           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2759           SDValue Load =
2760             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2761                            LN0->getChain(), NewPtr,
2762                            LN0->getPointerInfo(),
2763                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2764                            Alignment);
2765           AddToWorkList(N);
2766           CombineTo(LN0, Load, Load.getValue(1));
2767           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2768         }
2769       }
2770     }
2771   }
2772
2773   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2774       VT.getSizeInBits() <= 64) {
2775     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2776       APInt ADDC = ADDI->getAPIntValue();
2777       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2778         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2779         // immediate for an add, but it is legal if its top c2 bits are set,
2780         // transform the ADD so the immediate doesn't need to be materialized
2781         // in a register.
2782         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2783           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2784                                              SRLI->getZExtValue());
2785           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2786             ADDC |= Mask;
2787             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2788               SDValue NewAdd =
2789                 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
2790                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2791               CombineTo(N0.getNode(), NewAdd);
2792               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2793             }
2794           }
2795         }
2796       }
2797     }
2798   }
2799
2800   return SDValue();
2801 }
2802
2803 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2804 ///
2805 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2806                                         bool DemandHighBits) {
2807   if (!LegalOperations)
2808     return SDValue();
2809
2810   EVT VT = N->getValueType(0);
2811   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2812     return SDValue();
2813   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2814     return SDValue();
2815
2816   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2817   bool LookPassAnd0 = false;
2818   bool LookPassAnd1 = false;
2819   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2820       std::swap(N0, N1);
2821   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2822       std::swap(N0, N1);
2823   if (N0.getOpcode() == ISD::AND) {
2824     if (!N0.getNode()->hasOneUse())
2825       return SDValue();
2826     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2827     if (!N01C || N01C->getZExtValue() != 0xFF00)
2828       return SDValue();
2829     N0 = N0.getOperand(0);
2830     LookPassAnd0 = true;
2831   }
2832
2833   if (N1.getOpcode() == ISD::AND) {
2834     if (!N1.getNode()->hasOneUse())
2835       return SDValue();
2836     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2837     if (!N11C || N11C->getZExtValue() != 0xFF)
2838       return SDValue();
2839     N1 = N1.getOperand(0);
2840     LookPassAnd1 = true;
2841   }
2842
2843   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2844     std::swap(N0, N1);
2845   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2846     return SDValue();
2847   if (!N0.getNode()->hasOneUse() ||
2848       !N1.getNode()->hasOneUse())
2849     return SDValue();
2850
2851   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2852   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2853   if (!N01C || !N11C)
2854     return SDValue();
2855   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2856     return SDValue();
2857
2858   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2859   SDValue N00 = N0->getOperand(0);
2860   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2861     if (!N00.getNode()->hasOneUse())
2862       return SDValue();
2863     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2864     if (!N001C || N001C->getZExtValue() != 0xFF)
2865       return SDValue();
2866     N00 = N00.getOperand(0);
2867     LookPassAnd0 = true;
2868   }
2869
2870   SDValue N10 = N1->getOperand(0);
2871   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2872     if (!N10.getNode()->hasOneUse())
2873       return SDValue();
2874     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2875     if (!N101C || N101C->getZExtValue() != 0xFF00)
2876       return SDValue();
2877     N10 = N10.getOperand(0);
2878     LookPassAnd1 = true;
2879   }
2880
2881   if (N00 != N10)
2882     return SDValue();
2883
2884   // Make sure everything beyond the low halfword is zero since the SRL 16
2885   // will clear the top bits.
2886   unsigned OpSizeInBits = VT.getSizeInBits();
2887   if (DemandHighBits && OpSizeInBits > 16 &&
2888       (!LookPassAnd0 || !LookPassAnd1) &&
2889       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
2890     return SDValue();
2891
2892   SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
2893   if (OpSizeInBits > 16)
2894     Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
2895                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2896   return Res;
2897 }
2898
2899 /// isBSwapHWordElement - Return true if the specified node is an element
2900 /// that makes up a 32-bit packed halfword byteswap. i.e.
2901 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2902 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
2903   if (!N.getNode()->hasOneUse())
2904     return false;
2905
2906   unsigned Opc = N.getOpcode();
2907   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2908     return false;
2909
2910   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2911   if (!N1C)
2912     return false;
2913
2914   unsigned Num;
2915   switch (N1C->getZExtValue()) {
2916   default:
2917     return false;
2918   case 0xFF:       Num = 0; break;
2919   case 0xFF00:     Num = 1; break;
2920   case 0xFF0000:   Num = 2; break;
2921   case 0xFF000000: Num = 3; break;
2922   }
2923
2924   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
2925   SDValue N0 = N.getOperand(0);
2926   if (Opc == ISD::AND) {
2927     if (Num == 0 || Num == 2) {
2928       // (x >> 8) & 0xff
2929       // (x >> 8) & 0xff0000
2930       if (N0.getOpcode() != ISD::SRL)
2931         return false;
2932       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2933       if (!C || C->getZExtValue() != 8)
2934         return false;
2935     } else {
2936       // (x << 8) & 0xff00
2937       // (x << 8) & 0xff000000
2938       if (N0.getOpcode() != ISD::SHL)
2939         return false;
2940       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2941       if (!C || C->getZExtValue() != 8)
2942         return false;
2943     }
2944   } else if (Opc == ISD::SHL) {
2945     // (x & 0xff) << 8
2946     // (x & 0xff0000) << 8
2947     if (Num != 0 && Num != 2)
2948       return false;
2949     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2950     if (!C || C->getZExtValue() != 8)
2951       return false;
2952   } else { // Opc == ISD::SRL
2953     // (x & 0xff00) >> 8
2954     // (x & 0xff000000) >> 8
2955     if (Num != 1 && Num != 3)
2956       return false;
2957     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2958     if (!C || C->getZExtValue() != 8)
2959       return false;
2960   }
2961
2962   if (Parts[Num])
2963     return false;
2964
2965   Parts[Num] = N0.getOperand(0).getNode();
2966   return true;
2967 }
2968
2969 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
2970 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2971 /// => (rotl (bswap x), 16)
2972 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
2973   if (!LegalOperations)
2974     return SDValue();
2975
2976   EVT VT = N->getValueType(0);
2977   if (VT != MVT::i32)
2978     return SDValue();
2979   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2980     return SDValue();
2981
2982   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
2983   // Look for either
2984   // (or (or (and), (and)), (or (and), (and)))
2985   // (or (or (or (and), (and)), (and)), (and))
2986   if (N0.getOpcode() != ISD::OR)
2987     return SDValue();
2988   SDValue N00 = N0.getOperand(0);
2989   SDValue N01 = N0.getOperand(1);
2990
2991   if (N1.getOpcode() == ISD::OR &&
2992       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
2993     // (or (or (and), (and)), (or (and), (and)))
2994     SDValue N000 = N00.getOperand(0);
2995     if (!isBSwapHWordElement(N000, Parts))
2996       return SDValue();
2997
2998     SDValue N001 = N00.getOperand(1);
2999     if (!isBSwapHWordElement(N001, Parts))
3000       return SDValue();
3001     SDValue N010 = N01.getOperand(0);
3002     if (!isBSwapHWordElement(N010, Parts))
3003       return SDValue();
3004     SDValue N011 = N01.getOperand(1);
3005     if (!isBSwapHWordElement(N011, Parts))
3006       return SDValue();
3007   } else {
3008     // (or (or (or (and), (and)), (and)), (and))
3009     if (!isBSwapHWordElement(N1, Parts))
3010       return SDValue();
3011     if (!isBSwapHWordElement(N01, Parts))
3012       return SDValue();
3013     if (N00.getOpcode() != ISD::OR)
3014       return SDValue();
3015     SDValue N000 = N00.getOperand(0);
3016     if (!isBSwapHWordElement(N000, Parts))
3017       return SDValue();
3018     SDValue N001 = N00.getOperand(1);
3019     if (!isBSwapHWordElement(N001, Parts))
3020       return SDValue();
3021   }
3022
3023   // Make sure the parts are all coming from the same node.
3024   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3025     return SDValue();
3026
3027   SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
3028                               SDValue(Parts[0],0));
3029
3030   // Result of the bswap should be rotated by 16. If it's not legal, than
3031   // do  (x << 16) | (x >> 16).
3032   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3033   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3034     return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
3035   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3036     return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
3037   return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
3038                      DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
3039                      DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
3040 }
3041
3042 SDValue DAGCombiner::visitOR(SDNode *N) {
3043   SDValue N0 = N->getOperand(0);
3044   SDValue N1 = N->getOperand(1);
3045   SDValue LL, LR, RL, RR, CC0, CC1;
3046   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3047   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3048   EVT VT = N1.getValueType();
3049
3050   // fold vector ops
3051   if (VT.isVector()) {
3052     SDValue FoldedVOp = SimplifyVBinOp(N);
3053     if (FoldedVOp.getNode()) return FoldedVOp;
3054
3055     // fold (or x, 0) -> x, vector edition
3056     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3057       return N1;
3058     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3059       return N0;
3060
3061     // fold (or x, -1) -> -1, vector edition
3062     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3063       return N0;
3064     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3065       return N1;
3066   }
3067
3068   // fold (or x, undef) -> -1
3069   if (!LegalOperations &&
3070       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3071     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3072     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3073   }
3074   // fold (or c1, c2) -> c1|c2
3075   if (N0C && N1C)
3076     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3077   // canonicalize constant to RHS
3078   if (N0C && !N1C)
3079     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
3080   // fold (or x, 0) -> x
3081   if (N1C && N1C->isNullValue())
3082     return N0;
3083   // fold (or x, -1) -> -1
3084   if (N1C && N1C->isAllOnesValue())
3085     return N1;
3086   // fold (or x, c) -> c iff (x & ~c) == 0
3087   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3088     return N1;
3089
3090   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3091   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3092   if (BSwap.getNode() != 0)
3093     return BSwap;
3094   BSwap = MatchBSwapHWordLow(N, N0, N1);
3095   if (BSwap.getNode() != 0)
3096     return BSwap;
3097
3098   // reassociate or
3099   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
3100   if (ROR.getNode() != 0)
3101     return ROR;
3102   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3103   // iff (c1 & c2) == 0.
3104   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3105              isa<ConstantSDNode>(N0.getOperand(1))) {
3106     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3107     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3108       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3109                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3110                                      N0.getOperand(0), N1),
3111                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3112   }
3113   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3114   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3115     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3116     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3117
3118     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3119         LL.getValueType().isInteger()) {
3120       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3121       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3122       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3123           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3124         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
3125                                      LR.getValueType(), LL, RL);
3126         AddToWorkList(ORNode.getNode());
3127         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
3128       }
3129       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3130       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3131       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3132           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3133         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
3134                                       LR.getValueType(), LL, RL);
3135         AddToWorkList(ANDNode.getNode());
3136         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
3137       }
3138     }
3139     // canonicalize equivalent to ll == rl
3140     if (LL == RR && LR == RL) {
3141       Op1 = ISD::getSetCCSwappedOperands(Op1);
3142       std::swap(RL, RR);
3143     }
3144     if (LL == RL && LR == RR) {
3145       bool isInteger = LL.getValueType().isInteger();
3146       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3147       if (Result != ISD::SETCC_INVALID &&
3148           (!LegalOperations ||
3149            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3150             TLI.isOperationLegal(ISD::SETCC,
3151               TLI.getSetCCResultType(N0.getValueType())))))
3152         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
3153                             LL, LR, Result);
3154     }
3155   }
3156
3157   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3158   if (N0.getOpcode() == N1.getOpcode()) {
3159     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3160     if (Tmp.getNode()) return Tmp;
3161   }
3162
3163   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3164   if (N0.getOpcode() == ISD::AND &&
3165       N1.getOpcode() == ISD::AND &&
3166       N0.getOperand(1).getOpcode() == ISD::Constant &&
3167       N1.getOperand(1).getOpcode() == ISD::Constant &&
3168       // Don't increase # computations.
3169       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3170     // We can only do this xform if we know that bits from X that are set in C2
3171     // but not in C1 are already zero.  Likewise for Y.
3172     const APInt &LHSMask =
3173       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3174     const APInt &RHSMask =
3175       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3176
3177     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3178         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3179       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
3180                               N0.getOperand(0), N1.getOperand(0));
3181       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
3182                          DAG.getConstant(LHSMask | RHSMask, VT));
3183     }
3184   }
3185
3186   // See if this is some rotate idiom.
3187   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
3188     return SDValue(Rot, 0);
3189
3190   // Simplify the operands using demanded-bits information.
3191   if (!VT.isVector() &&
3192       SimplifyDemandedBits(SDValue(N, 0)))
3193     return SDValue(N, 0);
3194
3195   return SDValue();
3196 }
3197
3198 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3199 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3200   if (Op.getOpcode() == ISD::AND) {
3201     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3202       Mask = Op.getOperand(1);
3203       Op = Op.getOperand(0);
3204     } else {
3205       return false;
3206     }
3207   }
3208
3209   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3210     Shift = Op;
3211     return true;
3212   }
3213
3214   return false;
3215 }
3216
3217 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3218 // idioms for rotate, and if the target supports rotation instructions, generate
3219 // a rot[lr].
3220 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
3221   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3222   EVT VT = LHS.getValueType();
3223   if (!TLI.isTypeLegal(VT)) return 0;
3224
3225   // The target must have at least one rotate flavor.
3226   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3227   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3228   if (!HasROTL && !HasROTR) return 0;
3229
3230   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3231   SDValue LHSShift;   // The shift.
3232   SDValue LHSMask;    // AND value if any.
3233   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3234     return 0; // Not part of a rotate.
3235
3236   SDValue RHSShift;   // The shift.
3237   SDValue RHSMask;    // AND value if any.
3238   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3239     return 0; // Not part of a rotate.
3240
3241   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3242     return 0;   // Not shifting the same value.
3243
3244   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3245     return 0;   // Shifts must disagree.
3246
3247   // Canonicalize shl to left side in a shl/srl pair.
3248   if (RHSShift.getOpcode() == ISD::SHL) {
3249     std::swap(LHS, RHS);
3250     std::swap(LHSShift, RHSShift);
3251     std::swap(LHSMask , RHSMask );
3252   }
3253
3254   unsigned OpSizeInBits = VT.getSizeInBits();
3255   SDValue LHSShiftArg = LHSShift.getOperand(0);
3256   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3257   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3258
3259   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3260   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3261   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3262       RHSShiftAmt.getOpcode() == ISD::Constant) {
3263     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3264     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3265     if ((LShVal + RShVal) != OpSizeInBits)
3266       return 0;
3267
3268     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3269                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3270
3271     // If there is an AND of either shifted operand, apply it to the result.
3272     if (LHSMask.getNode() || RHSMask.getNode()) {
3273       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3274
3275       if (LHSMask.getNode()) {
3276         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3277         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3278       }
3279       if (RHSMask.getNode()) {
3280         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3281         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3282       }
3283
3284       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3285     }
3286
3287     return Rot.getNode();
3288   }
3289
3290   // If there is a mask here, and we have a variable shift, we can't be sure
3291   // that we're masking out the right stuff.
3292   if (LHSMask.getNode() || RHSMask.getNode())
3293     return 0;
3294
3295   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
3296   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
3297   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
3298       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
3299     if (ConstantSDNode *SUBC =
3300           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
3301       if (SUBC->getAPIntValue() == OpSizeInBits) {
3302         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3303                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3304       }
3305     }
3306   }
3307
3308   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
3309   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
3310   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
3311       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
3312     if (ConstantSDNode *SUBC =
3313           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
3314       if (SUBC->getAPIntValue() == OpSizeInBits) {
3315         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3316                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3317       }
3318     }
3319   }
3320
3321   // Look for sign/zext/any-extended or truncate cases:
3322   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3323        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3324        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3325        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3326       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3327        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3328        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3329        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3330     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
3331     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
3332     if (RExtOp0.getOpcode() == ISD::SUB &&
3333         RExtOp0.getOperand(1) == LExtOp0) {
3334       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3335       //   (rotl x, y)
3336       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3337       //   (rotr x, (sub 32, y))
3338       if (ConstantSDNode *SUBC =
3339             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3340         if (SUBC->getAPIntValue() == OpSizeInBits) {
3341           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3342                              LHSShiftArg,
3343                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3344         }
3345       }
3346     } else if (LExtOp0.getOpcode() == ISD::SUB &&
3347                RExtOp0 == LExtOp0.getOperand(1)) {
3348       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3349       //   (rotr x, y)
3350       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3351       //   (rotl x, (sub 32, y))
3352       if (ConstantSDNode *SUBC =
3353             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3354         if (SUBC->getAPIntValue() == OpSizeInBits) {
3355           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
3356                              LHSShiftArg,
3357                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3358         }
3359       }
3360     }
3361   }
3362
3363   return 0;
3364 }
3365
3366 SDValue DAGCombiner::visitXOR(SDNode *N) {
3367   SDValue N0 = N->getOperand(0);
3368   SDValue N1 = N->getOperand(1);
3369   SDValue LHS, RHS, CC;
3370   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3371   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3372   EVT VT = N0.getValueType();
3373
3374   // fold vector ops
3375   if (VT.isVector()) {
3376     SDValue FoldedVOp = SimplifyVBinOp(N);
3377     if (FoldedVOp.getNode()) return FoldedVOp;
3378
3379     // fold (xor x, 0) -> x, vector edition
3380     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3381       return N1;
3382     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3383       return N0;
3384   }
3385
3386   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3387   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3388     return DAG.getConstant(0, VT);
3389   // fold (xor x, undef) -> undef
3390   if (N0.getOpcode() == ISD::UNDEF)
3391     return N0;
3392   if (N1.getOpcode() == ISD::UNDEF)
3393     return N1;
3394   // fold (xor c1, c2) -> c1^c2
3395   if (N0C && N1C)
3396     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3397   // canonicalize constant to RHS
3398   if (N0C && !N1C)
3399     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
3400   // fold (xor x, 0) -> x
3401   if (N1C && N1C->isNullValue())
3402     return N0;
3403   // reassociate xor
3404   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
3405   if (RXOR.getNode() != 0)
3406     return RXOR;
3407
3408   // fold !(x cc y) -> (x !cc y)
3409   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3410     bool isInt = LHS.getValueType().isInteger();
3411     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3412                                                isInt);
3413
3414     if (!LegalOperations ||
3415         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3416       switch (N0.getOpcode()) {
3417       default:
3418         llvm_unreachable("Unhandled SetCC Equivalent!");
3419       case ISD::SETCC:
3420         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
3421       case ISD::SELECT_CC:
3422         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
3423                                N0.getOperand(3), NotCC);
3424       }
3425     }
3426   }
3427
3428   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3429   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3430       N0.getNode()->hasOneUse() &&
3431       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3432     SDValue V = N0.getOperand(0);
3433     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
3434                     DAG.getConstant(1, V.getValueType()));
3435     AddToWorkList(V.getNode());
3436     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
3437   }
3438
3439   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3440   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3441       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3442     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3443     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3444       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3445       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3446       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3447       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3448       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3449     }
3450   }
3451   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3452   if (N1C && N1C->isAllOnesValue() &&
3453       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3454     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3455     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3456       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3457       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
3458       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
3459       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3460       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
3461     }
3462   }
3463   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3464   if (N1C && N0.getOpcode() == ISD::XOR) {
3465     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3466     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3467     if (N00C)
3468       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
3469                          DAG.getConstant(N1C->getAPIntValue() ^
3470                                          N00C->getAPIntValue(), VT));
3471     if (N01C)
3472       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
3473                          DAG.getConstant(N1C->getAPIntValue() ^
3474                                          N01C->getAPIntValue(), VT));
3475   }
3476   // fold (xor x, x) -> 0
3477   if (N0 == N1)
3478     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
3479
3480   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3481   if (N0.getOpcode() == N1.getOpcode()) {
3482     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3483     if (Tmp.getNode()) return Tmp;
3484   }
3485
3486   // Simplify the expression using non-local knowledge.
3487   if (!VT.isVector() &&
3488       SimplifyDemandedBits(SDValue(N, 0)))
3489     return SDValue(N, 0);
3490
3491   return SDValue();
3492 }
3493
3494 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3495 /// the shift amount is a constant.
3496 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3497   SDNode *LHS = N->getOperand(0).getNode();
3498   if (!LHS->hasOneUse()) return SDValue();
3499
3500   // We want to pull some binops through shifts, so that we have (and (shift))
3501   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3502   // thing happens with address calculations, so it's important to canonicalize
3503   // it.
3504   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3505
3506   switch (LHS->getOpcode()) {
3507   default: return SDValue();
3508   case ISD::OR:
3509   case ISD::XOR:
3510     HighBitSet = false; // We can only transform sra if the high bit is clear.
3511     break;
3512   case ISD::AND:
3513     HighBitSet = true;  // We can only transform sra if the high bit is set.
3514     break;
3515   case ISD::ADD:
3516     if (N->getOpcode() != ISD::SHL)
3517       return SDValue(); // only shl(add) not sr[al](add).
3518     HighBitSet = false; // We can only transform sra if the high bit is clear.
3519     break;
3520   }
3521
3522   // We require the RHS of the binop to be a constant as well.
3523   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3524   if (!BinOpCst) return SDValue();
3525
3526   // FIXME: disable this unless the input to the binop is a shift by a constant.
3527   // If it is not a shift, it pessimizes some common cases like:
3528   //
3529   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3530   //    int bar(int *X, int i) { return X[i & 255]; }
3531   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3532   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3533        BinOpLHSVal->getOpcode() != ISD::SRA &&
3534        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3535       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3536     return SDValue();
3537
3538   EVT VT = N->getValueType(0);
3539
3540   // If this is a signed shift right, and the high bit is modified by the
3541   // logical operation, do not perform the transformation. The highBitSet
3542   // boolean indicates the value of the high bit of the constant which would
3543   // cause it to be modified for this operation.
3544   if (N->getOpcode() == ISD::SRA) {
3545     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3546     if (BinOpRHSSignSet != HighBitSet)
3547       return SDValue();
3548   }
3549
3550   // Fold the constants, shifting the binop RHS by the shift amount.
3551   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
3552                                N->getValueType(0),
3553                                LHS->getOperand(1), N->getOperand(1));
3554
3555   // Create the new shift.
3556   SDValue NewShift = DAG.getNode(N->getOpcode(),
3557                                  LHS->getOperand(0).getDebugLoc(),
3558                                  VT, LHS->getOperand(0), N->getOperand(1));
3559
3560   // Create the new binop.
3561   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
3562 }
3563
3564 SDValue DAGCombiner::visitSHL(SDNode *N) {
3565   SDValue N0 = N->getOperand(0);
3566   SDValue N1 = N->getOperand(1);
3567   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3568   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3569   EVT VT = N0.getValueType();
3570   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3571
3572   // fold (shl c1, c2) -> c1<<c2
3573   if (N0C && N1C)
3574     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3575   // fold (shl 0, x) -> 0
3576   if (N0C && N0C->isNullValue())
3577     return N0;
3578   // fold (shl x, c >= size(x)) -> undef
3579   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3580     return DAG.getUNDEF(VT);
3581   // fold (shl x, 0) -> x
3582   if (N1C && N1C->isNullValue())
3583     return N0;
3584   // fold (shl undef, x) -> 0
3585   if (N0.getOpcode() == ISD::UNDEF)
3586     return DAG.getConstant(0, VT);
3587   // if (shl x, c) is known to be zero, return 0
3588   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3589                             APInt::getAllOnesValue(OpSizeInBits)))
3590     return DAG.getConstant(0, VT);
3591   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3592   if (N1.getOpcode() == ISD::TRUNCATE &&
3593       N1.getOperand(0).getOpcode() == ISD::AND &&
3594       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3595     SDValue N101 = N1.getOperand(0).getOperand(1);
3596     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3597       EVT TruncVT = N1.getValueType();
3598       SDValue N100 = N1.getOperand(0).getOperand(0);
3599       APInt TruncC = N101C->getAPIntValue();
3600       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3601       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3602                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3603                                      DAG.getNode(ISD::TRUNCATE,
3604                                                  N->getDebugLoc(),
3605                                                  TruncVT, N100),
3606                                      DAG.getConstant(TruncC, TruncVT)));
3607     }
3608   }
3609
3610   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3611     return SDValue(N, 0);
3612
3613   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3614   if (N1C && N0.getOpcode() == ISD::SHL &&
3615       N0.getOperand(1).getOpcode() == ISD::Constant) {
3616     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3617     uint64_t c2 = N1C->getZExtValue();
3618     if (c1 + c2 >= OpSizeInBits)
3619       return DAG.getConstant(0, VT);
3620     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3621                        DAG.getConstant(c1 + c2, N1.getValueType()));
3622   }
3623
3624   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3625   // For this to be valid, the second form must not preserve any of the bits
3626   // that are shifted out by the inner shift in the first form.  This means
3627   // the outer shift size must be >= the number of bits added by the ext.
3628   // As a corollary, we don't care what kind of ext it is.
3629   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3630               N0.getOpcode() == ISD::ANY_EXTEND ||
3631               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3632       N0.getOperand(0).getOpcode() == ISD::SHL &&
3633       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3634     uint64_t c1 =
3635       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3636     uint64_t c2 = N1C->getZExtValue();
3637     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3638     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3639     if (c2 >= OpSizeInBits - InnerShiftSize) {
3640       if (c1 + c2 >= OpSizeInBits)
3641         return DAG.getConstant(0, VT);
3642       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3643                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3644                                      N0.getOperand(0)->getOperand(0)),
3645                          DAG.getConstant(c1 + c2, N1.getValueType()));
3646     }
3647   }
3648
3649   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3650   //                               (and (srl x, (sub c1, c2), MASK)
3651   // Only fold this if the inner shift has no other uses -- if it does, folding
3652   // this will increase the total number of instructions.
3653   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3654       N0.getOperand(1).getOpcode() == ISD::Constant) {
3655     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3656     if (c1 < VT.getSizeInBits()) {
3657       uint64_t c2 = N1C->getZExtValue();
3658       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3659                                          VT.getSizeInBits() - c1);
3660       SDValue Shift;
3661       if (c2 > c1) {
3662         Mask = Mask.shl(c2-c1);
3663         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3664                             DAG.getConstant(c2-c1, N1.getValueType()));
3665       } else {
3666         Mask = Mask.lshr(c1-c2);
3667         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3668                             DAG.getConstant(c1-c2, N1.getValueType()));
3669       }
3670       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
3671                          DAG.getConstant(Mask, VT));
3672     }
3673   }
3674   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3675   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3676     SDValue HiBitsMask =
3677       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3678                                             VT.getSizeInBits() -
3679                                               N1C->getZExtValue()),
3680                       VT);
3681     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3682                        HiBitsMask);
3683   }
3684
3685   if (N1C) {
3686     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3687     if (NewSHL.getNode())
3688       return NewSHL;
3689   }
3690
3691   return SDValue();
3692 }
3693
3694 SDValue DAGCombiner::visitSRA(SDNode *N) {
3695   SDValue N0 = N->getOperand(0);
3696   SDValue N1 = N->getOperand(1);
3697   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3698   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3699   EVT VT = N0.getValueType();
3700   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3701
3702   // fold (sra c1, c2) -> (sra c1, c2)
3703   if (N0C && N1C)
3704     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3705   // fold (sra 0, x) -> 0
3706   if (N0C && N0C->isNullValue())
3707     return N0;
3708   // fold (sra -1, x) -> -1
3709   if (N0C && N0C->isAllOnesValue())
3710     return N0;
3711   // fold (sra x, (setge c, size(x))) -> undef
3712   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3713     return DAG.getUNDEF(VT);
3714   // fold (sra x, 0) -> x
3715   if (N1C && N1C->isNullValue())
3716     return N0;
3717   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3718   // sext_inreg.
3719   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3720     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3721     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3722     if (VT.isVector())
3723       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3724                                ExtVT, VT.getVectorNumElements());
3725     if ((!LegalOperations ||
3726          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3727       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3728                          N0.getOperand(0), DAG.getValueType(ExtVT));
3729   }
3730
3731   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3732   if (N1C && N0.getOpcode() == ISD::SRA) {
3733     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3734       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3735       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3736       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3737                          DAG.getConstant(Sum, N1C->getValueType(0)));
3738     }
3739   }
3740
3741   // fold (sra (shl X, m), (sub result_size, n))
3742   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3743   // result_size - n != m.
3744   // If truncate is free for the target sext(shl) is likely to result in better
3745   // code.
3746   if (N0.getOpcode() == ISD::SHL) {
3747     // Get the two constanst of the shifts, CN0 = m, CN = n.
3748     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3749     if (N01C && N1C) {
3750       // Determine what the truncate's result bitsize and type would be.
3751       EVT TruncVT =
3752         EVT::getIntegerVT(*DAG.getContext(),
3753                           OpSizeInBits - N1C->getZExtValue());
3754       // Determine the residual right-shift amount.
3755       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3756
3757       // If the shift is not a no-op (in which case this should be just a sign
3758       // extend already), the truncated to type is legal, sign_extend is legal
3759       // on that type, and the truncate to that type is both legal and free,
3760       // perform the transform.
3761       if ((ShiftAmt > 0) &&
3762           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3763           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3764           TLI.isTruncateFree(VT, TruncVT)) {
3765
3766           SDValue Amt = DAG.getConstant(ShiftAmt,
3767               getShiftAmountTy(N0.getOperand(0).getValueType()));
3768           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3769                                       N0.getOperand(0), Amt);
3770           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3771                                       Shift);
3772           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3773                              N->getValueType(0), Trunc);
3774       }
3775     }
3776   }
3777
3778   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3779   if (N1.getOpcode() == ISD::TRUNCATE &&
3780       N1.getOperand(0).getOpcode() == ISD::AND &&
3781       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3782     SDValue N101 = N1.getOperand(0).getOperand(1);
3783     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3784       EVT TruncVT = N1.getValueType();
3785       SDValue N100 = N1.getOperand(0).getOperand(0);
3786       APInt TruncC = N101C->getAPIntValue();
3787       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3788       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3789                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3790                                      TruncVT,
3791                                      DAG.getNode(ISD::TRUNCATE,
3792                                                  N->getDebugLoc(),
3793                                                  TruncVT, N100),
3794                                      DAG.getConstant(TruncC, TruncVT)));
3795     }
3796   }
3797
3798   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3799   //      if c1 is equal to the number of bits the trunc removes
3800   if (N0.getOpcode() == ISD::TRUNCATE &&
3801       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3802        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3803       N0.getOperand(0).hasOneUse() &&
3804       N0.getOperand(0).getOperand(1).hasOneUse() &&
3805       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3806     EVT LargeVT = N0.getOperand(0).getValueType();
3807     ConstantSDNode *LargeShiftAmt =
3808       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3809
3810     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3811         LargeShiftAmt->getZExtValue()) {
3812       SDValue Amt =
3813         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3814               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3815       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3816                                 N0.getOperand(0).getOperand(0), Amt);
3817       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3818     }
3819   }
3820
3821   // Simplify, based on bits shifted out of the LHS.
3822   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3823     return SDValue(N, 0);
3824
3825
3826   // If the sign bit is known to be zero, switch this to a SRL.
3827   if (DAG.SignBitIsZero(N0))
3828     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3829
3830   if (N1C) {
3831     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3832     if (NewSRA.getNode())
3833       return NewSRA;
3834   }
3835
3836   return SDValue();
3837 }
3838
3839 SDValue DAGCombiner::visitSRL(SDNode *N) {
3840   SDValue N0 = N->getOperand(0);
3841   SDValue N1 = N->getOperand(1);
3842   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3844   EVT VT = N0.getValueType();
3845   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3846
3847   // fold (srl c1, c2) -> c1 >>u c2
3848   if (N0C && N1C)
3849     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3850   // fold (srl 0, x) -> 0
3851   if (N0C && N0C->isNullValue())
3852     return N0;
3853   // fold (srl x, c >= size(x)) -> undef
3854   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3855     return DAG.getUNDEF(VT);
3856   // fold (srl x, 0) -> x
3857   if (N1C && N1C->isNullValue())
3858     return N0;
3859   // if (srl x, c) is known to be zero, return 0
3860   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3861                                    APInt::getAllOnesValue(OpSizeInBits)))
3862     return DAG.getConstant(0, VT);
3863
3864   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3865   if (N1C && N0.getOpcode() == ISD::SRL &&
3866       N0.getOperand(1).getOpcode() == ISD::Constant) {
3867     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3868     uint64_t c2 = N1C->getZExtValue();
3869     if (c1 + c2 >= OpSizeInBits)
3870       return DAG.getConstant(0, VT);
3871     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3872                        DAG.getConstant(c1 + c2, N1.getValueType()));
3873   }
3874
3875   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3876   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3877       N0.getOperand(0).getOpcode() == ISD::SRL &&
3878       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3879     uint64_t c1 =
3880       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3881     uint64_t c2 = N1C->getZExtValue();
3882     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3883     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3884     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3885     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3886     if (c1 + OpSizeInBits == InnerShiftSize) {
3887       if (c1 + c2 >= InnerShiftSize)
3888         return DAG.getConstant(0, VT);
3889       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3890                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3891                                      N0.getOperand(0)->getOperand(0),
3892                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
3893     }
3894   }
3895
3896   // fold (srl (shl x, c), c) -> (and x, cst2)
3897   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3898       N0.getValueSizeInBits() <= 64) {
3899     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3900     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3901                        DAG.getConstant(~0ULL >> ShAmt, VT));
3902   }
3903
3904
3905   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3906   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3907     // Shifting in all undef bits?
3908     EVT SmallVT = N0.getOperand(0).getValueType();
3909     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3910       return DAG.getUNDEF(VT);
3911
3912     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3913       uint64_t ShiftAmt = N1C->getZExtValue();
3914       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3915                                        N0.getOperand(0),
3916                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
3917       AddToWorkList(SmallShift.getNode());
3918       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3919     }
3920   }
3921
3922   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
3923   // bit, which is unmodified by sra.
3924   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3925     if (N0.getOpcode() == ISD::SRA)
3926       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3927   }
3928
3929   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
3930   if (N1C && N0.getOpcode() == ISD::CTLZ &&
3931       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3932     APInt KnownZero, KnownOne;
3933     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
3934
3935     // If any of the input bits are KnownOne, then the input couldn't be all
3936     // zeros, thus the result of the srl will always be zero.
3937     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3938
3939     // If all of the bits input the to ctlz node are known to be zero, then
3940     // the result of the ctlz is "32" and the result of the shift is one.
3941     APInt UnknownBits = ~KnownZero;
3942     if (UnknownBits == 0) return DAG.getConstant(1, VT);
3943
3944     // Otherwise, check to see if there is exactly one bit input to the ctlz.
3945     if ((UnknownBits & (UnknownBits - 1)) == 0) {
3946       // Okay, we know that only that the single bit specified by UnknownBits
3947       // could be set on input to the CTLZ node. If this bit is set, the SRL
3948       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3949       // to an SRL/XOR pair, which is likely to simplify more.
3950       unsigned ShAmt = UnknownBits.countTrailingZeros();
3951       SDValue Op = N0.getOperand(0);
3952
3953       if (ShAmt) {
3954         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3955                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3956         AddToWorkList(Op.getNode());
3957       }
3958
3959       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3960                          Op, DAG.getConstant(1, VT));
3961     }
3962   }
3963
3964   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3965   if (N1.getOpcode() == ISD::TRUNCATE &&
3966       N1.getOperand(0).getOpcode() == ISD::AND &&
3967       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3968     SDValue N101 = N1.getOperand(0).getOperand(1);
3969     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3970       EVT TruncVT = N1.getValueType();
3971       SDValue N100 = N1.getOperand(0).getOperand(0);
3972       APInt TruncC = N101C->getAPIntValue();
3973       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3974       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3975                          DAG.getNode(ISD::AND, N->getDebugLoc(),
3976                                      TruncVT,
3977                                      DAG.getNode(ISD::TRUNCATE,
3978                                                  N->getDebugLoc(),
3979                                                  TruncVT, N100),
3980                                      DAG.getConstant(TruncC, TruncVT)));
3981     }
3982   }
3983
3984   // fold operands of srl based on knowledge that the low bits are not
3985   // demanded.
3986   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3987     return SDValue(N, 0);
3988
3989   if (N1C) {
3990     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3991     if (NewSRL.getNode())
3992       return NewSRL;
3993   }
3994
3995   // Attempt to convert a srl of a load into a narrower zero-extending load.
3996   SDValue NarrowLoad = ReduceLoadWidth(N);
3997   if (NarrowLoad.getNode())
3998     return NarrowLoad;
3999
4000   // Here is a common situation. We want to optimize:
4001   //
4002   //   %a = ...
4003   //   %b = and i32 %a, 2
4004   //   %c = srl i32 %b, 1
4005   //   brcond i32 %c ...
4006   //
4007   // into
4008   //
4009   //   %a = ...
4010   //   %b = and %a, 2
4011   //   %c = setcc eq %b, 0
4012   //   brcond %c ...
4013   //
4014   // However when after the source operand of SRL is optimized into AND, the SRL
4015   // itself may not be optimized further. Look for it and add the BRCOND into
4016   // the worklist.
4017   if (N->hasOneUse()) {
4018     SDNode *Use = *N->use_begin();
4019     if (Use->getOpcode() == ISD::BRCOND)
4020       AddToWorkList(Use);
4021     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4022       // Also look pass the truncate.
4023       Use = *Use->use_begin();
4024       if (Use->getOpcode() == ISD::BRCOND)
4025         AddToWorkList(Use);
4026     }
4027   }
4028
4029   return SDValue();
4030 }
4031
4032 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4033   SDValue N0 = N->getOperand(0);
4034   EVT VT = N->getValueType(0);
4035
4036   // fold (ctlz c1) -> c2
4037   if (isa<ConstantSDNode>(N0))
4038     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
4039   return SDValue();
4040 }
4041
4042 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4043   SDValue N0 = N->getOperand(0);
4044   EVT VT = N->getValueType(0);
4045
4046   // fold (ctlz_zero_undef c1) -> c2
4047   if (isa<ConstantSDNode>(N0))
4048     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4049   return SDValue();
4050 }
4051
4052 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4053   SDValue N0 = N->getOperand(0);
4054   EVT VT = N->getValueType(0);
4055
4056   // fold (cttz c1) -> c2
4057   if (isa<ConstantSDNode>(N0))
4058     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
4059   return SDValue();
4060 }
4061
4062 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4063   SDValue N0 = N->getOperand(0);
4064   EVT VT = N->getValueType(0);
4065
4066   // fold (cttz_zero_undef c1) -> c2
4067   if (isa<ConstantSDNode>(N0))
4068     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
4069   return SDValue();
4070 }
4071
4072 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4073   SDValue N0 = N->getOperand(0);
4074   EVT VT = N->getValueType(0);
4075
4076   // fold (ctpop c1) -> c2
4077   if (isa<ConstantSDNode>(N0))
4078     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
4079   return SDValue();
4080 }
4081
4082 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4083   SDValue N0 = N->getOperand(0);
4084   SDValue N1 = N->getOperand(1);
4085   SDValue N2 = N->getOperand(2);
4086   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4087   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4088   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4089   EVT VT = N->getValueType(0);
4090   EVT VT0 = N0.getValueType();
4091
4092   // fold (select C, X, X) -> X
4093   if (N1 == N2)
4094     return N1;
4095   // fold (select true, X, Y) -> X
4096   if (N0C && !N0C->isNullValue())
4097     return N1;
4098   // fold (select false, X, Y) -> Y
4099   if (N0C && N0C->isNullValue())
4100     return N2;
4101   // fold (select C, 1, X) -> (or C, X)
4102   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4103     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4104   // fold (select C, 0, 1) -> (xor C, 1)
4105   if (VT.isInteger() &&
4106       (VT0 == MVT::i1 ||
4107        (VT0.isInteger() &&
4108         TLI.getBooleanContents(false) ==
4109         TargetLowering::ZeroOrOneBooleanContent)) &&
4110       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4111     SDValue XORNode;
4112     if (VT == VT0)
4113       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
4114                          N0, DAG.getConstant(1, VT0));
4115     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
4116                           N0, DAG.getConstant(1, VT0));
4117     AddToWorkList(XORNode.getNode());
4118     if (VT.bitsGT(VT0))
4119       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
4120     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
4121   }
4122   // fold (select C, 0, X) -> (and (not C), X)
4123   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4124     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4125     AddToWorkList(NOTNode.getNode());
4126     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
4127   }
4128   // fold (select C, X, 1) -> (or (not C), X)
4129   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4130     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
4131     AddToWorkList(NOTNode.getNode());
4132     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
4133   }
4134   // fold (select C, X, 0) -> (and C, X)
4135   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4136     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4137   // fold (select X, X, Y) -> (or X, Y)
4138   // fold (select X, 1, Y) -> (or X, Y)
4139   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4140     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
4141   // fold (select X, Y, X) -> (and X, Y)
4142   // fold (select X, Y, 0) -> (and X, Y)
4143   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4144     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
4145
4146   // If we can fold this based on the true/false value, do so.
4147   if (SimplifySelectOps(N, N1, N2))
4148     return SDValue(N, 0);  // Don't revisit N.
4149
4150   // fold selects based on a setcc into other things, such as min/max/abs
4151   if (N0.getOpcode() == ISD::SETCC) {
4152     // FIXME:
4153     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4154     // having to say they don't support SELECT_CC on every type the DAG knows
4155     // about, since there is no way to mark an opcode illegal at all value types
4156     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4157         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4158       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
4159                          N0.getOperand(0), N0.getOperand(1),
4160                          N1, N2, N0.getOperand(2));
4161     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
4162   }
4163
4164   return SDValue();
4165 }
4166
4167 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4168   SDValue N0 = N->getOperand(0);
4169   SDValue N1 = N->getOperand(1);
4170   SDValue N2 = N->getOperand(2);
4171   DebugLoc DL = N->getDebugLoc();
4172
4173   // Canonicalize integer abs.
4174   // vselect (setg[te] X,  0),  X, -X ->
4175   // vselect (setgt    X, -1),  X, -X ->
4176   // vselect (setl[te] X,  0), -X,  X ->
4177   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4178   if (N0.getOpcode() == ISD::SETCC) {
4179     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4180     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4181     bool isAbs = false;
4182     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4183
4184     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4185          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4186         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4187       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4188     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4189              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4190       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4191
4192     if (isAbs) {
4193       EVT VT = LHS.getValueType();
4194       SDValue Shift = DAG.getNode(
4195           ISD::SRA, DL, VT, LHS,
4196           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4197       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4198       AddToWorkList(Shift.getNode());
4199       AddToWorkList(Add.getNode());
4200       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4201     }
4202   }
4203
4204   return SDValue();
4205 }
4206
4207 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4208   SDValue N0 = N->getOperand(0);
4209   SDValue N1 = N->getOperand(1);
4210   SDValue N2 = N->getOperand(2);
4211   SDValue N3 = N->getOperand(3);
4212   SDValue N4 = N->getOperand(4);
4213   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4214
4215   // fold select_cc lhs, rhs, x, x, cc -> x
4216   if (N2 == N3)
4217     return N2;
4218
4219   // Determine if the condition we're dealing with is constant
4220   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
4221                               N0, N1, CC, N->getDebugLoc(), false);
4222   if (SCC.getNode()) AddToWorkList(SCC.getNode());
4223
4224   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
4225     if (!SCCC->isNullValue())
4226       return N2;    // cond always true -> true val
4227     else
4228       return N3;    // cond always false -> false val
4229   }
4230
4231   // Fold to a simpler select_cc
4232   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
4233     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
4234                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4235                        SCC.getOperand(2));
4236
4237   // If we can fold this based on the true/false value, do so.
4238   if (SimplifySelectOps(N, N2, N3))
4239     return SDValue(N, 0);  // Don't revisit N.
4240
4241   // fold select_cc into other things, such as min/max/abs
4242   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
4243 }
4244
4245 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4246   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4247                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4248                        N->getDebugLoc());
4249 }
4250
4251 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4252 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4253 // transformation. Returns true if extension are possible and the above
4254 // mentioned transformation is profitable.
4255 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4256                                     unsigned ExtOpc,
4257                                     SmallVector<SDNode*, 4> &ExtendNodes,
4258                                     const TargetLowering &TLI) {
4259   bool HasCopyToRegUses = false;
4260   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4261   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4262                             UE = N0.getNode()->use_end();
4263        UI != UE; ++UI) {
4264     SDNode *User = *UI;
4265     if (User == N)
4266       continue;
4267     if (UI.getUse().getResNo() != N0.getResNo())
4268       continue;
4269     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4270     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4271       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4272       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4273         // Sign bits will be lost after a zext.
4274         return false;
4275       bool Add = false;
4276       for (unsigned i = 0; i != 2; ++i) {
4277         SDValue UseOp = User->getOperand(i);
4278         if (UseOp == N0)
4279           continue;
4280         if (!isa<ConstantSDNode>(UseOp))
4281           return false;
4282         Add = true;
4283       }
4284       if (Add)
4285         ExtendNodes.push_back(User);
4286       continue;
4287     }
4288     // If truncates aren't free and there are users we can't
4289     // extend, it isn't worthwhile.
4290     if (!isTruncFree)
4291       return false;
4292     // Remember if this value is live-out.
4293     if (User->getOpcode() == ISD::CopyToReg)
4294       HasCopyToRegUses = true;
4295   }
4296
4297   if (HasCopyToRegUses) {
4298     bool BothLiveOut = false;
4299     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4300          UI != UE; ++UI) {
4301       SDUse &Use = UI.getUse();
4302       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4303         BothLiveOut = true;
4304         break;
4305       }
4306     }
4307     if (BothLiveOut)
4308       // Both unextended and extended values are live out. There had better be
4309       // a good reason for the transformation.
4310       return ExtendNodes.size();
4311   }
4312   return true;
4313 }
4314
4315 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
4316                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
4317                                   ISD::NodeType ExtType) {
4318   // Extend SetCC uses if necessary.
4319   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4320     SDNode *SetCC = SetCCs[i];
4321     SmallVector<SDValue, 4> Ops;
4322
4323     for (unsigned j = 0; j != 2; ++j) {
4324       SDValue SOp = SetCC->getOperand(j);
4325       if (SOp == Trunc)
4326         Ops.push_back(ExtLoad);
4327       else
4328         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4329     }
4330
4331     Ops.push_back(SetCC->getOperand(2));
4332     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4333                                  &Ops[0], Ops.size()));
4334   }
4335 }
4336
4337 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4338   SDValue N0 = N->getOperand(0);
4339   EVT VT = N->getValueType(0);
4340
4341   // fold (sext c1) -> c1
4342   if (isa<ConstantSDNode>(N0))
4343     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
4344
4345   // fold (sext (sext x)) -> (sext x)
4346   // fold (sext (aext x)) -> (sext x)
4347   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4348     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
4349                        N0.getOperand(0));
4350
4351   if (N0.getOpcode() == ISD::TRUNCATE) {
4352     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4353     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4354     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4355     if (NarrowLoad.getNode()) {
4356       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4357       if (NarrowLoad.getNode() != N0.getNode()) {
4358         CombineTo(N0.getNode(), NarrowLoad);
4359         // CombineTo deleted the truncate, if needed, but not what's under it.
4360         AddToWorkList(oye);
4361       }
4362       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4363     }
4364
4365     // See if the value being truncated is already sign extended.  If so, just
4366     // eliminate the trunc/sext pair.
4367     SDValue Op = N0.getOperand(0);
4368     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4369     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4370     unsigned DestBits = VT.getScalarType().getSizeInBits();
4371     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4372
4373     if (OpBits == DestBits) {
4374       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4375       // bits, it is already ready.
4376       if (NumSignBits > DestBits-MidBits)
4377         return Op;
4378     } else if (OpBits < DestBits) {
4379       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4380       // bits, just sext from i32.
4381       if (NumSignBits > OpBits-MidBits)
4382         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
4383     } else {
4384       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4385       // bits, just truncate to i32.
4386       if (NumSignBits > OpBits-MidBits)
4387         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4388     }
4389
4390     // fold (sext (truncate x)) -> (sextinreg x).
4391     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4392                                                  N0.getValueType())) {
4393       if (OpBits < DestBits)
4394         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
4395       else if (OpBits > DestBits)
4396         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
4397       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
4398                          DAG.getValueType(N0.getValueType()));
4399     }
4400   }
4401
4402   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4403   // None of the supported targets knows how to perform load and sign extend
4404   // on vectors in one instruction.  We only perform this transformation on
4405   // scalars.
4406   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4407       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4408        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4409     bool DoXform = true;
4410     SmallVector<SDNode*, 4> SetCCs;
4411     if (!N0.hasOneUse())
4412       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4413     if (DoXform) {
4414       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4415       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4416                                        LN0->getChain(),
4417                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4418                                        N0.getValueType(),
4419                                        LN0->isVolatile(), LN0->isNonTemporal(),
4420                                        LN0->getAlignment());
4421       CombineTo(N, ExtLoad);
4422       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4423                                   N0.getValueType(), ExtLoad);
4424       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4425       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4426                       ISD::SIGN_EXTEND);
4427       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4428     }
4429   }
4430
4431   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4432   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4433   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4434       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4435     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4436     EVT MemVT = LN0->getMemoryVT();
4437     if ((!LegalOperations && !LN0->isVolatile()) ||
4438         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4439       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4440                                        LN0->getChain(),
4441                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4442                                        MemVT,
4443                                        LN0->isVolatile(), LN0->isNonTemporal(),
4444                                        LN0->getAlignment());
4445       CombineTo(N, ExtLoad);
4446       CombineTo(N0.getNode(),
4447                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4448                             N0.getValueType(), ExtLoad),
4449                 ExtLoad.getValue(1));
4450       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4451     }
4452   }
4453
4454   // fold (sext (and/or/xor (load x), cst)) ->
4455   //      (and/or/xor (sextload x), (sext cst))
4456   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4457        N0.getOpcode() == ISD::XOR) &&
4458       isa<LoadSDNode>(N0.getOperand(0)) &&
4459       N0.getOperand(1).getOpcode() == ISD::Constant &&
4460       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4461       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4462     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4463     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4464       bool DoXform = true;
4465       SmallVector<SDNode*, 4> SetCCs;
4466       if (!N0.hasOneUse())
4467         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4468                                           SetCCs, TLI);
4469       if (DoXform) {
4470         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
4471                                          LN0->getChain(), LN0->getBasePtr(),
4472                                          LN0->getPointerInfo(),
4473                                          LN0->getMemoryVT(),
4474                                          LN0->isVolatile(),
4475                                          LN0->isNonTemporal(),
4476                                          LN0->getAlignment());
4477         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4478         Mask = Mask.sext(VT.getSizeInBits());
4479         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4480                                   ExtLoad, DAG.getConstant(Mask, VT));
4481         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4482                                     N0.getOperand(0).getDebugLoc(),
4483                                     N0.getOperand(0).getValueType(), ExtLoad);
4484         CombineTo(N, And);
4485         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4486         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4487                         ISD::SIGN_EXTEND);
4488         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4489       }
4490     }
4491   }
4492
4493   if (N0.getOpcode() == ISD::SETCC) {
4494     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4495     // Only do this before legalize for now.
4496     if (VT.isVector() && !LegalOperations &&
4497         TLI.getBooleanContents(true) == 
4498           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4499       EVT N0VT = N0.getOperand(0).getValueType();
4500       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4501       // of the same size as the compared operands. Only optimize sext(setcc())
4502       // if this is the case.
4503       EVT SVT = TLI.getSetCCResultType(N0VT);
4504
4505       // We know that the # elements of the results is the same as the
4506       // # elements of the compare (and the # elements of the compare result
4507       // for that matter).  Check to see that they are the same size.  If so,
4508       // we know that the element size of the sext'd result matches the
4509       // element size of the compare operands.
4510       if (VT.getSizeInBits() == SVT.getSizeInBits())
4511         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4512                              N0.getOperand(1),
4513                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4514       // If the desired elements are smaller or larger than the source
4515       // elements we can use a matching integer vector type and then
4516       // truncate/sign extend
4517       EVT MatchingElementType =
4518         EVT::getIntegerVT(*DAG.getContext(),
4519                           N0VT.getScalarType().getSizeInBits());
4520       EVT MatchingVectorType =
4521         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4522                          N0VT.getVectorNumElements());
4523
4524       if (SVT == MatchingVectorType) {
4525         SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
4526                                N0.getOperand(0), N0.getOperand(1),
4527                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4528         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4529       }
4530     }
4531
4532     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4533     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4534     SDValue NegOne =
4535       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4536     SDValue SCC =
4537       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4538                        NegOne, DAG.getConstant(0, VT),
4539                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4540     if (SCC.getNode()) return SCC;
4541     if (!VT.isVector() && (!LegalOperations ||
4542         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT))))
4543       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
4544                          DAG.getSetCC(N->getDebugLoc(),
4545                                       TLI.getSetCCResultType(VT),
4546                                       N0.getOperand(0), N0.getOperand(1),
4547                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4548                          NegOne, DAG.getConstant(0, VT));
4549   }
4550
4551   // fold (sext x) -> (zext x) if the sign bit is known zero.
4552   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4553       DAG.SignBitIsZero(N0))
4554     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4555
4556   return SDValue();
4557 }
4558
4559 // isTruncateOf - If N is a truncate of some other value, return true, record
4560 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4561 // This function computes KnownZero to avoid a duplicated call to
4562 // ComputeMaskedBits in the caller.
4563 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4564                          APInt &KnownZero) {
4565   APInt KnownOne;
4566   if (N->getOpcode() == ISD::TRUNCATE) {
4567     Op = N->getOperand(0);
4568     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4569     return true;
4570   }
4571
4572   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4573       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4574     return false;
4575
4576   SDValue Op0 = N->getOperand(0);
4577   SDValue Op1 = N->getOperand(1);
4578   assert(Op0.getValueType() == Op1.getValueType());
4579
4580   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4581   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4582   if (COp0 && COp0->isNullValue())
4583     Op = Op1;
4584   else if (COp1 && COp1->isNullValue())
4585     Op = Op0;
4586   else
4587     return false;
4588
4589   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4590
4591   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4592     return false;
4593
4594   return true;
4595 }
4596
4597 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   EVT VT = N->getValueType(0);
4600
4601   // fold (zext c1) -> c1
4602   if (isa<ConstantSDNode>(N0))
4603     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
4604   // fold (zext (zext x)) -> (zext x)
4605   // fold (zext (aext x)) -> (zext x)
4606   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4607     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
4608                        N0.getOperand(0));
4609
4610   // fold (zext (truncate x)) -> (zext x) or
4611   //      (zext (truncate x)) -> (truncate x)
4612   // This is valid when the truncated bits of x are already zero.
4613   // FIXME: We should extend this to work for vectors too.
4614   SDValue Op;
4615   APInt KnownZero;
4616   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4617     APInt TruncatedBits =
4618       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4619       APInt(Op.getValueSizeInBits(), 0) :
4620       APInt::getBitsSet(Op.getValueSizeInBits(),
4621                         N0.getValueSizeInBits(),
4622                         std::min(Op.getValueSizeInBits(),
4623                                  VT.getSizeInBits()));
4624     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4625       if (VT.bitsGT(Op.getValueType()))
4626         return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
4627       if (VT.bitsLT(Op.getValueType()))
4628         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4629
4630       return Op;
4631     }
4632   }
4633
4634   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4635   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4636   if (N0.getOpcode() == ISD::TRUNCATE) {
4637     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4638     if (NarrowLoad.getNode()) {
4639       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4640       if (NarrowLoad.getNode() != N0.getNode()) {
4641         CombineTo(N0.getNode(), NarrowLoad);
4642         // CombineTo deleted the truncate, if needed, but not what's under it.
4643         AddToWorkList(oye);
4644       }
4645       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4646     }
4647   }
4648
4649   // fold (zext (truncate x)) -> (and x, mask)
4650   if (N0.getOpcode() == ISD::TRUNCATE &&
4651       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4652
4653     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4654     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4655     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4656     if (NarrowLoad.getNode()) {
4657       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4658       if (NarrowLoad.getNode() != N0.getNode()) {
4659         CombineTo(N0.getNode(), NarrowLoad);
4660         // CombineTo deleted the truncate, if needed, but not what's under it.
4661         AddToWorkList(oye);
4662       }
4663       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4664     }
4665
4666     SDValue Op = N0.getOperand(0);
4667     if (Op.getValueType().bitsLT(VT)) {
4668       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
4669       AddToWorkList(Op.getNode());
4670     } else if (Op.getValueType().bitsGT(VT)) {
4671       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
4672       AddToWorkList(Op.getNode());
4673     }
4674     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
4675                                   N0.getValueType().getScalarType());
4676   }
4677
4678   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4679   // if either of the casts is not free.
4680   if (N0.getOpcode() == ISD::AND &&
4681       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4682       N0.getOperand(1).getOpcode() == ISD::Constant &&
4683       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4684                            N0.getValueType()) ||
4685        !TLI.isZExtFree(N0.getValueType(), VT))) {
4686     SDValue X = N0.getOperand(0).getOperand(0);
4687     if (X.getValueType().bitsLT(VT)) {
4688       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
4689     } else if (X.getValueType().bitsGT(VT)) {
4690       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4691     }
4692     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4693     Mask = Mask.zext(VT.getSizeInBits());
4694     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4695                        X, DAG.getConstant(Mask, VT));
4696   }
4697
4698   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4699   // None of the supported targets knows how to perform load and vector_zext
4700   // on vectors in one instruction.  We only perform this transformation on
4701   // scalars.
4702   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4703       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4704        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4705     bool DoXform = true;
4706     SmallVector<SDNode*, 4> SetCCs;
4707     if (!N0.hasOneUse())
4708       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4709     if (DoXform) {
4710       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4711       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4712                                        LN0->getChain(),
4713                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4714                                        N0.getValueType(),
4715                                        LN0->isVolatile(), LN0->isNonTemporal(),
4716                                        LN0->getAlignment());
4717       CombineTo(N, ExtLoad);
4718       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4719                                   N0.getValueType(), ExtLoad);
4720       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4721
4722       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4723                       ISD::ZERO_EXTEND);
4724       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4725     }
4726   }
4727
4728   // fold (zext (and/or/xor (load x), cst)) ->
4729   //      (and/or/xor (zextload x), (zext cst))
4730   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4731        N0.getOpcode() == ISD::XOR) &&
4732       isa<LoadSDNode>(N0.getOperand(0)) &&
4733       N0.getOperand(1).getOpcode() == ISD::Constant &&
4734       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4735       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4736     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4737     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4738       bool DoXform = true;
4739       SmallVector<SDNode*, 4> SetCCs;
4740       if (!N0.hasOneUse())
4741         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4742                                           SetCCs, TLI);
4743       if (DoXform) {
4744         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
4745                                          LN0->getChain(), LN0->getBasePtr(),
4746                                          LN0->getPointerInfo(),
4747                                          LN0->getMemoryVT(),
4748                                          LN0->isVolatile(),
4749                                          LN0->isNonTemporal(),
4750                                          LN0->getAlignment());
4751         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4752         Mask = Mask.zext(VT.getSizeInBits());
4753         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4754                                   ExtLoad, DAG.getConstant(Mask, VT));
4755         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4756                                     N0.getOperand(0).getDebugLoc(),
4757                                     N0.getOperand(0).getValueType(), ExtLoad);
4758         CombineTo(N, And);
4759         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4760         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4761                         ISD::ZERO_EXTEND);
4762         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4763       }
4764     }
4765   }
4766
4767   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4768   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4769   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4770       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4771     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4772     EVT MemVT = LN0->getMemoryVT();
4773     if ((!LegalOperations && !LN0->isVolatile()) ||
4774         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4775       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
4776                                        LN0->getChain(),
4777                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4778                                        MemVT,
4779                                        LN0->isVolatile(), LN0->isNonTemporal(),
4780                                        LN0->getAlignment());
4781       CombineTo(N, ExtLoad);
4782       CombineTo(N0.getNode(),
4783                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
4784                             ExtLoad),
4785                 ExtLoad.getValue(1));
4786       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4787     }
4788   }
4789
4790   if (N0.getOpcode() == ISD::SETCC) {
4791     if (!LegalOperations && VT.isVector()) {
4792       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4793       // Only do this before legalize for now.
4794       EVT N0VT = N0.getOperand(0).getValueType();
4795       EVT EltVT = VT.getVectorElementType();
4796       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4797                                     DAG.getConstant(1, EltVT));
4798       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4799         // We know that the # elements of the results is the same as the
4800         // # elements of the compare (and the # elements of the compare result
4801         // for that matter).  Check to see that they are the same size.  If so,
4802         // we know that the element size of the sext'd result matches the
4803         // element size of the compare operands.
4804         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4805                            DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4806                                          N0.getOperand(1),
4807                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4808                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4809                                        &OneOps[0], OneOps.size()));
4810
4811       // If the desired elements are smaller or larger than the source
4812       // elements we can use a matching integer vector type and then
4813       // truncate/sign extend
4814       EVT MatchingElementType =
4815         EVT::getIntegerVT(*DAG.getContext(),
4816                           N0VT.getScalarType().getSizeInBits());
4817       EVT MatchingVectorType =
4818         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4819                          N0VT.getVectorNumElements());
4820       SDValue VsetCC =
4821         DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4822                       N0.getOperand(1),
4823                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4824       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4825                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4826                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4827                                      &OneOps[0], OneOps.size()));
4828     }
4829
4830     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4831     SDValue SCC =
4832       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4833                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4834                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4835     if (SCC.getNode()) return SCC;
4836   }
4837
4838   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4839   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4840       isa<ConstantSDNode>(N0.getOperand(1)) &&
4841       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4842       N0.hasOneUse()) {
4843     SDValue ShAmt = N0.getOperand(1);
4844     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4845     if (N0.getOpcode() == ISD::SHL) {
4846       SDValue InnerZExt = N0.getOperand(0);
4847       // If the original shl may be shifting out bits, do not perform this
4848       // transformation.
4849       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4850         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4851       if (ShAmtVal > KnownZeroBits)
4852         return SDValue();
4853     }
4854
4855     DebugLoc DL = N->getDebugLoc();
4856
4857     // Ensure that the shift amount is wide enough for the shifted value.
4858     if (VT.getSizeInBits() >= 256)
4859       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4860
4861     return DAG.getNode(N0.getOpcode(), DL, VT,
4862                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4863                        ShAmt);
4864   }
4865
4866   return SDValue();
4867 }
4868
4869 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4870   SDValue N0 = N->getOperand(0);
4871   EVT VT = N->getValueType(0);
4872
4873   // fold (aext c1) -> c1
4874   if (isa<ConstantSDNode>(N0))
4875     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4876   // fold (aext (aext x)) -> (aext x)
4877   // fold (aext (zext x)) -> (zext x)
4878   // fold (aext (sext x)) -> (sext x)
4879   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
4880       N0.getOpcode() == ISD::ZERO_EXTEND ||
4881       N0.getOpcode() == ISD::SIGN_EXTEND)
4882     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4883
4884   // fold (aext (truncate (load x))) -> (aext (smaller load x))
4885   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4886   if (N0.getOpcode() == ISD::TRUNCATE) {
4887     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4888     if (NarrowLoad.getNode()) {
4889       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4890       if (NarrowLoad.getNode() != N0.getNode()) {
4891         CombineTo(N0.getNode(), NarrowLoad);
4892         // CombineTo deleted the truncate, if needed, but not what's under it.
4893         AddToWorkList(oye);
4894       }
4895       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4896     }
4897   }
4898
4899   // fold (aext (truncate x))
4900   if (N0.getOpcode() == ISD::TRUNCATE) {
4901     SDValue TruncOp = N0.getOperand(0);
4902     if (TruncOp.getValueType() == VT)
4903       return TruncOp; // x iff x size == zext size.
4904     if (TruncOp.getValueType().bitsGT(VT))
4905       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4906     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4907   }
4908
4909   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4910   // if the trunc is not free.
4911   if (N0.getOpcode() == ISD::AND &&
4912       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4913       N0.getOperand(1).getOpcode() == ISD::Constant &&
4914       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4915                           N0.getValueType())) {
4916     SDValue X = N0.getOperand(0).getOperand(0);
4917     if (X.getValueType().bitsLT(VT)) {
4918       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4919     } else if (X.getValueType().bitsGT(VT)) {
4920       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4921     }
4922     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4923     Mask = Mask.zext(VT.getSizeInBits());
4924     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4925                        X, DAG.getConstant(Mask, VT));
4926   }
4927
4928   // fold (aext (load x)) -> (aext (truncate (extload x)))
4929   // None of the supported targets knows how to perform load and any_ext
4930   // on vectors in one instruction.  We only perform this transformation on
4931   // scalars.
4932   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4933       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4934        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4935     bool DoXform = true;
4936     SmallVector<SDNode*, 4> SetCCs;
4937     if (!N0.hasOneUse())
4938       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4939     if (DoXform) {
4940       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4941       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4942                                        LN0->getChain(),
4943                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4944                                        N0.getValueType(),
4945                                        LN0->isVolatile(), LN0->isNonTemporal(),
4946                                        LN0->getAlignment());
4947       CombineTo(N, ExtLoad);
4948       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4949                                   N0.getValueType(), ExtLoad);
4950       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4951       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
4952                       ISD::ANY_EXTEND);
4953       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4954     }
4955   }
4956
4957   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4958   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4959   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
4960   if (N0.getOpcode() == ISD::LOAD &&
4961       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4962       N0.hasOneUse()) {
4963     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4964     EVT MemVT = LN0->getMemoryVT();
4965     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4966                                      VT, LN0->getChain(), LN0->getBasePtr(),
4967                                      LN0->getPointerInfo(), MemVT,
4968                                      LN0->isVolatile(), LN0->isNonTemporal(),
4969                                      LN0->getAlignment());
4970     CombineTo(N, ExtLoad);
4971     CombineTo(N0.getNode(),
4972               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4973                           N0.getValueType(), ExtLoad),
4974               ExtLoad.getValue(1));
4975     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4976   }
4977
4978   if (N0.getOpcode() == ISD::SETCC) {
4979     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4980     // Only do this before legalize for now.
4981     if (VT.isVector() && !LegalOperations) {
4982       EVT N0VT = N0.getOperand(0).getValueType();
4983         // We know that the # elements of the results is the same as the
4984         // # elements of the compare (and the # elements of the compare result
4985         // for that matter).  Check to see that they are the same size.  If so,
4986         // we know that the element size of the sext'd result matches the
4987         // element size of the compare operands.
4988       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4989         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4990                              N0.getOperand(1),
4991                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4992       // If the desired elements are smaller or larger than the source
4993       // elements we can use a matching integer vector type and then
4994       // truncate/sign extend
4995       else {
4996         EVT MatchingElementType =
4997           EVT::getIntegerVT(*DAG.getContext(),
4998                             N0VT.getScalarType().getSizeInBits());
4999         EVT MatchingVectorType =
5000           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5001                            N0VT.getVectorNumElements());
5002         SDValue VsetCC =
5003           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
5004                         N0.getOperand(1),
5005                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5006         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
5007       }
5008     }
5009
5010     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5011     SDValue SCC =
5012       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
5013                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5014                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5015     if (SCC.getNode())
5016       return SCC;
5017   }
5018
5019   return SDValue();
5020 }
5021
5022 /// GetDemandedBits - See if the specified operand can be simplified with the
5023 /// knowledge that only the bits specified by Mask are used.  If so, return the
5024 /// simpler operand, otherwise return a null SDValue.
5025 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5026   switch (V.getOpcode()) {
5027   default: break;
5028   case ISD::Constant: {
5029     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5030     assert(CV != 0 && "Const value should be ConstSDNode.");
5031     const APInt &CVal = CV->getAPIntValue();
5032     APInt NewVal = CVal & Mask;
5033     if (NewVal != CVal) {
5034       return DAG.getConstant(NewVal, V.getValueType());
5035     }
5036     break;
5037   }
5038   case ISD::OR:
5039   case ISD::XOR:
5040     // If the LHS or RHS don't contribute bits to the or, drop them.
5041     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5042       return V.getOperand(1);
5043     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5044       return V.getOperand(0);
5045     break;
5046   case ISD::SRL:
5047     // Only look at single-use SRLs.
5048     if (!V.getNode()->hasOneUse())
5049       break;
5050     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5051       // See if we can recursively simplify the LHS.
5052       unsigned Amt = RHSC->getZExtValue();
5053
5054       // Watch out for shift count overflow though.
5055       if (Amt >= Mask.getBitWidth()) break;
5056       APInt NewMask = Mask << Amt;
5057       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5058       if (SimplifyLHS.getNode())
5059         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
5060                            SimplifyLHS, V.getOperand(1));
5061     }
5062   }
5063   return SDValue();
5064 }
5065
5066 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5067 /// bits and then truncated to a narrower type and where N is a multiple
5068 /// of number of bits of the narrower type, transform it to a narrower load
5069 /// from address + N / num of bits of new type. If the result is to be
5070 /// extended, also fold the extension to form a extending load.
5071 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5072   unsigned Opc = N->getOpcode();
5073
5074   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5075   SDValue N0 = N->getOperand(0);
5076   EVT VT = N->getValueType(0);
5077   EVT ExtVT = VT;
5078
5079   // This transformation isn't valid for vector loads.
5080   if (VT.isVector())
5081     return SDValue();
5082
5083   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5084   // extended to VT.
5085   if (Opc == ISD::SIGN_EXTEND_INREG) {
5086     ExtType = ISD::SEXTLOAD;
5087     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5088   } else if (Opc == ISD::SRL) {
5089     // Another special-case: SRL is basically zero-extending a narrower value.
5090     ExtType = ISD::ZEXTLOAD;
5091     N0 = SDValue(N, 0);
5092     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5093     if (!N01) return SDValue();
5094     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5095                               VT.getSizeInBits() - N01->getZExtValue());
5096   }
5097   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5098     return SDValue();
5099
5100   unsigned EVTBits = ExtVT.getSizeInBits();
5101
5102   // Do not generate loads of non-round integer types since these can
5103   // be expensive (and would be wrong if the type is not byte sized).
5104   if (!ExtVT.isRound())
5105     return SDValue();
5106
5107   unsigned ShAmt = 0;
5108   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5109     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5110       ShAmt = N01->getZExtValue();
5111       // Is the shift amount a multiple of size of VT?
5112       if ((ShAmt & (EVTBits-1)) == 0) {
5113         N0 = N0.getOperand(0);
5114         // Is the load width a multiple of size of VT?
5115         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5116           return SDValue();
5117       }
5118
5119       // At this point, we must have a load or else we can't do the transform.
5120       if (!isa<LoadSDNode>(N0)) return SDValue();
5121
5122       // Because a SRL must be assumed to *need* to zero-extend the high bits
5123       // (as opposed to anyext the high bits), we can't combine the zextload
5124       // lowering of SRL and an sextload.
5125       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5126         return SDValue();
5127
5128       // If the shift amount is larger than the input type then we're not
5129       // accessing any of the loaded bytes.  If the load was a zextload/extload
5130       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5131       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5132         return SDValue();
5133     }
5134   }
5135
5136   // If the load is shifted left (and the result isn't shifted back right),
5137   // we can fold the truncate through the shift.
5138   unsigned ShLeftAmt = 0;
5139   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5140       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5141     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5142       ShLeftAmt = N01->getZExtValue();
5143       N0 = N0.getOperand(0);
5144     }
5145   }
5146
5147   // If we haven't found a load, we can't narrow it.  Don't transform one with
5148   // multiple uses, this would require adding a new load.
5149   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5150     return SDValue();
5151
5152   // Don't change the width of a volatile load.
5153   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5154   if (LN0->isVolatile())
5155     return SDValue();
5156
5157   // Verify that we are actually reducing a load width here.
5158   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5159     return SDValue();
5160
5161   // For the transform to be legal, the load must produce only two values
5162   // (the value loaded and the chain).  Don't transform a pre-increment
5163   // load, for example, which produces an extra value.  Otherwise the 
5164   // transformation is not equivalent, and the downstream logic to replace
5165   // uses gets things wrong.
5166   if (LN0->getNumValues() > 2)
5167     return SDValue();
5168
5169   EVT PtrType = N0.getOperand(1).getValueType();
5170
5171   if (PtrType == MVT::Untyped || PtrType.isExtended())
5172     // It's not possible to generate a constant of extended or untyped type.
5173     return SDValue();
5174
5175   // For big endian targets, we need to adjust the offset to the pointer to
5176   // load the correct bytes.
5177   if (TLI.isBigEndian()) {
5178     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5179     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5180     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5181   }
5182
5183   uint64_t PtrOff = ShAmt / 8;
5184   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5185   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
5186                                PtrType, LN0->getBasePtr(),
5187                                DAG.getConstant(PtrOff, PtrType));
5188   AddToWorkList(NewPtr.getNode());
5189
5190   SDValue Load;
5191   if (ExtType == ISD::NON_EXTLOAD)
5192     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
5193                         LN0->getPointerInfo().getWithOffset(PtrOff),
5194                         LN0->isVolatile(), LN0->isNonTemporal(),
5195                         LN0->isInvariant(), NewAlign);
5196   else
5197     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
5198                           LN0->getPointerInfo().getWithOffset(PtrOff),
5199                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5200                           NewAlign);
5201
5202   // Replace the old load's chain with the new load's chain.
5203   WorkListRemover DeadNodes(*this);
5204   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5205
5206   // Shift the result left, if we've swallowed a left shift.
5207   SDValue Result = Load;
5208   if (ShLeftAmt != 0) {
5209     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5210     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5211       ShImmTy = VT;
5212     // If the shift amount is as large as the result size (but, presumably,
5213     // no larger than the source) then the useful bits of the result are
5214     // zero; we can't simply return the shortened shift, because the result
5215     // of that operation is undefined.
5216     if (ShLeftAmt >= VT.getSizeInBits())
5217       Result = DAG.getConstant(0, VT);
5218     else
5219       Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
5220                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5221   }
5222
5223   // Return the new loaded value.
5224   return Result;
5225 }
5226
5227 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5228   SDValue N0 = N->getOperand(0);
5229   SDValue N1 = N->getOperand(1);
5230   EVT VT = N->getValueType(0);
5231   EVT EVT = cast<VTSDNode>(N1)->getVT();
5232   unsigned VTBits = VT.getScalarType().getSizeInBits();
5233   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5234
5235   // fold (sext_in_reg c1) -> c1
5236   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5237     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
5238
5239   // If the input is already sign extended, just drop the extension.
5240   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5241     return N0;
5242
5243   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5244   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5245       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
5246     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5247                        N0.getOperand(0), N1);
5248   }
5249
5250   // fold (sext_in_reg (sext x)) -> (sext x)
5251   // fold (sext_in_reg (aext x)) -> (sext x)
5252   // if x is small enough.
5253   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5254     SDValue N00 = N0.getOperand(0);
5255     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5256         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5257       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
5258   }
5259
5260   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5261   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5262     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
5263
5264   // fold operands of sext_in_reg based on knowledge that the top bits are not
5265   // demanded.
5266   if (SimplifyDemandedBits(SDValue(N, 0)))
5267     return SDValue(N, 0);
5268
5269   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5270   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5271   SDValue NarrowLoad = ReduceLoadWidth(N);
5272   if (NarrowLoad.getNode())
5273     return NarrowLoad;
5274
5275   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5276   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5277   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5278   if (N0.getOpcode() == ISD::SRL) {
5279     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5280       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5281         // We can turn this into an SRA iff the input to the SRL is already sign
5282         // extended enough.
5283         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5284         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5285           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
5286                              N0.getOperand(0), N0.getOperand(1));
5287       }
5288   }
5289
5290   // fold (sext_inreg (extload x)) -> (sextload x)
5291   if (ISD::isEXTLoad(N0.getNode()) &&
5292       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5293       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5294       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5295        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5296     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5297     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5298                                      LN0->getChain(),
5299                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5300                                      EVT,
5301                                      LN0->isVolatile(), LN0->isNonTemporal(),
5302                                      LN0->getAlignment());
5303     CombineTo(N, ExtLoad);
5304     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5305     AddToWorkList(ExtLoad.getNode());
5306     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5307   }
5308   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5309   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5310       N0.hasOneUse() &&
5311       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5312       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5313        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5314     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5315     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
5316                                      LN0->getChain(),
5317                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5318                                      EVT,
5319                                      LN0->isVolatile(), LN0->isNonTemporal(),
5320                                      LN0->getAlignment());
5321     CombineTo(N, ExtLoad);
5322     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5323     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5324   }
5325
5326   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5327   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5328     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5329                                        N0.getOperand(1), false);
5330     if (BSwap.getNode() != 0)
5331       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
5332                          BSwap, N1);
5333   }
5334
5335   return SDValue();
5336 }
5337
5338 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5339   SDValue N0 = N->getOperand(0);
5340   EVT VT = N->getValueType(0);
5341   bool isLE = TLI.isLittleEndian();
5342
5343   // noop truncate
5344   if (N0.getValueType() == N->getValueType(0))
5345     return N0;
5346   // fold (truncate c1) -> c1
5347   if (isa<ConstantSDNode>(N0))
5348     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
5349   // fold (truncate (truncate x)) -> (truncate x)
5350   if (N0.getOpcode() == ISD::TRUNCATE)
5351     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5352   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5353   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5354       N0.getOpcode() == ISD::SIGN_EXTEND ||
5355       N0.getOpcode() == ISD::ANY_EXTEND) {
5356     if (N0.getOperand(0).getValueType().bitsLT(VT))
5357       // if the source is smaller than the dest, we still need an extend
5358       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
5359                          N0.getOperand(0));
5360     if (N0.getOperand(0).getValueType().bitsGT(VT))
5361       // if the source is larger than the dest, than we just need the truncate
5362       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
5363     // if the source and dest are the same type, we can drop both the extend
5364     // and the truncate.
5365     return N0.getOperand(0);
5366   }
5367
5368   // Fold extract-and-trunc into a narrow extract. For example:
5369   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5370   //   i32 y = TRUNCATE(i64 x)
5371   //        -- becomes --
5372   //   v16i8 b = BITCAST (v2i64 val)
5373   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5374   //
5375   // Note: We only run this optimization after type legalization (which often
5376   // creates this pattern) and before operation legalization after which
5377   // we need to be more careful about the vector instructions that we generate.
5378   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5379       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5380
5381     EVT VecTy = N0.getOperand(0).getValueType();
5382     EVT ExTy = N0.getValueType();
5383     EVT TrTy = N->getValueType(0);
5384
5385     unsigned NumElem = VecTy.getVectorNumElements();
5386     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5387
5388     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5389     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5390
5391     SDValue EltNo = N0->getOperand(1);
5392     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5393       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5394       EVT IndexTy = N0->getOperand(1).getValueType();
5395       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5396
5397       SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5398                               NVT, N0.getOperand(0));
5399
5400       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5401                          N->getDebugLoc(), TrTy, V,
5402                          DAG.getConstant(Index, IndexTy));
5403     }
5404   }
5405
5406   // Fold a series of buildvector, bitcast, and truncate if possible.
5407   // For example fold
5408   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5409   //   (2xi32 (buildvector x, y)).
5410   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5411       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5412       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5413       N0.getOperand(0).hasOneUse()) {
5414
5415     SDValue BuildVect = N0.getOperand(0);
5416     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5417     EVT TruncVecEltTy = VT.getVectorElementType();
5418
5419     // Check that the element types match.
5420     if (BuildVectEltTy == TruncVecEltTy) {
5421       // Now we only need to compute the offset of the truncated elements.
5422       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5423       unsigned TruncVecNumElts = VT.getVectorNumElements();
5424       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5425
5426       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5427              "Invalid number of elements");
5428
5429       SmallVector<SDValue, 8> Opnds;
5430       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5431         Opnds.push_back(BuildVect.getOperand(i));
5432
5433       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, &Opnds[0],
5434                          Opnds.size());
5435     }
5436   }
5437
5438   // See if we can simplify the input to this truncate through knowledge that
5439   // only the low bits are being used.
5440   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5441   // Currently we only perform this optimization on scalars because vectors
5442   // may have different active low bits.
5443   if (!VT.isVector()) {
5444     SDValue Shorter =
5445       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5446                                                VT.getSizeInBits()));
5447     if (Shorter.getNode())
5448       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
5449   }
5450   // fold (truncate (load x)) -> (smaller load x)
5451   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5452   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5453     SDValue Reduced = ReduceLoadWidth(N);
5454     if (Reduced.getNode())
5455       return Reduced;
5456   }
5457   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5458   // where ... are all 'undef'.
5459   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5460     SmallVector<EVT, 8> VTs;
5461     SDValue V;
5462     unsigned Idx = 0;
5463     unsigned NumDefs = 0;
5464
5465     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5466       SDValue X = N0.getOperand(i);
5467       if (X.getOpcode() != ISD::UNDEF) {
5468         V = X;
5469         Idx = i;
5470         NumDefs++;
5471       }
5472       // Stop if more than one members are non-undef.
5473       if (NumDefs > 1)
5474         break;
5475       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5476                                      VT.getVectorElementType(),
5477                                      X.getValueType().getVectorNumElements()));
5478     }
5479
5480     if (NumDefs == 0)
5481       return DAG.getUNDEF(VT);
5482
5483     if (NumDefs == 1) {
5484       assert(V.getNode() && "The single defined operand is empty!");
5485       SmallVector<SDValue, 8> Opnds;
5486       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5487         if (i != Idx) {
5488           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5489           continue;
5490         }
5491         SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
5492         AddToWorkList(NV.getNode());
5493         Opnds.push_back(NV);
5494       }
5495       return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
5496                          &Opnds[0], Opnds.size());
5497     }
5498   }
5499
5500   // Simplify the operands using demanded-bits information.
5501   if (!VT.isVector() &&
5502       SimplifyDemandedBits(SDValue(N, 0)))
5503     return SDValue(N, 0);
5504
5505   return SDValue();
5506 }
5507
5508 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5509   SDValue Elt = N->getOperand(i);
5510   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5511     return Elt.getNode();
5512   return Elt.getOperand(Elt.getResNo()).getNode();
5513 }
5514
5515 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5516 /// if load locations are consecutive.
5517 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5518   assert(N->getOpcode() == ISD::BUILD_PAIR);
5519
5520   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5521   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5522   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5523       LD1->getPointerInfo().getAddrSpace() !=
5524          LD2->getPointerInfo().getAddrSpace())
5525     return SDValue();
5526   EVT LD1VT = LD1->getValueType(0);
5527
5528   if (ISD::isNON_EXTLoad(LD2) &&
5529       LD2->hasOneUse() &&
5530       // If both are volatile this would reduce the number of volatile loads.
5531       // If one is volatile it might be ok, but play conservative and bail out.
5532       !LD1->isVolatile() &&
5533       !LD2->isVolatile() &&
5534       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5535     unsigned Align = LD1->getAlignment();
5536     unsigned NewAlign = TLI.getDataLayout()->
5537       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5538
5539     if (NewAlign <= Align &&
5540         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5541       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
5542                          LD1->getBasePtr(), LD1->getPointerInfo(),
5543                          false, false, false, Align);
5544   }
5545
5546   return SDValue();
5547 }
5548
5549 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5550   SDValue N0 = N->getOperand(0);
5551   EVT VT = N->getValueType(0);
5552
5553   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5554   // Only do this before legalize, since afterward the target may be depending
5555   // on the bitconvert.
5556   // First check to see if this is all constant.
5557   if (!LegalTypes &&
5558       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5559       VT.isVector()) {
5560     bool isSimple = true;
5561     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5562       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5563           N0.getOperand(i).getOpcode() != ISD::Constant &&
5564           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5565         isSimple = false;
5566         break;
5567       }
5568
5569     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5570     assert(!DestEltVT.isVector() &&
5571            "Element type of vector ValueType must not be vector!");
5572     if (isSimple)
5573       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5574   }
5575
5576   // If the input is a constant, let getNode fold it.
5577   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5578     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
5579     if (Res.getNode() != N) {
5580       if (!LegalOperations ||
5581           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5582         return Res;
5583
5584       // Folding it resulted in an illegal node, and it's too late to
5585       // do that. Clean up the old node and forego the transformation.
5586       // Ideally this won't happen very often, because instcombine
5587       // and the earlier dagcombine runs (where illegal nodes are
5588       // permitted) should have folded most of them already.
5589       DAG.DeleteNode(Res.getNode());
5590     }
5591   }
5592
5593   // (conv (conv x, t1), t2) -> (conv x, t2)
5594   if (N0.getOpcode() == ISD::BITCAST)
5595     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
5596                        N0.getOperand(0));
5597
5598   // fold (conv (load x)) -> (load (conv*)x)
5599   // If the resultant load doesn't need a higher alignment than the original!
5600   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5601       // Do not change the width of a volatile load.
5602       !cast<LoadSDNode>(N0)->isVolatile() &&
5603       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5604     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5605     unsigned Align = TLI.getDataLayout()->
5606       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5607     unsigned OrigAlign = LN0->getAlignment();
5608
5609     if (Align <= OrigAlign) {
5610       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
5611                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5612                                  LN0->isVolatile(), LN0->isNonTemporal(),
5613                                  LN0->isInvariant(), OrigAlign);
5614       AddToWorkList(N);
5615       CombineTo(N0.getNode(),
5616                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5617                             N0.getValueType(), Load),
5618                 Load.getValue(1));
5619       return Load;
5620     }
5621   }
5622
5623   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5624   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5625   // This often reduces constant pool loads.
5626   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
5627        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
5628       N0.getNode()->hasOneUse() && VT.isInteger() &&
5629       !VT.isVector() && !N0.getValueType().isVector()) {
5630     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
5631                                   N0.getOperand(0));
5632     AddToWorkList(NewConv.getNode());
5633
5634     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5635     if (N0.getOpcode() == ISD::FNEG)
5636       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
5637                          NewConv, DAG.getConstant(SignBit, VT));
5638     assert(N0.getOpcode() == ISD::FABS);
5639     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
5640                        NewConv, DAG.getConstant(~SignBit, VT));
5641   }
5642
5643   // fold (bitconvert (fcopysign cst, x)) ->
5644   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5645   // Note that we don't handle (copysign x, cst) because this can always be
5646   // folded to an fneg or fabs.
5647   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5648       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5649       VT.isInteger() && !VT.isVector()) {
5650     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5651     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5652     if (isTypeLegal(IntXVT)) {
5653       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5654                               IntXVT, N0.getOperand(1));
5655       AddToWorkList(X.getNode());
5656
5657       // If X has a different width than the result/lhs, sext it or truncate it.
5658       unsigned VTWidth = VT.getSizeInBits();
5659       if (OrigXWidth < VTWidth) {
5660         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
5661         AddToWorkList(X.getNode());
5662       } else if (OrigXWidth > VTWidth) {
5663         // To get the sign bit in the right place, we have to shift it right
5664         // before truncating.
5665         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
5666                         X.getValueType(), X,
5667                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5668         AddToWorkList(X.getNode());
5669         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
5670         AddToWorkList(X.getNode());
5671       }
5672
5673       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5674       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
5675                       X, DAG.getConstant(SignBit, VT));
5676       AddToWorkList(X.getNode());
5677
5678       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
5679                                 VT, N0.getOperand(0));
5680       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
5681                         Cst, DAG.getConstant(~SignBit, VT));
5682       AddToWorkList(Cst.getNode());
5683
5684       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
5685     }
5686   }
5687
5688   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5689   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5690     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5691     if (CombineLD.getNode())
5692       return CombineLD;
5693   }
5694
5695   return SDValue();
5696 }
5697
5698 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5699   EVT VT = N->getValueType(0);
5700   return CombineConsecutiveLoads(N, VT);
5701 }
5702
5703 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5704 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5705 /// destination element value type.
5706 SDValue DAGCombiner::
5707 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5708   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5709
5710   // If this is already the right type, we're done.
5711   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5712
5713   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5714   unsigned DstBitSize = DstEltVT.getSizeInBits();
5715
5716   // If this is a conversion of N elements of one type to N elements of another
5717   // type, convert each element.  This handles FP<->INT cases.
5718   if (SrcBitSize == DstBitSize) {
5719     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5720                               BV->getValueType(0).getVectorNumElements());
5721
5722     // Due to the FP element handling below calling this routine recursively,
5723     // we can end up with a scalar-to-vector node here.
5724     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5725       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5726                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5727                                      DstEltVT, BV->getOperand(0)));
5728
5729     SmallVector<SDValue, 8> Ops;
5730     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5731       SDValue Op = BV->getOperand(i);
5732       // If the vector element type is not legal, the BUILD_VECTOR operands
5733       // are promoted and implicitly truncated.  Make that explicit here.
5734       if (Op.getValueType() != SrcEltVT)
5735         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
5736       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
5737                                 DstEltVT, Op));
5738       AddToWorkList(Ops.back().getNode());
5739     }
5740     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5741                        &Ops[0], Ops.size());
5742   }
5743
5744   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5745   // handle annoying details of growing/shrinking FP values, we convert them to
5746   // int first.
5747   if (SrcEltVT.isFloatingPoint()) {
5748     // Convert the input float vector to a int vector where the elements are the
5749     // same sizes.
5750     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5751     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5752     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5753     SrcEltVT = IntVT;
5754   }
5755
5756   // Now we know the input is an integer vector.  If the output is a FP type,
5757   // convert to integer first, then to FP of the right size.
5758   if (DstEltVT.isFloatingPoint()) {
5759     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5760     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5761     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5762
5763     // Next, convert to FP elements of the same size.
5764     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5765   }
5766
5767   // Okay, we know the src/dst types are both integers of differing types.
5768   // Handling growing first.
5769   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5770   if (SrcBitSize < DstBitSize) {
5771     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5772
5773     SmallVector<SDValue, 8> Ops;
5774     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5775          i += NumInputsPerOutput) {
5776       bool isLE = TLI.isLittleEndian();
5777       APInt NewBits = APInt(DstBitSize, 0);
5778       bool EltIsUndef = true;
5779       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5780         // Shift the previously computed bits over.
5781         NewBits <<= SrcBitSize;
5782         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5783         if (Op.getOpcode() == ISD::UNDEF) continue;
5784         EltIsUndef = false;
5785
5786         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5787                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5788       }
5789
5790       if (EltIsUndef)
5791         Ops.push_back(DAG.getUNDEF(DstEltVT));
5792       else
5793         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5794     }
5795
5796     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5797     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5798                        &Ops[0], Ops.size());
5799   }
5800
5801   // Finally, this must be the case where we are shrinking elements: each input
5802   // turns into multiple outputs.
5803   bool isS2V = ISD::isScalarToVector(BV);
5804   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5805   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5806                             NumOutputsPerInput*BV->getNumOperands());
5807   SmallVector<SDValue, 8> Ops;
5808
5809   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5810     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5811       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5812         Ops.push_back(DAG.getUNDEF(DstEltVT));
5813       continue;
5814     }
5815
5816     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5817                   getAPIntValue().zextOrTrunc(SrcBitSize);
5818
5819     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5820       APInt ThisVal = OpVal.trunc(DstBitSize);
5821       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5822       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5823         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5824         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
5825                            Ops[0]);
5826       OpVal = OpVal.lshr(DstBitSize);
5827     }
5828
5829     // For big endian targets, swap the order of the pieces of each element.
5830     if (TLI.isBigEndian())
5831       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5832   }
5833
5834   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
5835                      &Ops[0], Ops.size());
5836 }
5837
5838 SDValue DAGCombiner::visitFADD(SDNode *N) {
5839   SDValue N0 = N->getOperand(0);
5840   SDValue N1 = N->getOperand(1);
5841   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5842   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5843   EVT VT = N->getValueType(0);
5844
5845   // fold vector ops
5846   if (VT.isVector()) {
5847     SDValue FoldedVOp = SimplifyVBinOp(N);
5848     if (FoldedVOp.getNode()) return FoldedVOp;
5849   }
5850
5851   // fold (fadd c1, c2) -> c1 + c2
5852   if (N0CFP && N1CFP)
5853     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
5854   // canonicalize constant to RHS
5855   if (N0CFP && !N1CFP)
5856     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
5857   // fold (fadd A, 0) -> A
5858   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5859       N1CFP->getValueAPF().isZero())
5860     return N0;
5861   // fold (fadd A, (fneg B)) -> (fsub A, B)
5862   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5863     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5864     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
5865                        GetNegatedExpression(N1, DAG, LegalOperations));
5866   // fold (fadd (fneg A), B) -> (fsub B, A)
5867   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5868     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5869     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
5870                        GetNegatedExpression(N0, DAG, LegalOperations));
5871
5872   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
5873   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5874       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
5875       isa<ConstantFPSDNode>(N0.getOperand(1)))
5876     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
5877                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5878                                    N0.getOperand(1), N1));
5879
5880   // No FP constant should be created after legalization as Instruction
5881   // Selection pass has hard time in dealing with FP constant.
5882   //
5883   // We don't need test this condition for transformation like following, as
5884   // the DAG being transformed implies it is legal to take FP constant as
5885   // operand.
5886   // 
5887   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
5888   // 
5889   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
5890
5891   // If allow, fold (fadd (fneg x), x) -> 0.0
5892   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5893       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
5894     return DAG.getConstantFP(0.0, VT);
5895   }
5896
5897     // If allow, fold (fadd x, (fneg x)) -> 0.0
5898   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
5899       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
5900     return DAG.getConstantFP(0.0, VT);
5901   }
5902
5903   // In unsafe math mode, we can fold chains of FADD's of the same value
5904   // into multiplications.  This transform is not safe in general because
5905   // we are reducing the number of rounding steps.
5906   if (DAG.getTarget().Options.UnsafeFPMath &&
5907       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
5908       !N0CFP && !N1CFP) {
5909     if (N0.getOpcode() == ISD::FMUL) {
5910       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
5911       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
5912
5913       // (fadd (fmul c, x), x) -> (fmul c+1, x)
5914       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
5915         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5916                                      SDValue(CFP00, 0),
5917                                      DAG.getConstantFP(1.0, VT));
5918         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5919                            N1, NewCFP);
5920       }
5921
5922       // (fadd (fmul x, c), x) -> (fmul c+1, x)
5923       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
5924         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5925                                      SDValue(CFP01, 0),
5926                                      DAG.getConstantFP(1.0, VT));
5927         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5928                            N1, NewCFP);
5929       }
5930
5931       // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
5932       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
5933           N1.getOperand(0) == N1.getOperand(1) &&
5934           N0.getOperand(1) == N1.getOperand(0)) {
5935         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5936                                      SDValue(CFP00, 0),
5937                                      DAG.getConstantFP(2.0, VT));
5938         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5939                            N0.getOperand(1), NewCFP);
5940       }
5941
5942       // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
5943       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
5944           N1.getOperand(0) == N1.getOperand(1) &&
5945           N0.getOperand(0) == N1.getOperand(0)) {
5946         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5947                                      SDValue(CFP01, 0),
5948                                      DAG.getConstantFP(2.0, VT));
5949         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5950                            N0.getOperand(0), NewCFP);
5951       }
5952     }
5953
5954     if (N1.getOpcode() == ISD::FMUL) {
5955       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
5956       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
5957
5958       // (fadd x, (fmul c, x)) -> (fmul c+1, x)
5959       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
5960         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5961                                      SDValue(CFP10, 0),
5962                                      DAG.getConstantFP(1.0, VT));
5963         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5964                            N0, NewCFP);
5965       }
5966
5967       // (fadd x, (fmul x, c)) -> (fmul c+1, x)
5968       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
5969         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5970                                      SDValue(CFP11, 0),
5971                                      DAG.getConstantFP(1.0, VT));
5972         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5973                            N0, NewCFP);
5974       }
5975
5976
5977       // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
5978       if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
5979           N1.getOperand(0) == N1.getOperand(1) &&
5980           N0.getOperand(1) == N1.getOperand(0)) {
5981         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5982                                      SDValue(CFP10, 0),
5983                                      DAG.getConstantFP(2.0, VT));
5984         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5985                            N0.getOperand(1), NewCFP);
5986       }
5987
5988       // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
5989       if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
5990           N1.getOperand(0) == N1.getOperand(1) &&
5991           N0.getOperand(0) == N1.getOperand(0)) {
5992         SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
5993                                      SDValue(CFP11, 0),
5994                                      DAG.getConstantFP(2.0, VT));
5995         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5996                            N0.getOperand(0), NewCFP);
5997       }
5998     }
5999
6000     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6001       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6002       // (fadd (fadd x, x), x) -> (fmul 3.0, x)
6003       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6004           (N0.getOperand(0) == N1)) {
6005         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6006                            N1, DAG.getConstantFP(3.0, VT));
6007       }
6008     }
6009
6010     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6011       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6012       // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
6013       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6014           N1.getOperand(0) == N0) {
6015         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6016                            N0, DAG.getConstantFP(3.0, VT));
6017       }
6018     }
6019
6020     // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
6021     if (AllowNewFpConst &&
6022         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6023         N0.getOperand(0) == N0.getOperand(1) &&
6024         N1.getOperand(0) == N1.getOperand(1) &&
6025         N0.getOperand(0) == N1.getOperand(0)) {
6026       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6027                          N0.getOperand(0),
6028                          DAG.getConstantFP(4.0, VT));
6029     }
6030   }
6031
6032   // FADD -> FMA combines:
6033   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6034        DAG.getTarget().Options.UnsafeFPMath) &&
6035       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6036       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6037
6038     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6039     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6040       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
6041                          N0.getOperand(0), N0.getOperand(1), N1);
6042     }
6043
6044     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6045     // Note: Commutes FADD operands.
6046     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6047       return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
6048                          N1.getOperand(0), N1.getOperand(1), N0);
6049     }
6050   }
6051
6052   return SDValue();
6053 }
6054
6055 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6056   SDValue N0 = N->getOperand(0);
6057   SDValue N1 = N->getOperand(1);
6058   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6059   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6060   EVT VT = N->getValueType(0);
6061   DebugLoc dl = N->getDebugLoc();
6062
6063   // fold vector ops
6064   if (VT.isVector()) {
6065     SDValue FoldedVOp = SimplifyVBinOp(N);
6066     if (FoldedVOp.getNode()) return FoldedVOp;
6067   }
6068
6069   // fold (fsub c1, c2) -> c1-c2
6070   if (N0CFP && N1CFP)
6071     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
6072   // fold (fsub A, 0) -> A
6073   if (DAG.getTarget().Options.UnsafeFPMath &&
6074       N1CFP && N1CFP->getValueAPF().isZero())
6075     return N0;
6076   // fold (fsub 0, B) -> -B
6077   if (DAG.getTarget().Options.UnsafeFPMath &&
6078       N0CFP && N0CFP->getValueAPF().isZero()) {
6079     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6080       return GetNegatedExpression(N1, DAG, LegalOperations);
6081     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6082       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6083   }
6084   // fold (fsub A, (fneg B)) -> (fadd A, B)
6085   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6086     return DAG.getNode(ISD::FADD, dl, VT, N0,
6087                        GetNegatedExpression(N1, DAG, LegalOperations));
6088
6089   // If 'unsafe math' is enabled, fold
6090   //    (fsub x, x) -> 0.0 &
6091   //    (fsub x, (fadd x, y)) -> (fneg y) &
6092   //    (fsub x, (fadd y, x)) -> (fneg y)
6093   if (DAG.getTarget().Options.UnsafeFPMath) {
6094     if (N0 == N1)
6095       return DAG.getConstantFP(0.0f, VT);
6096
6097     if (N1.getOpcode() == ISD::FADD) {
6098       SDValue N10 = N1->getOperand(0);
6099       SDValue N11 = N1->getOperand(1);
6100
6101       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6102                                           &DAG.getTarget().Options))
6103         return GetNegatedExpression(N11, DAG, LegalOperations);
6104       else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6105                                                &DAG.getTarget().Options))
6106         return GetNegatedExpression(N10, DAG, LegalOperations);
6107     }
6108   }
6109
6110   // FSUB -> FMA combines:
6111   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6112        DAG.getTarget().Options.UnsafeFPMath) &&
6113       DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
6114       TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
6115
6116     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6117     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
6118       return DAG.getNode(ISD::FMA, dl, VT,
6119                          N0.getOperand(0), N0.getOperand(1),
6120                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6121     }
6122
6123     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6124     // Note: Commutes FSUB operands.
6125     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
6126       return DAG.getNode(ISD::FMA, dl, VT,
6127                          DAG.getNode(ISD::FNEG, dl, VT,
6128                          N1.getOperand(0)),
6129                          N1.getOperand(1), N0);
6130     }
6131
6132     // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6133     if (N0.getOpcode() == ISD::FNEG && 
6134         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6135         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6136       SDValue N00 = N0.getOperand(0).getOperand(0);
6137       SDValue N01 = N0.getOperand(0).getOperand(1);
6138       return DAG.getNode(ISD::FMA, dl, VT,
6139                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6140                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6141     }
6142   }
6143
6144   return SDValue();
6145 }
6146
6147 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6148   SDValue N0 = N->getOperand(0);
6149   SDValue N1 = N->getOperand(1);
6150   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6151   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6152   EVT VT = N->getValueType(0);
6153   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6154
6155   // fold vector ops
6156   if (VT.isVector()) {
6157     SDValue FoldedVOp = SimplifyVBinOp(N);
6158     if (FoldedVOp.getNode()) return FoldedVOp;
6159   }
6160
6161   // fold (fmul c1, c2) -> c1*c2
6162   if (N0CFP && N1CFP)
6163     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
6164   // canonicalize constant to RHS
6165   if (N0CFP && !N1CFP)
6166     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
6167   // fold (fmul A, 0) -> 0
6168   if (DAG.getTarget().Options.UnsafeFPMath &&
6169       N1CFP && N1CFP->getValueAPF().isZero())
6170     return N1;
6171   // fold (fmul A, 0) -> 0, vector edition.
6172   if (DAG.getTarget().Options.UnsafeFPMath &&
6173       ISD::isBuildVectorAllZeros(N1.getNode()))
6174     return N1;
6175   // fold (fmul A, 1.0) -> A
6176   if (N1CFP && N1CFP->isExactlyValue(1.0))
6177     return N0;
6178   // fold (fmul X, 2.0) -> (fadd X, X)
6179   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6180     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
6181   // fold (fmul X, -1.0) -> (fneg X)
6182   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6183     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6184       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
6185
6186   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6187   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6188                                        &DAG.getTarget().Options)) {
6189     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, 
6190                                          &DAG.getTarget().Options)) {
6191       // Both can be negated for free, check to see if at least one is cheaper
6192       // negated.
6193       if (LHSNeg == 2 || RHSNeg == 2)
6194         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6195                            GetNegatedExpression(N0, DAG, LegalOperations),
6196                            GetNegatedExpression(N1, DAG, LegalOperations));
6197     }
6198   }
6199
6200   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6201   if (DAG.getTarget().Options.UnsafeFPMath &&
6202       N1CFP && N0.getOpcode() == ISD::FMUL &&
6203       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6204     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
6205                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6206                                    N0.getOperand(1), N1));
6207
6208   return SDValue();
6209 }
6210
6211 SDValue DAGCombiner::visitFMA(SDNode *N) {
6212   SDValue N0 = N->getOperand(0);
6213   SDValue N1 = N->getOperand(1);
6214   SDValue N2 = N->getOperand(2);
6215   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6216   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6217   EVT VT = N->getValueType(0);
6218   DebugLoc dl = N->getDebugLoc();
6219
6220   if (DAG.getTarget().Options.UnsafeFPMath) {
6221     if (N0CFP && N0CFP->isZero())
6222       return N2;
6223     if (N1CFP && N1CFP->isZero())
6224       return N2;
6225   }
6226   if (N0CFP && N0CFP->isExactlyValue(1.0))
6227     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
6228   if (N1CFP && N1CFP->isExactlyValue(1.0))
6229     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
6230
6231   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6232   if (N0CFP && !N1CFP)
6233     return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
6234
6235   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6236   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6237       N2.getOpcode() == ISD::FMUL &&
6238       N0 == N2.getOperand(0) &&
6239       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6240     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6241                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6242   }
6243
6244
6245   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6246   if (DAG.getTarget().Options.UnsafeFPMath &&
6247       N0.getOpcode() == ISD::FMUL && N1CFP &&
6248       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6249     return DAG.getNode(ISD::FMA, dl, VT,
6250                        N0.getOperand(0),
6251                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6252                        N2);
6253   }
6254
6255   // (fma x, 1, y) -> (fadd x, y)
6256   // (fma x, -1, y) -> (fadd (fneg x), y)
6257   if (N1CFP) {
6258     if (N1CFP->isExactlyValue(1.0))
6259       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6260
6261     if (N1CFP->isExactlyValue(-1.0) &&
6262         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6263       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6264       AddToWorkList(RHSNeg.getNode());
6265       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6266     }
6267   }
6268
6269   // (fma x, c, x) -> (fmul x, (c+1))
6270   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
6271     return DAG.getNode(ISD::FMUL, dl, VT,
6272                        N0,
6273                        DAG.getNode(ISD::FADD, dl, VT,
6274                                    N1, DAG.getConstantFP(1.0, VT)));
6275   }
6276
6277   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6278   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6279       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
6280     return DAG.getNode(ISD::FMUL, dl, VT,
6281                        N0,
6282                        DAG.getNode(ISD::FADD, dl, VT,
6283                                    N1, DAG.getConstantFP(-1.0, VT)));
6284   }
6285
6286
6287   return SDValue();
6288 }
6289
6290 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6291   SDValue N0 = N->getOperand(0);
6292   SDValue N1 = N->getOperand(1);
6293   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6294   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6295   EVT VT = N->getValueType(0);
6296   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6297
6298   // fold vector ops
6299   if (VT.isVector()) {
6300     SDValue FoldedVOp = SimplifyVBinOp(N);
6301     if (FoldedVOp.getNode()) return FoldedVOp;
6302   }
6303
6304   // fold (fdiv c1, c2) -> c1/c2
6305   if (N0CFP && N1CFP)
6306     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
6307
6308   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6309   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6310     // Compute the reciprocal 1.0 / c2.
6311     APFloat N1APF = N1CFP->getValueAPF();
6312     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6313     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6314     // Only do the transform if the reciprocal is a legal fp immediate that
6315     // isn't too nasty (eg NaN, denormal, ...).
6316     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6317         (!LegalOperations ||
6318          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6319          // backend)... we should handle this gracefully after Legalize.
6320          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6321          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6322          TLI.isFPImmLegal(Recip, VT)))
6323       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
6324                          DAG.getConstantFP(Recip, VT));
6325   }
6326
6327   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6328   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6329                                        &DAG.getTarget().Options)) {
6330     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6331                                          &DAG.getTarget().Options)) {
6332       // Both can be negated for free, check to see if at least one is cheaper
6333       // negated.
6334       if (LHSNeg == 2 || RHSNeg == 2)
6335         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
6336                            GetNegatedExpression(N0, DAG, LegalOperations),
6337                            GetNegatedExpression(N1, DAG, LegalOperations));
6338     }
6339   }
6340
6341   return SDValue();
6342 }
6343
6344 SDValue DAGCombiner::visitFREM(SDNode *N) {
6345   SDValue N0 = N->getOperand(0);
6346   SDValue N1 = N->getOperand(1);
6347   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6348   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6349   EVT VT = N->getValueType(0);
6350
6351   // fold (frem c1, c2) -> fmod(c1,c2)
6352   if (N0CFP && N1CFP)
6353     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
6354
6355   return SDValue();
6356 }
6357
6358 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6359   SDValue N0 = N->getOperand(0);
6360   SDValue N1 = N->getOperand(1);
6361   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6362   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6363   EVT VT = N->getValueType(0);
6364
6365   if (N0CFP && N1CFP)  // Constant fold
6366     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
6367
6368   if (N1CFP) {
6369     const APFloat& V = N1CFP->getValueAPF();
6370     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6371     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6372     if (!V.isNegative()) {
6373       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6374         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6375     } else {
6376       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6377         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6378                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
6379     }
6380   }
6381
6382   // copysign(fabs(x), y) -> copysign(x, y)
6383   // copysign(fneg(x), y) -> copysign(x, y)
6384   // copysign(copysign(x,z), y) -> copysign(x, y)
6385   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6386       N0.getOpcode() == ISD::FCOPYSIGN)
6387     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6388                        N0.getOperand(0), N1);
6389
6390   // copysign(x, abs(y)) -> abs(x)
6391   if (N1.getOpcode() == ISD::FABS)
6392     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6393
6394   // copysign(x, copysign(y,z)) -> copysign(x, z)
6395   if (N1.getOpcode() == ISD::FCOPYSIGN)
6396     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6397                        N0, N1.getOperand(1));
6398
6399   // copysign(x, fp_extend(y)) -> copysign(x, y)
6400   // copysign(x, fp_round(y)) -> copysign(x, y)
6401   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6402     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6403                        N0, N1.getOperand(0));
6404
6405   return SDValue();
6406 }
6407
6408 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6409   SDValue N0 = N->getOperand(0);
6410   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6411   EVT VT = N->getValueType(0);
6412   EVT OpVT = N0.getValueType();
6413
6414   // fold (sint_to_fp c1) -> c1fp
6415   if (N0C &&
6416       // ...but only if the target supports immediate floating-point values
6417       (!LegalOperations ||
6418        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6419     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6420
6421   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6422   // but UINT_TO_FP is legal on this target, try to convert.
6423   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6424       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6425     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6426     if (DAG.SignBitIsZero(N0))
6427       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6428   }
6429
6430   // The next optimizations are desireable only if SELECT_CC can be lowered.
6431   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6432   // having to say they don't support SELECT_CC on every type the DAG knows
6433   // about, since there is no way to mark an opcode illegal at all value types
6434   // (See also visitSELECT)
6435   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6436     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6437     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6438         !VT.isVector() &&
6439         (!LegalOperations ||
6440          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6441       SDValue Ops[] =
6442         { N0.getOperand(0), N0.getOperand(1),
6443           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6444           N0.getOperand(2) };
6445       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6446     }
6447
6448     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6449     //      (select_cc x, y, 1.0, 0.0,, cc)
6450     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6451         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6452         (!LegalOperations ||
6453          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6454       SDValue Ops[] =
6455         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6456           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6457           N0.getOperand(0).getOperand(2) };
6458       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6459     }
6460   }
6461
6462   return SDValue();
6463 }
6464
6465 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6466   SDValue N0 = N->getOperand(0);
6467   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6468   EVT VT = N->getValueType(0);
6469   EVT OpVT = N0.getValueType();
6470
6471   // fold (uint_to_fp c1) -> c1fp
6472   if (N0C &&
6473       // ...but only if the target supports immediate floating-point values
6474       (!LegalOperations ||
6475        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6476     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
6477
6478   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6479   // but SINT_TO_FP is legal on this target, try to convert.
6480   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6481       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6482     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6483     if (DAG.SignBitIsZero(N0))
6484       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
6485   }
6486
6487   // The next optimizations are desireable only if SELECT_CC can be lowered.
6488   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6489   // having to say they don't support SELECT_CC on every type the DAG knows
6490   // about, since there is no way to mark an opcode illegal at all value types
6491   // (See also visitSELECT)
6492   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6493     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6494
6495     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6496         (!LegalOperations ||
6497          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6498       SDValue Ops[] =
6499         { N0.getOperand(0), N0.getOperand(1),
6500           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6501           N0.getOperand(2) };
6502       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
6503     }
6504   }
6505
6506   return SDValue();
6507 }
6508
6509 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6510   SDValue N0 = N->getOperand(0);
6511   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6512   EVT VT = N->getValueType(0);
6513
6514   // fold (fp_to_sint c1fp) -> c1
6515   if (N0CFP)
6516     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
6517
6518   return SDValue();
6519 }
6520
6521 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6522   SDValue N0 = N->getOperand(0);
6523   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6524   EVT VT = N->getValueType(0);
6525
6526   // fold (fp_to_uint c1fp) -> c1
6527   if (N0CFP)
6528     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
6529
6530   return SDValue();
6531 }
6532
6533 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6534   SDValue N0 = N->getOperand(0);
6535   SDValue N1 = N->getOperand(1);
6536   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6537   EVT VT = N->getValueType(0);
6538
6539   // fold (fp_round c1fp) -> c1fp
6540   if (N0CFP)
6541     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
6542
6543   // fold (fp_round (fp_extend x)) -> x
6544   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6545     return N0.getOperand(0);
6546
6547   // fold (fp_round (fp_round x)) -> (fp_round x)
6548   if (N0.getOpcode() == ISD::FP_ROUND) {
6549     // This is a value preserving truncation if both round's are.
6550     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6551                    N0.getNode()->getConstantOperandVal(1) == 1;
6552     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
6553                        DAG.getIntPtrConstant(IsTrunc));
6554   }
6555
6556   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6557   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6558     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
6559                               N0.getOperand(0), N1);
6560     AddToWorkList(Tmp.getNode());
6561     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
6562                        Tmp, N0.getOperand(1));
6563   }
6564
6565   return SDValue();
6566 }
6567
6568 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6569   SDValue N0 = N->getOperand(0);
6570   EVT VT = N->getValueType(0);
6571   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6572   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6573
6574   // fold (fp_round_inreg c1fp) -> c1fp
6575   if (N0CFP && isTypeLegal(EVT)) {
6576     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6577     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
6578   }
6579
6580   return SDValue();
6581 }
6582
6583 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6584   SDValue N0 = N->getOperand(0);
6585   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6586   EVT VT = N->getValueType(0);
6587
6588   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6589   if (N->hasOneUse() &&
6590       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6591     return SDValue();
6592
6593   // fold (fp_extend c1fp) -> c1fp
6594   if (N0CFP)
6595     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
6596
6597   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6598   // value of X.
6599   if (N0.getOpcode() == ISD::FP_ROUND
6600       && N0.getNode()->getConstantOperandVal(1) == 1) {
6601     SDValue In = N0.getOperand(0);
6602     if (In.getValueType() == VT) return In;
6603     if (VT.bitsLT(In.getValueType()))
6604       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
6605                          In, N0.getOperand(1));
6606     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
6607   }
6608
6609   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6610   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6611       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6612        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6613     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6614     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
6615                                      LN0->getChain(),
6616                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6617                                      N0.getValueType(),
6618                                      LN0->isVolatile(), LN0->isNonTemporal(),
6619                                      LN0->getAlignment());
6620     CombineTo(N, ExtLoad);
6621     CombineTo(N0.getNode(),
6622               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
6623                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6624               ExtLoad.getValue(1));
6625     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6626   }
6627
6628   return SDValue();
6629 }
6630
6631 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6632   SDValue N0 = N->getOperand(0);
6633   EVT VT = N->getValueType(0);
6634
6635   if (VT.isVector()) {
6636     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6637     if (FoldedVOp.getNode()) return FoldedVOp;
6638   }
6639
6640   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6641                          &DAG.getTarget().Options))
6642     return GetNegatedExpression(N0, DAG, LegalOperations);
6643
6644   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6645   // constant pool values.
6646   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6647       !VT.isVector() &&
6648       N0.getNode()->hasOneUse() &&
6649       N0.getOperand(0).getValueType().isInteger()) {
6650     SDValue Int = N0.getOperand(0);
6651     EVT IntVT = Int.getValueType();
6652     if (IntVT.isInteger() && !IntVT.isVector()) {
6653       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
6654               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6655       AddToWorkList(Int.getNode());
6656       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6657                          VT, Int);
6658     }
6659   }
6660
6661   // (fneg (fmul c, x)) -> (fmul -c, x)
6662   if (N0.getOpcode() == ISD::FMUL) {
6663     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6664     if (CFP1) {
6665       return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
6666                          N0.getOperand(0),
6667                          DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
6668                                      N0.getOperand(1)));
6669     }
6670   }
6671
6672   return SDValue();
6673 }
6674
6675 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6676   SDValue N0 = N->getOperand(0);
6677   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6678   EVT VT = N->getValueType(0);
6679
6680   // fold (fceil c1) -> fceil(c1)
6681   if (N0CFP)
6682     return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
6683
6684   return SDValue();
6685 }
6686
6687 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6688   SDValue N0 = N->getOperand(0);
6689   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6690   EVT VT = N->getValueType(0);
6691
6692   // fold (ftrunc c1) -> ftrunc(c1)
6693   if (N0CFP)
6694     return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
6695
6696   return SDValue();
6697 }
6698
6699 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6700   SDValue N0 = N->getOperand(0);
6701   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6702   EVT VT = N->getValueType(0);
6703
6704   // fold (ffloor c1) -> ffloor(c1)
6705   if (N0CFP)
6706     return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
6707
6708   return SDValue();
6709 }
6710
6711 SDValue DAGCombiner::visitFABS(SDNode *N) {
6712   SDValue N0 = N->getOperand(0);
6713   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6714   EVT VT = N->getValueType(0);
6715
6716   if (VT.isVector()) {
6717     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6718     if (FoldedVOp.getNode()) return FoldedVOp;
6719   }
6720
6721   // fold (fabs c1) -> fabs(c1)
6722   if (N0CFP)
6723     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
6724   // fold (fabs (fabs x)) -> (fabs x)
6725   if (N0.getOpcode() == ISD::FABS)
6726     return N->getOperand(0);
6727   // fold (fabs (fneg x)) -> (fabs x)
6728   // fold (fabs (fcopysign x, y)) -> (fabs x)
6729   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6730     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
6731
6732   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6733   // constant pool values.
6734   if (!TLI.isFAbsFree(VT) && 
6735       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6736       N0.getOperand(0).getValueType().isInteger() &&
6737       !N0.getOperand(0).getValueType().isVector()) {
6738     SDValue Int = N0.getOperand(0);
6739     EVT IntVT = Int.getValueType();
6740     if (IntVT.isInteger() && !IntVT.isVector()) {
6741       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
6742              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6743       AddToWorkList(Int.getNode());
6744       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
6745                          N->getValueType(0), Int);
6746     }
6747   }
6748
6749   return SDValue();
6750 }
6751
6752 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6753   SDValue Chain = N->getOperand(0);
6754   SDValue N1 = N->getOperand(1);
6755   SDValue N2 = N->getOperand(2);
6756
6757   // If N is a constant we could fold this into a fallthrough or unconditional
6758   // branch. However that doesn't happen very often in normal code, because
6759   // Instcombine/SimplifyCFG should have handled the available opportunities.
6760   // If we did this folding here, it would be necessary to update the
6761   // MachineBasicBlock CFG, which is awkward.
6762
6763   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6764   // on the target.
6765   if (N1.getOpcode() == ISD::SETCC &&
6766       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6767                                    N1.getOperand(0).getValueType())) {
6768     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6769                        Chain, N1.getOperand(2),
6770                        N1.getOperand(0), N1.getOperand(1), N2);
6771   }
6772
6773   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6774       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6775        (N1.getOperand(0).hasOneUse() &&
6776         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6777     SDNode *Trunc = 0;
6778     if (N1.getOpcode() == ISD::TRUNCATE) {
6779       // Look pass the truncate.
6780       Trunc = N1.getNode();
6781       N1 = N1.getOperand(0);
6782     }
6783
6784     // Match this pattern so that we can generate simpler code:
6785     //
6786     //   %a = ...
6787     //   %b = and i32 %a, 2
6788     //   %c = srl i32 %b, 1
6789     //   brcond i32 %c ...
6790     //
6791     // into
6792     //
6793     //   %a = ...
6794     //   %b = and i32 %a, 2
6795     //   %c = setcc eq %b, 0
6796     //   brcond %c ...
6797     //
6798     // This applies only when the AND constant value has one bit set and the
6799     // SRL constant is equal to the log2 of the AND constant. The back-end is
6800     // smart enough to convert the result into a TEST/JMP sequence.
6801     SDValue Op0 = N1.getOperand(0);
6802     SDValue Op1 = N1.getOperand(1);
6803
6804     if (Op0.getOpcode() == ISD::AND &&
6805         Op1.getOpcode() == ISD::Constant) {
6806       SDValue AndOp1 = Op0.getOperand(1);
6807
6808       if (AndOp1.getOpcode() == ISD::Constant) {
6809         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6810
6811         if (AndConst.isPowerOf2() &&
6812             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6813           SDValue SetCC =
6814             DAG.getSetCC(N->getDebugLoc(),
6815                          TLI.getSetCCResultType(Op0.getValueType()),
6816                          Op0, DAG.getConstant(0, Op0.getValueType()),
6817                          ISD::SETNE);
6818
6819           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6820                                           MVT::Other, Chain, SetCC, N2);
6821           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6822           // will convert it back to (X & C1) >> C2.
6823           CombineTo(N, NewBRCond, false);
6824           // Truncate is dead.
6825           if (Trunc) {
6826             removeFromWorkList(Trunc);
6827             DAG.DeleteNode(Trunc);
6828           }
6829           // Replace the uses of SRL with SETCC
6830           WorkListRemover DeadNodes(*this);
6831           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6832           removeFromWorkList(N1.getNode());
6833           DAG.DeleteNode(N1.getNode());
6834           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6835         }
6836       }
6837     }
6838
6839     if (Trunc)
6840       // Restore N1 if the above transformation doesn't match.
6841       N1 = N->getOperand(1);
6842   }
6843
6844   // Transform br(xor(x, y)) -> br(x != y)
6845   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6846   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6847     SDNode *TheXor = N1.getNode();
6848     SDValue Op0 = TheXor->getOperand(0);
6849     SDValue Op1 = TheXor->getOperand(1);
6850     if (Op0.getOpcode() == Op1.getOpcode()) {
6851       // Avoid missing important xor optimizations.
6852       SDValue Tmp = visitXOR(TheXor);
6853       if (Tmp.getNode()) {
6854         if (Tmp.getNode() != TheXor) {
6855           DEBUG(dbgs() << "\nReplacing.8 ";
6856                 TheXor->dump(&DAG);
6857                 dbgs() << "\nWith: ";
6858                 Tmp.getNode()->dump(&DAG);
6859                 dbgs() << '\n');
6860           WorkListRemover DeadNodes(*this);
6861           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6862           removeFromWorkList(TheXor);
6863           DAG.DeleteNode(TheXor);
6864           return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6865                              MVT::Other, Chain, Tmp, N2);
6866         }
6867
6868         // visitXOR has changed XOR's operands or replaced the XOR completely,
6869         // bail out.
6870         return SDValue(N, 0);
6871       }
6872     }
6873
6874     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6875       bool Equal = false;
6876       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6877         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6878             Op0.getOpcode() == ISD::XOR) {
6879           TheXor = Op0.getNode();
6880           Equal = true;
6881         }
6882
6883       EVT SetCCVT = N1.getValueType();
6884       if (LegalTypes)
6885         SetCCVT = TLI.getSetCCResultType(SetCCVT);
6886       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
6887                                    SetCCVT,
6888                                    Op0, Op1,
6889                                    Equal ? ISD::SETEQ : ISD::SETNE);
6890       // Replace the uses of XOR with SETCC
6891       WorkListRemover DeadNodes(*this);
6892       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6893       removeFromWorkList(N1.getNode());
6894       DAG.DeleteNode(N1.getNode());
6895       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
6896                          MVT::Other, Chain, SetCC, N2);
6897     }
6898   }
6899
6900   return SDValue();
6901 }
6902
6903 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
6904 //
6905 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
6906   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
6907   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
6908
6909   // If N is a constant we could fold this into a fallthrough or unconditional
6910   // branch. However that doesn't happen very often in normal code, because
6911   // Instcombine/SimplifyCFG should have handled the available opportunities.
6912   // If we did this folding here, it would be necessary to update the
6913   // MachineBasicBlock CFG, which is awkward.
6914
6915   // Use SimplifySetCC to simplify SETCC's.
6916   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
6917                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
6918                                false);
6919   if (Simp.getNode()) AddToWorkList(Simp.getNode());
6920
6921   // fold to a simpler setcc
6922   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
6923     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
6924                        N->getOperand(0), Simp.getOperand(2),
6925                        Simp.getOperand(0), Simp.getOperand(1),
6926                        N->getOperand(4));
6927
6928   return SDValue();
6929 }
6930
6931 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
6932 /// uses N as its base pointer and that N may be folded in the load / store
6933 /// addressing mode.
6934 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
6935                                     SelectionDAG &DAG,
6936                                     const TargetLowering &TLI) {
6937   EVT VT;
6938   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
6939     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
6940       return false;
6941     VT = Use->getValueType(0);
6942   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
6943     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
6944       return false;
6945     VT = ST->getValue().getValueType();
6946   } else
6947     return false;
6948
6949   TargetLowering::AddrMode AM;
6950   if (N->getOpcode() == ISD::ADD) {
6951     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6952     if (Offset)
6953       // [reg +/- imm]
6954       AM.BaseOffs = Offset->getSExtValue();
6955     else
6956       // [reg +/- reg]
6957       AM.Scale = 1;
6958   } else if (N->getOpcode() == ISD::SUB) {
6959     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
6960     if (Offset)
6961       // [reg +/- imm]
6962       AM.BaseOffs = -Offset->getSExtValue();
6963     else
6964       // [reg +/- reg]
6965       AM.Scale = 1;
6966   } else
6967     return false;
6968
6969   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
6970 }
6971
6972 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
6973 /// pre-indexed load / store when the base pointer is an add or subtract
6974 /// and it has other uses besides the load / store. After the
6975 /// transformation, the new indexed load / store has effectively folded
6976 /// the add / subtract in and all of its other uses are redirected to the
6977 /// new load / store.
6978 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
6979   if (Level < AfterLegalizeDAG)
6980     return false;
6981
6982   bool isLoad = true;
6983   SDValue Ptr;
6984   EVT VT;
6985   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
6986     if (LD->isIndexed())
6987       return false;
6988     VT = LD->getMemoryVT();
6989     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
6990         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
6991       return false;
6992     Ptr = LD->getBasePtr();
6993   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
6994     if (ST->isIndexed())
6995       return false;
6996     VT = ST->getMemoryVT();
6997     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
6998         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
6999       return false;
7000     Ptr = ST->getBasePtr();
7001     isLoad = false;
7002   } else {
7003     return false;
7004   }
7005
7006   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7007   // out.  There is no reason to make this a preinc/predec.
7008   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7009       Ptr.getNode()->hasOneUse())
7010     return false;
7011
7012   // Ask the target to do addressing mode selection.
7013   SDValue BasePtr;
7014   SDValue Offset;
7015   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7016   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7017     return false;
7018
7019   // Backends without true r+i pre-indexed forms may need to pass a
7020   // constant base with a variable offset so that constant coercion
7021   // will work with the patterns in canonical form.
7022   bool Swapped = false;
7023   if (isa<ConstantSDNode>(BasePtr)) {
7024     std::swap(BasePtr, Offset);
7025     Swapped = true;
7026   }
7027
7028   // Don't create a indexed load / store with zero offset.
7029   if (isa<ConstantSDNode>(Offset) &&
7030       cast<ConstantSDNode>(Offset)->isNullValue())
7031     return false;
7032
7033   // Try turning it into a pre-indexed load / store except when:
7034   // 1) The new base ptr is a frame index.
7035   // 2) If N is a store and the new base ptr is either the same as or is a
7036   //    predecessor of the value being stored.
7037   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7038   //    that would create a cycle.
7039   // 4) All uses are load / store ops that use it as old base ptr.
7040
7041   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7042   // (plus the implicit offset) to a register to preinc anyway.
7043   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7044     return false;
7045
7046   // Check #2.
7047   if (!isLoad) {
7048     SDValue Val = cast<StoreSDNode>(N)->getValue();
7049     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7050       return false;
7051   }
7052
7053   // If the offset is a constant, there may be other adds of constants that
7054   // can be folded with this one. We should do this to avoid having to keep
7055   // a copy of the original base pointer.
7056   SmallVector<SDNode *, 16> OtherUses;
7057   if (isa<ConstantSDNode>(Offset))
7058     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7059          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7060       SDNode *Use = *I;
7061       if (Use == Ptr.getNode())
7062         continue;
7063
7064       if (Use->isPredecessorOf(N))
7065         continue;
7066
7067       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7068         OtherUses.clear();
7069         break;
7070       }
7071
7072       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7073       if (Op1.getNode() == BasePtr.getNode())
7074         std::swap(Op0, Op1);
7075       assert(Op0.getNode() == BasePtr.getNode() &&
7076              "Use of ADD/SUB but not an operand");
7077
7078       if (!isa<ConstantSDNode>(Op1)) {
7079         OtherUses.clear();
7080         break;
7081       }
7082
7083       // FIXME: In some cases, we can be smarter about this.
7084       if (Op1.getValueType() != Offset.getValueType()) {
7085         OtherUses.clear();
7086         break;
7087       }
7088
7089       OtherUses.push_back(Use);
7090     }
7091
7092   if (Swapped)
7093     std::swap(BasePtr, Offset);
7094
7095   // Now check for #3 and #4.
7096   bool RealUse = false;
7097
7098   // Caches for hasPredecessorHelper
7099   SmallPtrSet<const SDNode *, 32> Visited;
7100   SmallVector<const SDNode *, 16> Worklist;
7101
7102   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7103          E = Ptr.getNode()->use_end(); I != E; ++I) {
7104     SDNode *Use = *I;
7105     if (Use == N)
7106       continue;
7107     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7108       return false;
7109
7110     // If Ptr may be folded in addressing mode of other use, then it's
7111     // not profitable to do this transformation.
7112     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7113       RealUse = true;
7114   }
7115
7116   if (!RealUse)
7117     return false;
7118
7119   SDValue Result;
7120   if (isLoad)
7121     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7122                                 BasePtr, Offset, AM);
7123   else
7124     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7125                                  BasePtr, Offset, AM);
7126   ++PreIndexedNodes;
7127   ++NodesCombined;
7128   DEBUG(dbgs() << "\nReplacing.4 ";
7129         N->dump(&DAG);
7130         dbgs() << "\nWith: ";
7131         Result.getNode()->dump(&DAG);
7132         dbgs() << '\n');
7133   WorkListRemover DeadNodes(*this);
7134   if (isLoad) {
7135     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7136     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7137   } else {
7138     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7139   }
7140
7141   // Finally, since the node is now dead, remove it from the graph.
7142   DAG.DeleteNode(N);
7143
7144   if (Swapped)
7145     std::swap(BasePtr, Offset);
7146
7147   // Replace other uses of BasePtr that can be updated to use Ptr
7148   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7149     unsigned OffsetIdx = 1;
7150     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7151       OffsetIdx = 0;
7152     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7153            BasePtr.getNode() && "Expected BasePtr operand");
7154
7155     APInt OV =
7156       cast<ConstantSDNode>(Offset)->getAPIntValue();
7157     if (AM == ISD::PRE_DEC)
7158       OV = -OV;
7159
7160     ConstantSDNode *CN =
7161       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7162     APInt CNV = CN->getAPIntValue();
7163     if (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1)
7164       CNV += OV;
7165     else
7166       CNV -= OV;
7167
7168     SDValue NewOp1 = Result.getValue(isLoad ? 1 : 0);
7169     SDValue NewOp2 = DAG.getConstant(CNV, CN->getValueType(0));
7170     if (OffsetIdx == 0)
7171       std::swap(NewOp1, NewOp2);
7172
7173     SDValue NewUse = DAG.getNode(OtherUses[i]->getOpcode(),
7174                                  OtherUses[i]->getDebugLoc(),
7175                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7176     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7177     removeFromWorkList(OtherUses[i]);
7178     DAG.DeleteNode(OtherUses[i]);
7179   }
7180
7181   // Replace the uses of Ptr with uses of the updated base value.
7182   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7183   removeFromWorkList(Ptr.getNode());
7184   DAG.DeleteNode(Ptr.getNode());
7185
7186   return true;
7187 }
7188
7189 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7190 /// add / sub of the base pointer node into a post-indexed load / store.
7191 /// The transformation folded the add / subtract into the new indexed
7192 /// load / store effectively and all of its uses are redirected to the
7193 /// new load / store.
7194 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7195   if (Level < AfterLegalizeDAG)
7196     return false;
7197
7198   bool isLoad = true;
7199   SDValue Ptr;
7200   EVT VT;
7201   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7202     if (LD->isIndexed())
7203       return false;
7204     VT = LD->getMemoryVT();
7205     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7206         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7207       return false;
7208     Ptr = LD->getBasePtr();
7209   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7210     if (ST->isIndexed())
7211       return false;
7212     VT = ST->getMemoryVT();
7213     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7214         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7215       return false;
7216     Ptr = ST->getBasePtr();
7217     isLoad = false;
7218   } else {
7219     return false;
7220   }
7221
7222   if (Ptr.getNode()->hasOneUse())
7223     return false;
7224
7225   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7226          E = Ptr.getNode()->use_end(); I != E; ++I) {
7227     SDNode *Op = *I;
7228     if (Op == N ||
7229         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7230       continue;
7231
7232     SDValue BasePtr;
7233     SDValue Offset;
7234     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7235     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7236       // Don't create a indexed load / store with zero offset.
7237       if (isa<ConstantSDNode>(Offset) &&
7238           cast<ConstantSDNode>(Offset)->isNullValue())
7239         continue;
7240
7241       // Try turning it into a post-indexed load / store except when
7242       // 1) All uses are load / store ops that use it as base ptr (and
7243       //    it may be folded as addressing mmode).
7244       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7245       //    nor a successor of N. Otherwise, if Op is folded that would
7246       //    create a cycle.
7247
7248       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7249         continue;
7250
7251       // Check for #1.
7252       bool TryNext = false;
7253       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7254              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7255         SDNode *Use = *II;
7256         if (Use == Ptr.getNode())
7257           continue;
7258
7259         // If all the uses are load / store addresses, then don't do the
7260         // transformation.
7261         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7262           bool RealUse = false;
7263           for (SDNode::use_iterator III = Use->use_begin(),
7264                  EEE = Use->use_end(); III != EEE; ++III) {
7265             SDNode *UseUse = *III;
7266             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI)) 
7267               RealUse = true;
7268           }
7269
7270           if (!RealUse) {
7271             TryNext = true;
7272             break;
7273           }
7274         }
7275       }
7276
7277       if (TryNext)
7278         continue;
7279
7280       // Check for #2
7281       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7282         SDValue Result = isLoad
7283           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
7284                                BasePtr, Offset, AM)
7285           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
7286                                 BasePtr, Offset, AM);
7287         ++PostIndexedNodes;
7288         ++NodesCombined;
7289         DEBUG(dbgs() << "\nReplacing.5 ";
7290               N->dump(&DAG);
7291               dbgs() << "\nWith: ";
7292               Result.getNode()->dump(&DAG);
7293               dbgs() << '\n');
7294         WorkListRemover DeadNodes(*this);
7295         if (isLoad) {
7296           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7297           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7298         } else {
7299           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7300         }
7301
7302         // Finally, since the node is now dead, remove it from the graph.
7303         DAG.DeleteNode(N);
7304
7305         // Replace the uses of Use with uses of the updated base value.
7306         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7307                                       Result.getValue(isLoad ? 1 : 0));
7308         removeFromWorkList(Op);
7309         DAG.DeleteNode(Op);
7310         return true;
7311       }
7312     }
7313   }
7314
7315   return false;
7316 }
7317
7318 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7319   LoadSDNode *LD  = cast<LoadSDNode>(N);
7320   SDValue Chain = LD->getChain();
7321   SDValue Ptr   = LD->getBasePtr();
7322
7323   // If load is not volatile and there are no uses of the loaded value (and
7324   // the updated indexed value in case of indexed loads), change uses of the
7325   // chain value into uses of the chain input (i.e. delete the dead load).
7326   if (!LD->isVolatile()) {
7327     if (N->getValueType(1) == MVT::Other) {
7328       // Unindexed loads.
7329       if (!N->hasAnyUseOfValue(0)) {
7330         // It's not safe to use the two value CombineTo variant here. e.g.
7331         // v1, chain2 = load chain1, loc
7332         // v2, chain3 = load chain2, loc
7333         // v3         = add v2, c
7334         // Now we replace use of chain2 with chain1.  This makes the second load
7335         // isomorphic to the one we are deleting, and thus makes this load live.
7336         DEBUG(dbgs() << "\nReplacing.6 ";
7337               N->dump(&DAG);
7338               dbgs() << "\nWith chain: ";
7339               Chain.getNode()->dump(&DAG);
7340               dbgs() << "\n");
7341         WorkListRemover DeadNodes(*this);
7342         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7343
7344         if (N->use_empty()) {
7345           removeFromWorkList(N);
7346           DAG.DeleteNode(N);
7347         }
7348
7349         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7350       }
7351     } else {
7352       // Indexed loads.
7353       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7354       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7355         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7356         DEBUG(dbgs() << "\nReplacing.7 ";
7357               N->dump(&DAG);
7358               dbgs() << "\nWith: ";
7359               Undef.getNode()->dump(&DAG);
7360               dbgs() << " and 2 other values\n");
7361         WorkListRemover DeadNodes(*this);
7362         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7363         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7364                                       DAG.getUNDEF(N->getValueType(1)));
7365         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7366         removeFromWorkList(N);
7367         DAG.DeleteNode(N);
7368         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7369       }
7370     }
7371   }
7372
7373   // If this load is directly stored, replace the load value with the stored
7374   // value.
7375   // TODO: Handle store large -> read small portion.
7376   // TODO: Handle TRUNCSTORE/LOADEXT
7377   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7378     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7379       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7380       if (PrevST->getBasePtr() == Ptr &&
7381           PrevST->getValue().getValueType() == N->getValueType(0))
7382       return CombineTo(N, Chain.getOperand(1), Chain);
7383     }
7384   }
7385
7386   // Try to infer better alignment information than the load already has.
7387   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7388     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7389       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7390         SDValue NewLoad =
7391                DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
7392                               LD->getValueType(0),
7393                               Chain, Ptr, LD->getPointerInfo(),
7394                               LD->getMemoryVT(),
7395                               LD->isVolatile(), LD->isNonTemporal(), Align);
7396         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7397       }
7398     }
7399   }
7400
7401   if (CombinerAA) {
7402     // Walk up chain skipping non-aliasing memory nodes.
7403     SDValue BetterChain = FindBetterChain(N, Chain);
7404
7405     // If there is a better chain.
7406     if (Chain != BetterChain) {
7407       SDValue ReplLoad;
7408
7409       // Replace the chain to void dependency.
7410       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7411         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
7412                                BetterChain, Ptr, LD->getPointerInfo(),
7413                                LD->isVolatile(), LD->isNonTemporal(),
7414                                LD->isInvariant(), LD->getAlignment());
7415       } else {
7416         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
7417                                   LD->getValueType(0),
7418                                   BetterChain, Ptr, LD->getPointerInfo(),
7419                                   LD->getMemoryVT(),
7420                                   LD->isVolatile(),
7421                                   LD->isNonTemporal(),
7422                                   LD->getAlignment());
7423       }
7424
7425       // Create token factor to keep old chain connected.
7426       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
7427                                   MVT::Other, Chain, ReplLoad.getValue(1));
7428
7429       // Make sure the new and old chains are cleaned up.
7430       AddToWorkList(Token.getNode());
7431
7432       // Replace uses with load result and token factor. Don't add users
7433       // to work list.
7434       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7435     }
7436   }
7437
7438   // Try transforming N to an indexed load.
7439   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7440     return SDValue(N, 0);
7441
7442   return SDValue();
7443 }
7444
7445 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7446 /// load is having specific bytes cleared out.  If so, return the byte size
7447 /// being masked out and the shift amount.
7448 static std::pair<unsigned, unsigned>
7449 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7450   std::pair<unsigned, unsigned> Result(0, 0);
7451
7452   // Check for the structure we're looking for.
7453   if (V->getOpcode() != ISD::AND ||
7454       !isa<ConstantSDNode>(V->getOperand(1)) ||
7455       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7456     return Result;
7457
7458   // Check the chain and pointer.
7459   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7460   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7461
7462   // The store should be chained directly to the load or be an operand of a
7463   // tokenfactor.
7464   if (LD == Chain.getNode())
7465     ; // ok.
7466   else if (Chain->getOpcode() != ISD::TokenFactor)
7467     return Result; // Fail.
7468   else {
7469     bool isOk = false;
7470     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7471       if (Chain->getOperand(i).getNode() == LD) {
7472         isOk = true;
7473         break;
7474       }
7475     if (!isOk) return Result;
7476   }
7477
7478   // This only handles simple types.
7479   if (V.getValueType() != MVT::i16 &&
7480       V.getValueType() != MVT::i32 &&
7481       V.getValueType() != MVT::i64)
7482     return Result;
7483
7484   // Check the constant mask.  Invert it so that the bits being masked out are
7485   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7486   // follow the sign bit for uniformity.
7487   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7488   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
7489   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7490   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
7491   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7492   if (NotMaskLZ == 64) return Result;  // All zero mask.
7493
7494   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7495   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7496     return Result;
7497
7498   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7499   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7500     NotMaskLZ -= 64-V.getValueSizeInBits();
7501
7502   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7503   switch (MaskedBytes) {
7504   case 1:
7505   case 2:
7506   case 4: break;
7507   default: return Result; // All one mask, or 5-byte mask.
7508   }
7509
7510   // Verify that the first bit starts at a multiple of mask so that the access
7511   // is aligned the same as the access width.
7512   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7513
7514   Result.first = MaskedBytes;
7515   Result.second = NotMaskTZ/8;
7516   return Result;
7517 }
7518
7519
7520 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7521 /// provides a value as specified by MaskInfo.  If so, replace the specified
7522 /// store with a narrower store of truncated IVal.
7523 static SDNode *
7524 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7525                                 SDValue IVal, StoreSDNode *St,
7526                                 DAGCombiner *DC) {
7527   unsigned NumBytes = MaskInfo.first;
7528   unsigned ByteShift = MaskInfo.second;
7529   SelectionDAG &DAG = DC->getDAG();
7530
7531   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7532   // that uses this.  If not, this is not a replacement.
7533   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7534                                   ByteShift*8, (ByteShift+NumBytes)*8);
7535   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7536
7537   // Check that it is legal on the target to do this.  It is legal if the new
7538   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7539   // legalization.
7540   MVT VT = MVT::getIntegerVT(NumBytes*8);
7541   if (!DC->isTypeLegal(VT))
7542     return 0;
7543
7544   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7545   // shifted by ByteShift and truncated down to NumBytes.
7546   if (ByteShift)
7547     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
7548                        DAG.getConstant(ByteShift*8,
7549                                     DC->getShiftAmountTy(IVal.getValueType())));
7550
7551   // Figure out the offset for the store and the alignment of the access.
7552   unsigned StOffset;
7553   unsigned NewAlign = St->getAlignment();
7554
7555   if (DAG.getTargetLoweringInfo().isLittleEndian())
7556     StOffset = ByteShift;
7557   else
7558     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7559
7560   SDValue Ptr = St->getBasePtr();
7561   if (StOffset) {
7562     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
7563                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7564     NewAlign = MinAlign(NewAlign, StOffset);
7565   }
7566
7567   // Truncate down to the new size.
7568   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
7569
7570   ++OpsNarrowed;
7571   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
7572                       St->getPointerInfo().getWithOffset(StOffset),
7573                       false, false, NewAlign).getNode();
7574 }
7575
7576
7577 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7578 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7579 /// of the loaded bits, try narrowing the load and store if it would end up
7580 /// being a win for performance or code size.
7581 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7582   StoreSDNode *ST  = cast<StoreSDNode>(N);
7583   if (ST->isVolatile())
7584     return SDValue();
7585
7586   SDValue Chain = ST->getChain();
7587   SDValue Value = ST->getValue();
7588   SDValue Ptr   = ST->getBasePtr();
7589   EVT VT = Value.getValueType();
7590
7591   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7592     return SDValue();
7593
7594   unsigned Opc = Value.getOpcode();
7595
7596   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7597   // is a byte mask indicating a consecutive number of bytes, check to see if
7598   // Y is known to provide just those bytes.  If so, we try to replace the
7599   // load + replace + store sequence with a single (narrower) store, which makes
7600   // the load dead.
7601   if (Opc == ISD::OR) {
7602     std::pair<unsigned, unsigned> MaskedLoad;
7603     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7604     if (MaskedLoad.first)
7605       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7606                                                   Value.getOperand(1), ST,this))
7607         return SDValue(NewST, 0);
7608
7609     // Or is commutative, so try swapping X and Y.
7610     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7611     if (MaskedLoad.first)
7612       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7613                                                   Value.getOperand(0), ST,this))
7614         return SDValue(NewST, 0);
7615   }
7616
7617   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7618       Value.getOperand(1).getOpcode() != ISD::Constant)
7619     return SDValue();
7620
7621   SDValue N0 = Value.getOperand(0);
7622   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7623       Chain == SDValue(N0.getNode(), 1)) {
7624     LoadSDNode *LD = cast<LoadSDNode>(N0);
7625     if (LD->getBasePtr() != Ptr ||
7626         LD->getPointerInfo().getAddrSpace() !=
7627         ST->getPointerInfo().getAddrSpace())
7628       return SDValue();
7629
7630     // Find the type to narrow it the load / op / store to.
7631     SDValue N1 = Value.getOperand(1);
7632     unsigned BitWidth = N1.getValueSizeInBits();
7633     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7634     if (Opc == ISD::AND)
7635       Imm ^= APInt::getAllOnesValue(BitWidth);
7636     if (Imm == 0 || Imm.isAllOnesValue())
7637       return SDValue();
7638     unsigned ShAmt = Imm.countTrailingZeros();
7639     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7640     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7641     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7642     while (NewBW < BitWidth &&
7643            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7644              TLI.isNarrowingProfitable(VT, NewVT))) {
7645       NewBW = NextPowerOf2(NewBW);
7646       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7647     }
7648     if (NewBW >= BitWidth)
7649       return SDValue();
7650
7651     // If the lsb changed does not start at the type bitwidth boundary,
7652     // start at the previous one.
7653     if (ShAmt % NewBW)
7654       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7655     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7656                                    std::min(BitWidth, ShAmt + NewBW));
7657     if ((Imm & Mask) == Imm) {
7658       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7659       if (Opc == ISD::AND)
7660         NewImm ^= APInt::getAllOnesValue(NewBW);
7661       uint64_t PtrOff = ShAmt / 8;
7662       // For big endian targets, we need to adjust the offset to the pointer to
7663       // load the correct bytes.
7664       if (TLI.isBigEndian())
7665         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7666
7667       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7668       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7669       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7670         return SDValue();
7671
7672       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
7673                                    Ptr.getValueType(), Ptr,
7674                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7675       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
7676                                   LD->getChain(), NewPtr,
7677                                   LD->getPointerInfo().getWithOffset(PtrOff),
7678                                   LD->isVolatile(), LD->isNonTemporal(),
7679                                   LD->isInvariant(), NewAlign);
7680       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
7681                                    DAG.getConstant(NewImm, NewVT));
7682       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
7683                                    NewVal, NewPtr,
7684                                    ST->getPointerInfo().getWithOffset(PtrOff),
7685                                    false, false, NewAlign);
7686
7687       AddToWorkList(NewPtr.getNode());
7688       AddToWorkList(NewLD.getNode());
7689       AddToWorkList(NewVal.getNode());
7690       WorkListRemover DeadNodes(*this);
7691       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7692       ++OpsNarrowed;
7693       return NewST;
7694     }
7695   }
7696
7697   return SDValue();
7698 }
7699
7700 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7701 /// if the load value isn't used by any other operations, then consider
7702 /// transforming the pair to integer load / store operations if the target
7703 /// deems the transformation profitable.
7704 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7705   StoreSDNode *ST  = cast<StoreSDNode>(N);
7706   SDValue Chain = ST->getChain();
7707   SDValue Value = ST->getValue();
7708   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7709       Value.hasOneUse() &&
7710       Chain == SDValue(Value.getNode(), 1)) {
7711     LoadSDNode *LD = cast<LoadSDNode>(Value);
7712     EVT VT = LD->getMemoryVT();
7713     if (!VT.isFloatingPoint() ||
7714         VT != ST->getMemoryVT() ||
7715         LD->isNonTemporal() ||
7716         ST->isNonTemporal() ||
7717         LD->getPointerInfo().getAddrSpace() != 0 ||
7718         ST->getPointerInfo().getAddrSpace() != 0)
7719       return SDValue();
7720
7721     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7722     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7723         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7724         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7725         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7726       return SDValue();
7727
7728     unsigned LDAlign = LD->getAlignment();
7729     unsigned STAlign = ST->getAlignment();
7730     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7731     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7732     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7733       return SDValue();
7734
7735     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
7736                                 LD->getChain(), LD->getBasePtr(),
7737                                 LD->getPointerInfo(),
7738                                 false, false, false, LDAlign);
7739
7740     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
7741                                  NewLD, ST->getBasePtr(),
7742                                  ST->getPointerInfo(),
7743                                  false, false, STAlign);
7744
7745     AddToWorkList(NewLD.getNode());
7746     AddToWorkList(NewST.getNode());
7747     WorkListRemover DeadNodes(*this);
7748     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7749     ++LdStFP2Int;
7750     return NewST;
7751   }
7752
7753   return SDValue();
7754 }
7755
7756 /// Helper struct to parse and store a memory address as base + index + offset.
7757 /// We ignore sign extensions when it is safe to do so.
7758 /// The following two expressions are not equivalent. To differentiate we need
7759 /// to store whether there was a sign extension involved in the index
7760 /// computation.
7761 ///  (load (i64 add (i64 copyfromreg %c)
7762 ///                 (i64 signextend (add (i8 load %index)
7763 ///                                      (i8 1))))
7764 /// vs
7765 ///
7766 /// (load (i64 add (i64 copyfromreg %c)
7767 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7768 ///                                         (i32 1)))))
7769 struct BaseIndexOffset {
7770   SDValue Base;
7771   SDValue Index;
7772   int64_t Offset;
7773   bool IsIndexSignExt;
7774
7775   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7776
7777   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7778                   bool IsIndexSignExt) :
7779     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7780
7781   bool equalBaseIndex(const BaseIndexOffset &Other) {
7782     return Other.Base == Base && Other.Index == Index &&
7783       Other.IsIndexSignExt == IsIndexSignExt;
7784   }
7785
7786   /// Parses tree in Ptr for base, index, offset addresses.
7787   static BaseIndexOffset match(SDValue Ptr) {
7788     bool IsIndexSignExt = false;
7789
7790     // Just Base or possibly anything else.
7791     if (Ptr->getOpcode() != ISD::ADD)
7792       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7793
7794     // Base + offset.
7795     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7796       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7797       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7798                               IsIndexSignExt);
7799     }
7800
7801     // Look at Base + Index + Offset cases.
7802     SDValue Base = Ptr->getOperand(0);
7803     SDValue IndexOffset = Ptr->getOperand(1);
7804
7805     // Skip signextends.
7806     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7807       IndexOffset = IndexOffset->getOperand(0);
7808       IsIndexSignExt = true;
7809     }
7810
7811     // Either the case of Base + Index (no offset) or something else.
7812     if (IndexOffset->getOpcode() != ISD::ADD)
7813       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7814
7815     // Now we have the case of Base + Index + offset.
7816     SDValue Index = IndexOffset->getOperand(0);
7817     SDValue Offset = IndexOffset->getOperand(1);
7818
7819     if (!isa<ConstantSDNode>(Offset))
7820       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7821
7822     // Ignore signextends.
7823     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7824       Index = Index->getOperand(0);
7825       IsIndexSignExt = true;
7826     } else IsIndexSignExt = false;
7827
7828     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7829     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7830   }
7831 };
7832
7833 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7834 /// is located in a sequence of memory operations connected by a chain.
7835 struct MemOpLink {
7836   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7837     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7838   // Ptr to the mem node.
7839   LSBaseSDNode *MemNode;
7840   // Offset from the base ptr.
7841   int64_t OffsetFromBase;
7842   // What is the sequence number of this mem node.
7843   // Lowest mem operand in the DAG starts at zero.
7844   unsigned SequenceNum;
7845 };
7846
7847 /// Sorts store nodes in a link according to their offset from a shared
7848 // base ptr.
7849 struct ConsecutiveMemoryChainSorter {
7850   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7851     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7852   }
7853 };
7854
7855 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7856   EVT MemVT = St->getMemoryVT();
7857   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
7858   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
7859     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
7860
7861   // Don't merge vectors into wider inputs.
7862   if (MemVT.isVector() || !MemVT.isSimple())
7863     return false;
7864
7865   // Perform an early exit check. Do not bother looking at stored values that
7866   // are not constants or loads.
7867   SDValue StoredVal = St->getValue();
7868   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
7869   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
7870       !IsLoadSrc)
7871     return false;
7872
7873   // Only look at ends of store sequences.
7874   SDValue Chain = SDValue(St, 1);
7875   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
7876     return false;
7877
7878   // This holds the base pointer, index, and the offset in bytes from the base
7879   // pointer.
7880   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
7881
7882   // We must have a base and an offset.
7883   if (!BasePtr.Base.getNode())
7884     return false;
7885
7886   // Do not handle stores to undef base pointers.
7887   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
7888     return false;
7889
7890   // Save the LoadSDNodes that we find in the chain.
7891   // We need to make sure that these nodes do not interfere with
7892   // any of the store nodes.
7893   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
7894
7895   // Save the StoreSDNodes that we find in the chain.
7896   SmallVector<MemOpLink, 8> StoreNodes;
7897
7898   // Walk up the chain and look for nodes with offsets from the same
7899   // base pointer. Stop when reaching an instruction with a different kind
7900   // or instruction which has a different base pointer.
7901   unsigned Seq = 0;
7902   StoreSDNode *Index = St;
7903   while (Index) {
7904     // If the chain has more than one use, then we can't reorder the mem ops.
7905     if (Index != St && !SDValue(Index, 1)->hasOneUse())
7906       break;
7907
7908     // Find the base pointer and offset for this memory node.
7909     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
7910
7911     // Check that the base pointer is the same as the original one.
7912     if (!Ptr.equalBaseIndex(BasePtr))
7913       break;
7914
7915     // Check that the alignment is the same.
7916     if (Index->getAlignment() != St->getAlignment())
7917       break;
7918
7919     // The memory operands must not be volatile.
7920     if (Index->isVolatile() || Index->isIndexed())
7921       break;
7922
7923     // No truncation.
7924     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
7925       if (St->isTruncatingStore())
7926         break;
7927
7928     // The stored memory type must be the same.
7929     if (Index->getMemoryVT() != MemVT)
7930       break;
7931
7932     // We do not allow unaligned stores because we want to prevent overriding
7933     // stores.
7934     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
7935       break;
7936
7937     // We found a potential memory operand to merge.
7938     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
7939
7940     // Find the next memory operand in the chain. If the next operand in the
7941     // chain is a store then move up and continue the scan with the next
7942     // memory operand. If the next operand is a load save it and use alias
7943     // information to check if it interferes with anything.
7944     SDNode *NextInChain = Index->getChain().getNode();
7945     while (1) {
7946       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
7947         // We found a store node. Use it for the next iteration.
7948         Index = STn;
7949         break;
7950       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
7951         // Save the load node for later. Continue the scan.
7952         AliasLoadNodes.push_back(Ldn);
7953         NextInChain = Ldn->getChain().getNode();
7954         continue;
7955       } else {
7956         Index = NULL;
7957         break;
7958       }
7959     }
7960   }
7961
7962   // Check if there is anything to merge.
7963   if (StoreNodes.size() < 2)
7964     return false;
7965
7966   // Sort the memory operands according to their distance from the base pointer.
7967   std::sort(StoreNodes.begin(), StoreNodes.end(),
7968             ConsecutiveMemoryChainSorter());
7969
7970   // Scan the memory operations on the chain and find the first non-consecutive
7971   // store memory address.
7972   unsigned LastConsecutiveStore = 0;
7973   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
7974   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
7975
7976     // Check that the addresses are consecutive starting from the second
7977     // element in the list of stores.
7978     if (i > 0) {
7979       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
7980       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
7981         break;
7982     }
7983
7984     bool Alias = false;
7985     // Check if this store interferes with any of the loads that we found.
7986     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
7987       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
7988         Alias = true;
7989         break;
7990       }
7991     // We found a load that alias with this store. Stop the sequence.
7992     if (Alias)
7993       break;
7994
7995     // Mark this node as useful.
7996     LastConsecutiveStore = i;
7997   }
7998
7999   // The node with the lowest store address.
8000   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8001
8002   // Store the constants into memory as one consecutive store.
8003   if (!IsLoadSrc) {
8004     unsigned LastLegalType = 0;
8005     unsigned LastLegalVectorType = 0;
8006     bool NonZero = false;
8007     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8008       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8009       SDValue StoredVal = St->getValue();
8010
8011       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8012         NonZero |= !C->isNullValue();
8013       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8014         NonZero |= !C->getConstantFPValue()->isNullValue();
8015       } else {
8016         // Non constant.
8017         break;
8018       }
8019
8020       // Find a legal type for the constant store.
8021       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8022       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8023       if (TLI.isTypeLegal(StoreTy))
8024         LastLegalType = i+1;
8025       // Or check whether a truncstore is legal.
8026       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8027                TargetLowering::TypePromoteInteger) {
8028         EVT LegalizedStoredValueTy =
8029           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8030         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8031           LastLegalType = i+1;
8032       }
8033
8034       // Find a legal type for the vector store.
8035       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8036       if (TLI.isTypeLegal(Ty))
8037         LastLegalVectorType = i + 1;
8038     }
8039
8040     // We only use vectors if the constant is known to be zero and the
8041     // function is not marked with the noimplicitfloat attribute.
8042     if (NonZero || NoVectors)
8043       LastLegalVectorType = 0;
8044
8045     // Check if we found a legal integer type to store.
8046     if (LastLegalType == 0 && LastLegalVectorType == 0)
8047       return false;
8048
8049     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8050     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8051
8052     // Make sure we have something to merge.
8053     if (NumElem < 2)
8054       return false;
8055
8056     unsigned EarliestNodeUsed = 0;
8057     for (unsigned i=0; i < NumElem; ++i) {
8058       // Find a chain for the new wide-store operand. Notice that some
8059       // of the store nodes that we found may not be selected for inclusion
8060       // in the wide store. The chain we use needs to be the chain of the
8061       // earliest store node which is *used* and replaced by the wide store.
8062       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8063         EarliestNodeUsed = i;
8064     }
8065
8066     // The earliest Node in the DAG.
8067     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8068     DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
8069
8070     SDValue StoredVal;
8071     if (UseVector) {
8072       // Find a legal type for the vector store.
8073       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8074       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8075       StoredVal = DAG.getConstant(0, Ty);
8076     } else {
8077       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8078       APInt StoreInt(StoreBW, 0);
8079
8080       // Construct a single integer constant which is made of the smaller
8081       // constant inputs.
8082       bool IsLE = TLI.isLittleEndian();
8083       for (unsigned i = 0; i < NumElem ; ++i) {
8084         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8085         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8086         SDValue Val = St->getValue();
8087         StoreInt<<=ElementSizeBytes*8;
8088         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8089           StoreInt|=C->getAPIntValue().zext(StoreBW);
8090         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8091           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8092         } else {
8093           assert(false && "Invalid constant element type");
8094         }
8095       }
8096
8097       // Create the new Load and Store operations.
8098       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8099       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8100     }
8101
8102     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8103                                     FirstInChain->getBasePtr(),
8104                                     FirstInChain->getPointerInfo(),
8105                                     false, false,
8106                                     FirstInChain->getAlignment());
8107
8108     // Replace the first store with the new store
8109     CombineTo(EarliestOp, NewStore);
8110     // Erase all other stores.
8111     for (unsigned i = 0; i < NumElem ; ++i) {
8112       if (StoreNodes[i].MemNode == EarliestOp)
8113         continue;
8114       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8115       // ReplaceAllUsesWith will replace all uses that existed when it was
8116       // called, but graph optimizations may cause new ones to appear. For
8117       // example, the case in pr14333 looks like
8118       //
8119       //  St's chain -> St -> another store -> X
8120       //
8121       // And the only difference from St to the other store is the chain.
8122       // When we change it's chain to be St's chain they become identical,
8123       // get CSEed and the net result is that X is now a use of St.
8124       // Since we know that St is redundant, just iterate.
8125       while (!St->use_empty())
8126         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8127       removeFromWorkList(St);
8128       DAG.DeleteNode(St);
8129     }
8130
8131     return true;
8132   }
8133
8134   // Below we handle the case of multiple consecutive stores that
8135   // come from multiple consecutive loads. We merge them into a single
8136   // wide load and a single wide store.
8137
8138   // Look for load nodes which are used by the stored values.
8139   SmallVector<MemOpLink, 8> LoadNodes;
8140
8141   // Find acceptable loads. Loads need to have the same chain (token factor),
8142   // must not be zext, volatile, indexed, and they must be consecutive.
8143   BaseIndexOffset LdBasePtr;
8144   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8145     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8146     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8147     if (!Ld) break;
8148
8149     // Loads must only have one use.
8150     if (!Ld->hasNUsesOfValue(1, 0))
8151       break;
8152
8153     // Check that the alignment is the same as the stores.
8154     if (Ld->getAlignment() != St->getAlignment())
8155       break;
8156
8157     // The memory operands must not be volatile.
8158     if (Ld->isVolatile() || Ld->isIndexed())
8159       break;
8160
8161     // We do not accept ext loads.
8162     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8163       break;
8164
8165     // The stored memory type must be the same.
8166     if (Ld->getMemoryVT() != MemVT)
8167       break;
8168
8169     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8170     // If this is not the first ptr that we check.
8171     if (LdBasePtr.Base.getNode()) {
8172       // The base ptr must be the same.
8173       if (!LdPtr.equalBaseIndex(LdBasePtr))
8174         break;
8175     } else {
8176       // Check that all other base pointers are the same as this one.
8177       LdBasePtr = LdPtr;
8178     }
8179
8180     // We found a potential memory operand to merge.
8181     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8182   }
8183
8184   if (LoadNodes.size() < 2)
8185     return false;
8186
8187   // Scan the memory operations on the chain and find the first non-consecutive
8188   // load memory address. These variables hold the index in the store node
8189   // array.
8190   unsigned LastConsecutiveLoad = 0;
8191   // This variable refers to the size and not index in the array.
8192   unsigned LastLegalVectorType = 0;
8193   unsigned LastLegalIntegerType = 0;
8194   StartAddress = LoadNodes[0].OffsetFromBase;
8195   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8196   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8197     // All loads much share the same chain.
8198     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8199       break;
8200
8201     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8202     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8203       break;
8204     LastConsecutiveLoad = i;
8205
8206     // Find a legal type for the vector store.
8207     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8208     if (TLI.isTypeLegal(StoreTy))
8209       LastLegalVectorType = i + 1;
8210
8211     // Find a legal type for the integer store.
8212     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8213     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8214     if (TLI.isTypeLegal(StoreTy))
8215       LastLegalIntegerType = i + 1;
8216     // Or check whether a truncstore and extload is legal.
8217     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8218              TargetLowering::TypePromoteInteger) {
8219       EVT LegalizedStoredValueTy =
8220         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8221       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8222           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8223           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8224           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8225         LastLegalIntegerType = i+1;
8226     }
8227   }
8228
8229   // Only use vector types if the vector type is larger than the integer type.
8230   // If they are the same, use integers.
8231   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8232   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8233
8234   // We add +1 here because the LastXXX variables refer to location while
8235   // the NumElem refers to array/index size.
8236   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8237   NumElem = std::min(LastLegalType, NumElem);
8238
8239   if (NumElem < 2)
8240     return false;
8241
8242   // The earliest Node in the DAG.
8243   unsigned EarliestNodeUsed = 0;
8244   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8245   for (unsigned i=1; i<NumElem; ++i) {
8246     // Find a chain for the new wide-store operand. Notice that some
8247     // of the store nodes that we found may not be selected for inclusion
8248     // in the wide store. The chain we use needs to be the chain of the
8249     // earliest store node which is *used* and replaced by the wide store.
8250     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8251       EarliestNodeUsed = i;
8252   }
8253
8254   // Find if it is better to use vectors or integers to load and store
8255   // to memory.
8256   EVT JointMemOpVT;
8257   if (UseVectorTy) {
8258     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8259   } else {
8260     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8261     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8262   }
8263
8264   DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
8265   DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
8266
8267   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8268   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8269                                 FirstLoad->getChain(),
8270                                 FirstLoad->getBasePtr(),
8271                                 FirstLoad->getPointerInfo(),
8272                                 false, false, false,
8273                                 FirstLoad->getAlignment());
8274
8275   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8276                                   FirstInChain->getBasePtr(),
8277                                   FirstInChain->getPointerInfo(), false, false,
8278                                   FirstInChain->getAlignment());
8279
8280   // Replace one of the loads with the new load.
8281   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8282   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8283                                 SDValue(NewLoad.getNode(), 1));
8284
8285   // Remove the rest of the load chains.
8286   for (unsigned i = 1; i < NumElem ; ++i) {
8287     // Replace all chain users of the old load nodes with the chain of the new
8288     // load node.
8289     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8290     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8291   }
8292
8293   // Replace the first store with the new store.
8294   CombineTo(EarliestOp, NewStore);
8295   // Erase all other stores.
8296   for (unsigned i = 0; i < NumElem ; ++i) {
8297     // Remove all Store nodes.
8298     if (StoreNodes[i].MemNode == EarliestOp)
8299       continue;
8300     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8301     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8302     removeFromWorkList(St);
8303     DAG.DeleteNode(St);
8304   }
8305
8306   return true;
8307 }
8308
8309 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8310   StoreSDNode *ST  = cast<StoreSDNode>(N);
8311   SDValue Chain = ST->getChain();
8312   SDValue Value = ST->getValue();
8313   SDValue Ptr   = ST->getBasePtr();
8314
8315   // If this is a store of a bit convert, store the input value if the
8316   // resultant store does not need a higher alignment than the original.
8317   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8318       ST->isUnindexed()) {
8319     unsigned OrigAlign = ST->getAlignment();
8320     EVT SVT = Value.getOperand(0).getValueType();
8321     unsigned Align = TLI.getDataLayout()->
8322       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8323     if (Align <= OrigAlign &&
8324         ((!LegalOperations && !ST->isVolatile()) ||
8325          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8326       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8327                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8328                           ST->isNonTemporal(), OrigAlign);
8329   }
8330
8331   // Turn 'store undef, Ptr' -> nothing.
8332   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8333     return Chain;
8334
8335   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8336   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8337     // NOTE: If the original store is volatile, this transform must not increase
8338     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8339     // processor operation but an i64 (which is not legal) requires two.  So the
8340     // transform should not be done in this case.
8341     if (Value.getOpcode() != ISD::TargetConstantFP) {
8342       SDValue Tmp;
8343       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
8344       default: llvm_unreachable("Unknown FP type");
8345       case MVT::f16:    // We don't do this for these yet.
8346       case MVT::f80:
8347       case MVT::f128:
8348       case MVT::ppcf128:
8349         break;
8350       case MVT::f32:
8351         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8352             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8353           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8354                               bitcastToAPInt().getZExtValue(), MVT::i32);
8355           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8356                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8357                               ST->isNonTemporal(), ST->getAlignment());
8358         }
8359         break;
8360       case MVT::f64:
8361         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8362              !ST->isVolatile()) ||
8363             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8364           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8365                                 getZExtValue(), MVT::i64);
8366           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
8367                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8368                               ST->isNonTemporal(), ST->getAlignment());
8369         }
8370
8371         if (!ST->isVolatile() &&
8372             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8373           // Many FP stores are not made apparent until after legalize, e.g. for
8374           // argument passing.  Since this is so common, custom legalize the
8375           // 64-bit integer store into two 32-bit stores.
8376           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8377           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8378           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8379           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8380
8381           unsigned Alignment = ST->getAlignment();
8382           bool isVolatile = ST->isVolatile();
8383           bool isNonTemporal = ST->isNonTemporal();
8384
8385           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
8386                                      Ptr, ST->getPointerInfo(),
8387                                      isVolatile, isNonTemporal,
8388                                      ST->getAlignment());
8389           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
8390                             DAG.getConstant(4, Ptr.getValueType()));
8391           Alignment = MinAlign(Alignment, 4U);
8392           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
8393                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8394                                      isVolatile, isNonTemporal,
8395                                      Alignment);
8396           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
8397                              St0, St1);
8398         }
8399
8400         break;
8401       }
8402     }
8403   }
8404
8405   // Try to infer better alignment information than the store already has.
8406   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8407     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8408       if (Align > ST->getAlignment())
8409         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
8410                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8411                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8412     }
8413   }
8414
8415   // Try transforming a pair floating point load / store ops to integer
8416   // load / store ops.
8417   SDValue NewST = TransformFPLoadStorePair(N);
8418   if (NewST.getNode())
8419     return NewST;
8420
8421   if (CombinerAA) {
8422     // Walk up chain skipping non-aliasing memory nodes.
8423     SDValue BetterChain = FindBetterChain(N, Chain);
8424
8425     // If there is a better chain.
8426     if (Chain != BetterChain) {
8427       SDValue ReplStore;
8428
8429       // Replace the chain to avoid dependency.
8430       if (ST->isTruncatingStore()) {
8431         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8432                                       ST->getPointerInfo(),
8433                                       ST->getMemoryVT(), ST->isVolatile(),
8434                                       ST->isNonTemporal(), ST->getAlignment());
8435       } else {
8436         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
8437                                  ST->getPointerInfo(),
8438                                  ST->isVolatile(), ST->isNonTemporal(),
8439                                  ST->getAlignment());
8440       }
8441
8442       // Create token to keep both nodes around.
8443       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
8444                                   MVT::Other, Chain, ReplStore);
8445
8446       // Make sure the new and old chains are cleaned up.
8447       AddToWorkList(Token.getNode());
8448
8449       // Don't add users to work list.
8450       return CombineTo(N, Token, false);
8451     }
8452   }
8453
8454   // Try transforming N to an indexed store.
8455   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8456     return SDValue(N, 0);
8457
8458   // FIXME: is there such a thing as a truncating indexed store?
8459   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8460       Value.getValueType().isInteger()) {
8461     // See if we can simplify the input to this truncstore with knowledge that
8462     // only the low bits are being used.  For example:
8463     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8464     SDValue Shorter =
8465       GetDemandedBits(Value,
8466                       APInt::getLowBitsSet(
8467                         Value.getValueType().getScalarType().getSizeInBits(),
8468                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8469     AddToWorkList(Value.getNode());
8470     if (Shorter.getNode())
8471       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
8472                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8473                                ST->isVolatile(), ST->isNonTemporal(),
8474                                ST->getAlignment());
8475
8476     // Otherwise, see if we can simplify the operation with
8477     // SimplifyDemandedBits, which only works if the value has a single use.
8478     if (SimplifyDemandedBits(Value,
8479                         APInt::getLowBitsSet(
8480                           Value.getValueType().getScalarType().getSizeInBits(),
8481                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8482       return SDValue(N, 0);
8483   }
8484
8485   // If this is a load followed by a store to the same location, then the store
8486   // is dead/noop.
8487   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8488     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8489         ST->isUnindexed() && !ST->isVolatile() &&
8490         // There can't be any side effects between the load and store, such as
8491         // a call or store.
8492         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8493       // The store is dead, remove it.
8494       return Chain;
8495     }
8496   }
8497
8498   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8499   // truncating store.  We can do this even if this is already a truncstore.
8500   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8501       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8502       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8503                             ST->getMemoryVT())) {
8504     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
8505                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8506                              ST->isVolatile(), ST->isNonTemporal(),
8507                              ST->getAlignment());
8508   }
8509
8510   // Only perform this optimization before the types are legal, because we
8511   // don't want to perform this optimization on every DAGCombine invocation.
8512   if (!LegalTypes) {
8513     bool EverChanged = false;
8514
8515     do {
8516       // There can be multiple store sequences on the same chain.
8517       // Keep trying to merge store sequences until we are unable to do so
8518       // or until we merge the last store on the chain.
8519       bool Changed = MergeConsecutiveStores(ST);
8520       EverChanged |= Changed;
8521       if (!Changed) break;
8522     } while (ST->getOpcode() != ISD::DELETED_NODE);
8523
8524     if (EverChanged)
8525       return SDValue(N, 0);
8526   }
8527
8528   return ReduceLoadOpStoreWidth(N);
8529 }
8530
8531 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8532   SDValue InVec = N->getOperand(0);
8533   SDValue InVal = N->getOperand(1);
8534   SDValue EltNo = N->getOperand(2);
8535   DebugLoc dl = N->getDebugLoc();
8536
8537   // If the inserted element is an UNDEF, just use the input vector.
8538   if (InVal.getOpcode() == ISD::UNDEF)
8539     return InVec;
8540
8541   EVT VT = InVec.getValueType();
8542
8543   // If we can't generate a legal BUILD_VECTOR, exit
8544   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8545     return SDValue();
8546
8547   // Check that we know which element is being inserted
8548   if (!isa<ConstantSDNode>(EltNo))
8549     return SDValue();
8550   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8551
8552   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8553   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8554   // vector elements.
8555   SmallVector<SDValue, 8> Ops;
8556   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
8557     Ops.append(InVec.getNode()->op_begin(),
8558                InVec.getNode()->op_end());
8559   } else if (InVec.getOpcode() == ISD::UNDEF) {
8560     unsigned NElts = VT.getVectorNumElements();
8561     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8562   } else {
8563     return SDValue();
8564   }
8565
8566   // Insert the element
8567   if (Elt < Ops.size()) {
8568     // All the operands of BUILD_VECTOR must have the same type;
8569     // we enforce that here.
8570     EVT OpVT = Ops[0].getValueType();
8571     if (InVal.getValueType() != OpVT)
8572       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8573                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8574                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8575     Ops[Elt] = InVal;
8576   }
8577
8578   // Return the new vector
8579   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8580                      VT, &Ops[0], Ops.size());
8581 }
8582
8583 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8584   // (vextract (scalar_to_vector val, 0) -> val
8585   SDValue InVec = N->getOperand(0);
8586   EVT VT = InVec.getValueType();
8587   EVT NVT = N->getValueType(0);
8588
8589   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8590     // Check if the result type doesn't match the inserted element type. A
8591     // SCALAR_TO_VECTOR may truncate the inserted element and the
8592     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8593     SDValue InOp = InVec.getOperand(0);
8594     if (InOp.getValueType() != NVT) {
8595       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8596       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
8597     }
8598     return InOp;
8599   }
8600
8601   SDValue EltNo = N->getOperand(1);
8602   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8603
8604   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8605   // We only perform this optimization before the op legalization phase because
8606   // we may introduce new vector instructions which are not backed by TD
8607   // patterns. For example on AVX, extracting elements from a wide vector
8608   // without using extract_subvector.
8609   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8610       && ConstEltNo && !LegalOperations) {
8611     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8612     int NumElem = VT.getVectorNumElements();
8613     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8614     // Find the new index to extract from.
8615     int OrigElt = SVOp->getMaskElt(Elt);
8616
8617     // Extracting an undef index is undef.
8618     if (OrigElt == -1)
8619       return DAG.getUNDEF(NVT);
8620
8621     // Select the right vector half to extract from.
8622     if (OrigElt < NumElem) {
8623       InVec = InVec->getOperand(0);
8624     } else {
8625       InVec = InVec->getOperand(1);
8626       OrigElt -= NumElem;
8627     }
8628
8629     EVT IndexTy = N->getOperand(1).getValueType();
8630     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
8631                        InVec, DAG.getConstant(OrigElt, IndexTy));
8632   }
8633
8634   // Perform only after legalization to ensure build_vector / vector_shuffle
8635   // optimizations have already been done.
8636   if (!LegalOperations) return SDValue();
8637
8638   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8639   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8640   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8641
8642   if (ConstEltNo) {
8643     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8644     bool NewLoad = false;
8645     bool BCNumEltsChanged = false;
8646     EVT ExtVT = VT.getVectorElementType();
8647     EVT LVT = ExtVT;
8648
8649     // If the result of load has to be truncated, then it's not necessarily
8650     // profitable.
8651     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8652       return SDValue();
8653
8654     if (InVec.getOpcode() == ISD::BITCAST) {
8655       // Don't duplicate a load with other uses.
8656       if (!InVec.hasOneUse())
8657         return SDValue();
8658
8659       EVT BCVT = InVec.getOperand(0).getValueType();
8660       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8661         return SDValue();
8662       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8663         BCNumEltsChanged = true;
8664       InVec = InVec.getOperand(0);
8665       ExtVT = BCVT.getVectorElementType();
8666       NewLoad = true;
8667     }
8668
8669     LoadSDNode *LN0 = NULL;
8670     const ShuffleVectorSDNode *SVN = NULL;
8671     if (ISD::isNormalLoad(InVec.getNode())) {
8672       LN0 = cast<LoadSDNode>(InVec);
8673     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8674                InVec.getOperand(0).getValueType() == ExtVT &&
8675                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8676       // Don't duplicate a load with other uses.
8677       if (!InVec.hasOneUse())
8678         return SDValue();
8679
8680       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8681     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8682       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8683       // =>
8684       // (load $addr+1*size)
8685
8686       // Don't duplicate a load with other uses.
8687       if (!InVec.hasOneUse())
8688         return SDValue();
8689
8690       // If the bit convert changed the number of elements, it is unsafe
8691       // to examine the mask.
8692       if (BCNumEltsChanged)
8693         return SDValue();
8694
8695       // Select the input vector, guarding against out of range extract vector.
8696       unsigned NumElems = VT.getVectorNumElements();
8697       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8698       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8699
8700       if (InVec.getOpcode() == ISD::BITCAST) {
8701         // Don't duplicate a load with other uses.
8702         if (!InVec.hasOneUse())
8703           return SDValue();
8704
8705         InVec = InVec.getOperand(0);
8706       }
8707       if (ISD::isNormalLoad(InVec.getNode())) {
8708         LN0 = cast<LoadSDNode>(InVec);
8709         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8710       }
8711     }
8712
8713     // Make sure we found a non-volatile load and the extractelement is
8714     // the only use.
8715     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8716       return SDValue();
8717
8718     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8719     if (Elt == -1)
8720       return DAG.getUNDEF(LVT);
8721
8722     unsigned Align = LN0->getAlignment();
8723     if (NewLoad) {
8724       // Check the resultant load doesn't need a higher alignment than the
8725       // original load.
8726       unsigned NewAlign =
8727         TLI.getDataLayout()
8728             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8729
8730       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8731         return SDValue();
8732
8733       Align = NewAlign;
8734     }
8735
8736     SDValue NewPtr = LN0->getBasePtr();
8737     unsigned PtrOff = 0;
8738
8739     if (Elt) {
8740       PtrOff = LVT.getSizeInBits() * Elt / 8;
8741       EVT PtrType = NewPtr.getValueType();
8742       if (TLI.isBigEndian())
8743         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8744       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
8745                            DAG.getConstant(PtrOff, PtrType));
8746     }
8747
8748     // The replacement we need to do here is a little tricky: we need to
8749     // replace an extractelement of a load with a load.
8750     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8751     // Note that this replacement assumes that the extractvalue is the only
8752     // use of the load; that's okay because we don't want to perform this
8753     // transformation in other cases anyway.
8754     SDValue Load;
8755     SDValue Chain;
8756     if (NVT.bitsGT(LVT)) {
8757       // If the result type of vextract is wider than the load, then issue an
8758       // extending load instead.
8759       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8760         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8761       Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
8762                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8763                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8764       Chain = Load.getValue(1);
8765     } else {
8766       Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
8767                          LN0->getPointerInfo().getWithOffset(PtrOff),
8768                          LN0->isVolatile(), LN0->isNonTemporal(), 
8769                          LN0->isInvariant(), Align);
8770       Chain = Load.getValue(1);
8771       if (NVT.bitsLT(LVT))
8772         Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
8773       else
8774         Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
8775     }
8776     WorkListRemover DeadNodes(*this);
8777     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8778     SDValue To[] = { Load, Chain };
8779     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8780     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8781     // worklist explicitly as well.
8782     AddToWorkList(Load.getNode());
8783     AddUsersToWorkList(Load.getNode()); // Add users too
8784     // Make sure to revisit this node to clean it up; it will usually be dead.
8785     AddToWorkList(N);
8786     return SDValue(N, 0);
8787   }
8788
8789   return SDValue();
8790 }
8791
8792 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8793 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8794   // We perform this optimization post type-legalization because
8795   // the type-legalizer often scalarizes integer-promoted vectors.
8796   // Performing this optimization before may create bit-casts which
8797   // will be type-legalized to complex code sequences.
8798   // We perform this optimization only before the operation legalizer because we
8799   // may introduce illegal operations.
8800   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8801     return SDValue();
8802
8803   unsigned NumInScalars = N->getNumOperands();
8804   DebugLoc dl = N->getDebugLoc();
8805   EVT VT = N->getValueType(0);
8806
8807   // Check to see if this is a BUILD_VECTOR of a bunch of values
8808   // which come from any_extend or zero_extend nodes. If so, we can create
8809   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8810   // optimizations. We do not handle sign-extend because we can't fill the sign
8811   // using shuffles.
8812   EVT SourceType = MVT::Other;
8813   bool AllAnyExt = true;
8814
8815   for (unsigned i = 0; i != NumInScalars; ++i) {
8816     SDValue In = N->getOperand(i);
8817     // Ignore undef inputs.
8818     if (In.getOpcode() == ISD::UNDEF) continue;
8819
8820     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8821     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8822
8823     // Abort if the element is not an extension.
8824     if (!ZeroExt && !AnyExt) {
8825       SourceType = MVT::Other;
8826       break;
8827     }
8828
8829     // The input is a ZeroExt or AnyExt. Check the original type.
8830     EVT InTy = In.getOperand(0).getValueType();
8831
8832     // Check that all of the widened source types are the same.
8833     if (SourceType == MVT::Other)
8834       // First time.
8835       SourceType = InTy;
8836     else if (InTy != SourceType) {
8837       // Multiple income types. Abort.
8838       SourceType = MVT::Other;
8839       break;
8840     }
8841
8842     // Check if all of the extends are ANY_EXTENDs.
8843     AllAnyExt &= AnyExt;
8844   }
8845
8846   // In order to have valid types, all of the inputs must be extended from the
8847   // same source type and all of the inputs must be any or zero extend.
8848   // Scalar sizes must be a power of two.
8849   EVT OutScalarTy = VT.getScalarType();
8850   bool ValidTypes = SourceType != MVT::Other &&
8851                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8852                  isPowerOf2_32(SourceType.getSizeInBits());
8853
8854   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
8855   // turn into a single shuffle instruction.
8856   if (!ValidTypes)
8857     return SDValue();
8858
8859   bool isLE = TLI.isLittleEndian();
8860   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
8861   assert(ElemRatio > 1 && "Invalid element size ratio");
8862   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
8863                                DAG.getConstant(0, SourceType);
8864
8865   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
8866   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
8867
8868   // Populate the new build_vector
8869   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
8870     SDValue Cast = N->getOperand(i);
8871     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
8872             Cast.getOpcode() == ISD::ZERO_EXTEND ||
8873             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
8874     SDValue In;
8875     if (Cast.getOpcode() == ISD::UNDEF)
8876       In = DAG.getUNDEF(SourceType);
8877     else
8878       In = Cast->getOperand(0);
8879     unsigned Index = isLE ? (i * ElemRatio) :
8880                             (i * ElemRatio + (ElemRatio - 1));
8881
8882     assert(Index < Ops.size() && "Invalid index");
8883     Ops[Index] = In;
8884   }
8885
8886   // The type of the new BUILD_VECTOR node.
8887   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
8888   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
8889          "Invalid vector size");
8890   // Check if the new vector type is legal.
8891   if (!isTypeLegal(VecVT)) return SDValue();
8892
8893   // Make the new BUILD_VECTOR.
8894   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
8895
8896   // The new BUILD_VECTOR node has the potential to be further optimized.
8897   AddToWorkList(BV.getNode());
8898   // Bitcast to the desired type.
8899   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
8900 }
8901
8902 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
8903   EVT VT = N->getValueType(0);
8904
8905   unsigned NumInScalars = N->getNumOperands();
8906   DebugLoc dl = N->getDebugLoc();
8907
8908   EVT SrcVT = MVT::Other;
8909   unsigned Opcode = ISD::DELETED_NODE;
8910   unsigned NumDefs = 0;
8911
8912   for (unsigned i = 0; i != NumInScalars; ++i) {
8913     SDValue In = N->getOperand(i);
8914     unsigned Opc = In.getOpcode();
8915
8916     if (Opc == ISD::UNDEF)
8917       continue;
8918
8919     // If all scalar values are floats and converted from integers.
8920     if (Opcode == ISD::DELETED_NODE &&
8921         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
8922       Opcode = Opc;
8923     }
8924
8925     if (Opc != Opcode)
8926       return SDValue();
8927
8928     EVT InVT = In.getOperand(0).getValueType();
8929
8930     // If all scalar values are typed differently, bail out. It's chosen to
8931     // simplify BUILD_VECTOR of integer types.
8932     if (SrcVT == MVT::Other)
8933       SrcVT = InVT;
8934     if (SrcVT != InVT)
8935       return SDValue();
8936     NumDefs++;
8937   }
8938
8939   // If the vector has just one element defined, it's not worth to fold it into
8940   // a vectorized one.
8941   if (NumDefs < 2)
8942     return SDValue();
8943
8944   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
8945          && "Should only handle conversion from integer to float.");
8946   assert(SrcVT != MVT::Other && "Cannot determine source type!");
8947
8948   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
8949
8950   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
8951     return SDValue();
8952
8953   SmallVector<SDValue, 8> Opnds;
8954   for (unsigned i = 0; i != NumInScalars; ++i) {
8955     SDValue In = N->getOperand(i);
8956
8957     if (In.getOpcode() == ISD::UNDEF)
8958       Opnds.push_back(DAG.getUNDEF(SrcVT));
8959     else
8960       Opnds.push_back(In.getOperand(0));
8961   }
8962   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
8963                            &Opnds[0], Opnds.size());
8964   AddToWorkList(BV.getNode());
8965
8966   return DAG.getNode(Opcode, dl, VT, BV);
8967 }
8968
8969 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
8970   unsigned NumInScalars = N->getNumOperands();
8971   DebugLoc dl = N->getDebugLoc();
8972   EVT VT = N->getValueType(0);
8973
8974   // A vector built entirely of undefs is undef.
8975   if (ISD::allOperandsUndef(N))
8976     return DAG.getUNDEF(VT);
8977
8978   SDValue V = reduceBuildVecExtToExtBuildVec(N);
8979   if (V.getNode())
8980     return V;
8981
8982   V = reduceBuildVecConvertToConvertBuildVec(N);
8983   if (V.getNode())
8984     return V;
8985
8986   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
8987   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
8988   // at most two distinct vectors, turn this into a shuffle node.
8989
8990   // May only combine to shuffle after legalize if shuffle is legal.
8991   if (LegalOperations &&
8992       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
8993     return SDValue();
8994
8995   SDValue VecIn1, VecIn2;
8996   for (unsigned i = 0; i != NumInScalars; ++i) {
8997     // Ignore undef inputs.
8998     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
8999
9000     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9001     // constant index, bail out.
9002     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9003         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9004       VecIn1 = VecIn2 = SDValue(0, 0);
9005       break;
9006     }
9007
9008     // We allow up to two distinct input vectors.
9009     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9010     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9011       continue;
9012
9013     if (VecIn1.getNode() == 0) {
9014       VecIn1 = ExtractedFromVec;
9015     } else if (VecIn2.getNode() == 0) {
9016       VecIn2 = ExtractedFromVec;
9017     } else {
9018       // Too many inputs.
9019       VecIn1 = VecIn2 = SDValue(0, 0);
9020       break;
9021     }
9022   }
9023
9024     // If everything is good, we can make a shuffle operation.
9025   if (VecIn1.getNode()) {
9026     SmallVector<int, 8> Mask;
9027     for (unsigned i = 0; i != NumInScalars; ++i) {
9028       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9029         Mask.push_back(-1);
9030         continue;
9031       }
9032
9033       // If extracting from the first vector, just use the index directly.
9034       SDValue Extract = N->getOperand(i);
9035       SDValue ExtVal = Extract.getOperand(1);
9036       if (Extract.getOperand(0) == VecIn1) {
9037         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9038         if (ExtIndex > VT.getVectorNumElements())
9039           return SDValue();
9040
9041         Mask.push_back(ExtIndex);
9042         continue;
9043       }
9044
9045       // Otherwise, use InIdx + VecSize
9046       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9047       Mask.push_back(Idx+NumInScalars);
9048     }
9049
9050     // We can't generate a shuffle node with mismatched input and output types.
9051     // Attempt to transform a single input vector to the correct type.
9052     if ((VT != VecIn1.getValueType())) {
9053       // We don't support shuffeling between TWO values of different types.
9054       if (VecIn2.getNode() != 0)
9055         return SDValue();
9056
9057       // We only support widening of vectors which are half the size of the
9058       // output registers. For example XMM->YMM widening on X86 with AVX.
9059       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9060         return SDValue();
9061
9062       // If the input vector type has a different base type to the output
9063       // vector type, bail out.
9064       if (VecIn1.getValueType().getVectorElementType() !=
9065           VT.getVectorElementType())
9066         return SDValue();
9067
9068       // Widen the input vector by adding undef values.
9069       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9070                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9071     }
9072
9073     // If VecIn2 is unused then change it to undef.
9074     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9075
9076     // Check that we were able to transform all incoming values to the same
9077     // type.
9078     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9079         VecIn1.getValueType() != VT)
9080           return SDValue();
9081
9082     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9083     if (!isTypeLegal(VT))
9084       return SDValue();
9085
9086     // Return the new VECTOR_SHUFFLE node.
9087     SDValue Ops[2];
9088     Ops[0] = VecIn1;
9089     Ops[1] = VecIn2;
9090     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9091   }
9092
9093   return SDValue();
9094 }
9095
9096 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9097   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9098   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9099   // inputs come from at most two distinct vectors, turn this into a shuffle
9100   // node.
9101
9102   // If we only have one input vector, we don't need to do any concatenation.
9103   if (N->getNumOperands() == 1)
9104     return N->getOperand(0);
9105
9106   // Check if all of the operands are undefs.
9107   if (ISD::allOperandsUndef(N))
9108     return DAG.getUNDEF(N->getValueType(0));
9109
9110   return SDValue();
9111 }
9112
9113 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9114   EVT NVT = N->getValueType(0);
9115   SDValue V = N->getOperand(0);
9116
9117   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9118     // Combine:
9119     //    (extract_subvec (concat V1, V2, ...), i)
9120     // Into:
9121     //    Vi if possible
9122     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9123     if (V->getOperand(0).getValueType() != NVT)
9124       return SDValue();
9125     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9126     unsigned NumElems = NVT.getVectorNumElements();
9127     assert((Idx % NumElems) == 0 &&
9128            "IDX in concat is not a multiple of the result vector length.");
9129     return V->getOperand(Idx / NumElems);
9130   }
9131
9132   // Skip bitcasting
9133   if (V->getOpcode() == ISD::BITCAST)
9134     V = V.getOperand(0);
9135
9136   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9137     DebugLoc dl = N->getDebugLoc();
9138     // Handle only simple case where vector being inserted and vector
9139     // being extracted are of same type, and are half size of larger vectors.
9140     EVT BigVT = V->getOperand(0).getValueType();
9141     EVT SmallVT = V->getOperand(1).getValueType();
9142     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9143       return SDValue();
9144
9145     // Only handle cases where both indexes are constants with the same type.
9146     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9147     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9148
9149     if (InsIdx && ExtIdx &&
9150         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9151         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9152       // Combine:
9153       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9154       // Into:
9155       //    indices are equal or bit offsets are equal => V1
9156       //    otherwise => (extract_subvec V1, ExtIdx)
9157       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9158           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9159         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9160       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9161                          DAG.getNode(ISD::BITCAST, dl,
9162                                      N->getOperand(0).getValueType(),
9163                                      V->getOperand(0)), N->getOperand(1));
9164     }
9165   }
9166
9167   return SDValue();
9168 }
9169
9170 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9171 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9172   EVT VT = N->getValueType(0);
9173   unsigned NumElts = VT.getVectorNumElements();
9174
9175   SDValue N0 = N->getOperand(0);
9176   SDValue N1 = N->getOperand(1);
9177   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9178
9179   SmallVector<SDValue, 4> Ops;
9180   EVT ConcatVT = N0.getOperand(0).getValueType();
9181   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9182   unsigned NumConcats = NumElts / NumElemsPerConcat;
9183
9184   // Look at every vector that's inserted. We're looking for exact
9185   // subvector-sized copies from a concatenated vector
9186   for (unsigned I = 0; I != NumConcats; ++I) {
9187     // Make sure we're dealing with a copy.
9188     unsigned Begin = I * NumElemsPerConcat;
9189     if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9190       return SDValue();
9191
9192     for (unsigned J = 1; J != NumElemsPerConcat; ++J) {
9193       if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9194         return SDValue();
9195     }
9196
9197     unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9198     if (FirstElt < N0.getNumOperands())
9199       Ops.push_back(N0.getOperand(FirstElt));
9200     else
9201       Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9202   }
9203
9204   return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, Ops.data(),
9205                      Ops.size());
9206 }
9207
9208 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9209   EVT VT = N->getValueType(0);
9210   unsigned NumElts = VT.getVectorNumElements();
9211
9212   SDValue N0 = N->getOperand(0);
9213   SDValue N1 = N->getOperand(1);
9214
9215   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9216
9217   // Canonicalize shuffle undef, undef -> undef
9218   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9219     return DAG.getUNDEF(VT);
9220
9221   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9222
9223   // Canonicalize shuffle v, v -> v, undef
9224   if (N0 == N1) {
9225     SmallVector<int, 8> NewMask;
9226     for (unsigned i = 0; i != NumElts; ++i) {
9227       int Idx = SVN->getMaskElt(i);
9228       if (Idx >= (int)NumElts) Idx -= NumElts;
9229       NewMask.push_back(Idx);
9230     }
9231     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
9232                                 &NewMask[0]);
9233   }
9234
9235   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9236   if (N0.getOpcode() == ISD::UNDEF) {
9237     SmallVector<int, 8> NewMask;
9238     for (unsigned i = 0; i != NumElts; ++i) {
9239       int Idx = SVN->getMaskElt(i);
9240       if (Idx >= 0) {
9241         if (Idx < (int)NumElts)
9242           Idx += NumElts;
9243         else
9244           Idx -= NumElts;
9245       }
9246       NewMask.push_back(Idx);
9247     }
9248     return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
9249                                 &NewMask[0]);
9250   }
9251
9252   // Remove references to rhs if it is undef
9253   if (N1.getOpcode() == ISD::UNDEF) {
9254     bool Changed = false;
9255     SmallVector<int, 8> NewMask;
9256     for (unsigned i = 0; i != NumElts; ++i) {
9257       int Idx = SVN->getMaskElt(i);
9258       if (Idx >= (int)NumElts) {
9259         Idx = -1;
9260         Changed = true;
9261       }
9262       NewMask.push_back(Idx);
9263     }
9264     if (Changed)
9265       return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
9266   }
9267
9268   // If it is a splat, check if the argument vector is another splat or a
9269   // build_vector with all scalar elements the same.
9270   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9271     SDNode *V = N0.getNode();
9272
9273     // If this is a bit convert that changes the element type of the vector but
9274     // not the number of vector elements, look through it.  Be careful not to
9275     // look though conversions that change things like v4f32 to v2f64.
9276     if (V->getOpcode() == ISD::BITCAST) {
9277       SDValue ConvInput = V->getOperand(0);
9278       if (ConvInput.getValueType().isVector() &&
9279           ConvInput.getValueType().getVectorNumElements() == NumElts)
9280         V = ConvInput.getNode();
9281     }
9282
9283     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9284       assert(V->getNumOperands() == NumElts &&
9285              "BUILD_VECTOR has wrong number of operands");
9286       SDValue Base;
9287       bool AllSame = true;
9288       for (unsigned i = 0; i != NumElts; ++i) {
9289         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9290           Base = V->getOperand(i);
9291           break;
9292         }
9293       }
9294       // Splat of <u, u, u, u>, return <u, u, u, u>
9295       if (!Base.getNode())
9296         return N0;
9297       for (unsigned i = 0; i != NumElts; ++i) {
9298         if (V->getOperand(i) != Base) {
9299           AllSame = false;
9300           break;
9301         }
9302       }
9303       // Splat of <x, x, x, x>, return <x, x, x, x>
9304       if (AllSame)
9305         return N0;
9306     }
9307   }
9308
9309   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9310       Level < AfterLegalizeVectorOps &&
9311       (N1.getOpcode() == ISD::UNDEF ||
9312       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9313        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9314     SDValue V = partitionShuffleOfConcats(N, DAG);
9315
9316     if (V.getNode())
9317       return V;
9318   }
9319
9320   // If this shuffle node is simply a swizzle of another shuffle node,
9321   // and it reverses the swizzle of the previous shuffle then we can
9322   // optimize shuffle(shuffle(x, undef), undef) -> x.
9323   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9324       N1.getOpcode() == ISD::UNDEF) {
9325
9326     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9327
9328     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9329     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9330       return SDValue();
9331
9332     // The incoming shuffle must be of the same type as the result of the
9333     // current shuffle.
9334     assert(OtherSV->getOperand(0).getValueType() == VT &&
9335            "Shuffle types don't match");
9336
9337     for (unsigned i = 0; i != NumElts; ++i) {
9338       int Idx = SVN->getMaskElt(i);
9339       assert(Idx < (int)NumElts && "Index references undef operand");
9340       // Next, this index comes from the first value, which is the incoming
9341       // shuffle. Adopt the incoming index.
9342       if (Idx >= 0)
9343         Idx = OtherSV->getMaskElt(Idx);
9344
9345       // The combined shuffle must map each index to itself.
9346       if (Idx >= 0 && (unsigned)Idx != i)
9347         return SDValue();
9348     }
9349
9350     return OtherSV->getOperand(0);
9351   }
9352
9353   return SDValue();
9354 }
9355
9356 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9357 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9358 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9359 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9360 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9361   EVT VT = N->getValueType(0);
9362   DebugLoc dl = N->getDebugLoc();
9363   SDValue LHS = N->getOperand(0);
9364   SDValue RHS = N->getOperand(1);
9365   if (N->getOpcode() == ISD::AND) {
9366     if (RHS.getOpcode() == ISD::BITCAST)
9367       RHS = RHS.getOperand(0);
9368     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9369       SmallVector<int, 8> Indices;
9370       unsigned NumElts = RHS.getNumOperands();
9371       for (unsigned i = 0; i != NumElts; ++i) {
9372         SDValue Elt = RHS.getOperand(i);
9373         if (!isa<ConstantSDNode>(Elt))
9374           return SDValue();
9375
9376         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9377           Indices.push_back(i);
9378         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9379           Indices.push_back(NumElts);
9380         else
9381           return SDValue();
9382       }
9383
9384       // Let's see if the target supports this vector_shuffle.
9385       EVT RVT = RHS.getValueType();
9386       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9387         return SDValue();
9388
9389       // Return the new VECTOR_SHUFFLE node.
9390       EVT EltVT = RVT.getVectorElementType();
9391       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9392                                      DAG.getConstant(0, EltVT));
9393       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9394                                  RVT, &ZeroOps[0], ZeroOps.size());
9395       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9396       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9397       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9398     }
9399   }
9400
9401   return SDValue();
9402 }
9403
9404 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9405 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9406   assert(N->getValueType(0).isVector() &&
9407          "SimplifyVBinOp only works on vectors!");
9408
9409   SDValue LHS = N->getOperand(0);
9410   SDValue RHS = N->getOperand(1);
9411   SDValue Shuffle = XformToShuffleWithZero(N);
9412   if (Shuffle.getNode()) return Shuffle;
9413
9414   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9415   // this operation.
9416   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9417       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9418     SmallVector<SDValue, 8> Ops;
9419     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9420       SDValue LHSOp = LHS.getOperand(i);
9421       SDValue RHSOp = RHS.getOperand(i);
9422       // If these two elements can't be folded, bail out.
9423       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9424            LHSOp.getOpcode() != ISD::Constant &&
9425            LHSOp.getOpcode() != ISD::ConstantFP) ||
9426           (RHSOp.getOpcode() != ISD::UNDEF &&
9427            RHSOp.getOpcode() != ISD::Constant &&
9428            RHSOp.getOpcode() != ISD::ConstantFP))
9429         break;
9430
9431       // Can't fold divide by zero.
9432       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9433           N->getOpcode() == ISD::FDIV) {
9434         if ((RHSOp.getOpcode() == ISD::Constant &&
9435              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9436             (RHSOp.getOpcode() == ISD::ConstantFP &&
9437              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9438           break;
9439       }
9440
9441       EVT VT = LHSOp.getValueType();
9442       EVT RVT = RHSOp.getValueType();
9443       if (RVT != VT) {
9444         // Integer BUILD_VECTOR operands may have types larger than the element
9445         // size (e.g., when the element type is not legal).  Prior to type
9446         // legalization, the types may not match between the two BUILD_VECTORS.
9447         // Truncate one of the operands to make them match.
9448         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9449           RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
9450         } else {
9451           LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
9452           VT = RVT;
9453         }
9454       }
9455       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
9456                                    LHSOp, RHSOp);
9457       if (FoldOp.getOpcode() != ISD::UNDEF &&
9458           FoldOp.getOpcode() != ISD::Constant &&
9459           FoldOp.getOpcode() != ISD::ConstantFP)
9460         break;
9461       Ops.push_back(FoldOp);
9462       AddToWorkList(FoldOp.getNode());
9463     }
9464
9465     if (Ops.size() == LHS.getNumOperands())
9466       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9467                          LHS.getValueType(), &Ops[0], Ops.size());
9468   }
9469
9470   return SDValue();
9471 }
9472
9473 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9474 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9475   assert(N->getValueType(0).isVector() &&
9476          "SimplifyVUnaryOp only works on vectors!");
9477
9478   SDValue N0 = N->getOperand(0);
9479
9480   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9481     return SDValue();
9482
9483   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9484   SmallVector<SDValue, 8> Ops;
9485   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9486     SDValue Op = N0.getOperand(i);
9487     if (Op.getOpcode() != ISD::UNDEF &&
9488         Op.getOpcode() != ISD::ConstantFP)
9489       break;
9490     EVT EltVT = Op.getValueType();
9491     SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
9492     if (FoldOp.getOpcode() != ISD::UNDEF &&
9493         FoldOp.getOpcode() != ISD::ConstantFP)
9494       break;
9495     Ops.push_back(FoldOp);
9496     AddToWorkList(FoldOp.getNode());
9497   }
9498
9499   if (Ops.size() != N0.getNumOperands())
9500     return SDValue();
9501
9502   return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
9503                      N0.getValueType(), &Ops[0], Ops.size());
9504 }
9505
9506 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
9507                                     SDValue N1, SDValue N2){
9508   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9509
9510   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9511                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9512
9513   // If we got a simplified select_cc node back from SimplifySelectCC, then
9514   // break it down into a new SETCC node, and a new SELECT node, and then return
9515   // the SELECT node, since we were called with a SELECT node.
9516   if (SCC.getNode()) {
9517     // Check to see if we got a select_cc back (to turn into setcc/select).
9518     // Otherwise, just return whatever node we got back, like fabs.
9519     if (SCC.getOpcode() == ISD::SELECT_CC) {
9520       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
9521                                   N0.getValueType(),
9522                                   SCC.getOperand(0), SCC.getOperand(1),
9523                                   SCC.getOperand(4));
9524       AddToWorkList(SETCC.getNode());
9525       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
9526                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
9527     }
9528
9529     return SCC;
9530   }
9531   return SDValue();
9532 }
9533
9534 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9535 /// are the two values being selected between, see if we can simplify the
9536 /// select.  Callers of this should assume that TheSelect is deleted if this
9537 /// returns true.  As such, they should return the appropriate thing (e.g. the
9538 /// node) back to the top-level of the DAG combiner loop to avoid it being
9539 /// looked at.
9540 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9541                                     SDValue RHS) {
9542
9543   // Cannot simplify select with vector condition
9544   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9545
9546   // If this is a select from two identical things, try to pull the operation
9547   // through the select.
9548   if (LHS.getOpcode() != RHS.getOpcode() ||
9549       !LHS.hasOneUse() || !RHS.hasOneUse())
9550     return false;
9551
9552   // If this is a load and the token chain is identical, replace the select
9553   // of two loads with a load through a select of the address to load from.
9554   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9555   // constants have been dropped into the constant pool.
9556   if (LHS.getOpcode() == ISD::LOAD) {
9557     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9558     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9559
9560     // Token chains must be identical.
9561     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9562         // Do not let this transformation reduce the number of volatile loads.
9563         LLD->isVolatile() || RLD->isVolatile() ||
9564         // If this is an EXTLOAD, the VT's must match.
9565         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9566         // If this is an EXTLOAD, the kind of extension must match.
9567         (LLD->getExtensionType() != RLD->getExtensionType() &&
9568          // The only exception is if one of the extensions is anyext.
9569          LLD->getExtensionType() != ISD::EXTLOAD &&
9570          RLD->getExtensionType() != ISD::EXTLOAD) ||
9571         // FIXME: this discards src value information.  This is
9572         // over-conservative. It would be beneficial to be able to remember
9573         // both potential memory locations.  Since we are discarding
9574         // src value info, don't do the transformation if the memory
9575         // locations are not in the default address space.
9576         LLD->getPointerInfo().getAddrSpace() != 0 ||
9577         RLD->getPointerInfo().getAddrSpace() != 0 ||
9578         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9579                                       LLD->getBasePtr().getValueType()))
9580       return false;
9581
9582     // Check that the select condition doesn't reach either load.  If so,
9583     // folding this will induce a cycle into the DAG.  If not, this is safe to
9584     // xform, so create a select of the addresses.
9585     SDValue Addr;
9586     if (TheSelect->getOpcode() == ISD::SELECT) {
9587       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9588       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9589           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9590         return false;
9591       // The loads must not depend on one another.
9592       if (LLD->isPredecessorOf(RLD) ||
9593           RLD->isPredecessorOf(LLD))
9594         return false;
9595       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
9596                          LLD->getBasePtr().getValueType(),
9597                          TheSelect->getOperand(0), LLD->getBasePtr(),
9598                          RLD->getBasePtr());
9599     } else {  // Otherwise SELECT_CC
9600       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9601       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9602
9603       if ((LLD->hasAnyUseOfValue(1) &&
9604            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9605           (RLD->hasAnyUseOfValue(1) &&
9606            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9607         return false;
9608
9609       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
9610                          LLD->getBasePtr().getValueType(),
9611                          TheSelect->getOperand(0),
9612                          TheSelect->getOperand(1),
9613                          LLD->getBasePtr(), RLD->getBasePtr(),
9614                          TheSelect->getOperand(4));
9615     }
9616
9617     SDValue Load;
9618     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9619       Load = DAG.getLoad(TheSelect->getValueType(0),
9620                          TheSelect->getDebugLoc(),
9621                          // FIXME: Discards pointer info.
9622                          LLD->getChain(), Addr, MachinePointerInfo(),
9623                          LLD->isVolatile(), LLD->isNonTemporal(),
9624                          LLD->isInvariant(), LLD->getAlignment());
9625     } else {
9626       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9627                             RLD->getExtensionType() : LLD->getExtensionType(),
9628                             TheSelect->getDebugLoc(),
9629                             TheSelect->getValueType(0),
9630                             // FIXME: Discards pointer info.
9631                             LLD->getChain(), Addr, MachinePointerInfo(),
9632                             LLD->getMemoryVT(), LLD->isVolatile(),
9633                             LLD->isNonTemporal(), LLD->getAlignment());
9634     }
9635
9636     // Users of the select now use the result of the load.
9637     CombineTo(TheSelect, Load);
9638
9639     // Users of the old loads now use the new load's chain.  We know the
9640     // old-load value is dead now.
9641     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9642     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9643     return true;
9644   }
9645
9646   return false;
9647 }
9648
9649 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9650 /// where 'cond' is the comparison specified by CC.
9651 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
9652                                       SDValue N2, SDValue N3,
9653                                       ISD::CondCode CC, bool NotExtCompare) {
9654   // (x ? y : y) -> y.
9655   if (N2 == N3) return N2;
9656
9657   EVT VT = N2.getValueType();
9658   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9659   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9660   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9661
9662   // Determine if the condition we're dealing with is constant
9663   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
9664                               N0, N1, CC, DL, false);
9665   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9666   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9667
9668   // fold select_cc true, x, y -> x
9669   if (SCCC && !SCCC->isNullValue())
9670     return N2;
9671   // fold select_cc false, x, y -> y
9672   if (SCCC && SCCC->isNullValue())
9673     return N3;
9674
9675   // Check to see if we can simplify the select into an fabs node
9676   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9677     // Allow either -0.0 or 0.0
9678     if (CFP->getValueAPF().isZero()) {
9679       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9680       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9681           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9682           N2 == N3.getOperand(0))
9683         return DAG.getNode(ISD::FABS, DL, VT, N0);
9684
9685       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9686       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9687           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9688           N2.getOperand(0) == N3)
9689         return DAG.getNode(ISD::FABS, DL, VT, N3);
9690     }
9691   }
9692
9693   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9694   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9695   // in it.  This is a win when the constant is not otherwise available because
9696   // it replaces two constant pool loads with one.  We only do this if the FP
9697   // type is known to be legal, because if it isn't, then we are before legalize
9698   // types an we want the other legalization to happen first (e.g. to avoid
9699   // messing with soft float) and if the ConstantFP is not legal, because if
9700   // it is legal, we may not need to store the FP constant in a constant pool.
9701   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9702     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9703       if (TLI.isTypeLegal(N2.getValueType()) &&
9704           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9705            TargetLowering::Legal) &&
9706           // If both constants have multiple uses, then we won't need to do an
9707           // extra load, they are likely around in registers for other users.
9708           (TV->hasOneUse() || FV->hasOneUse())) {
9709         Constant *Elts[] = {
9710           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9711           const_cast<ConstantFP*>(TV->getConstantFPValue())
9712         };
9713         Type *FPTy = Elts[0]->getType();
9714         const DataLayout &TD = *TLI.getDataLayout();
9715
9716         // Create a ConstantArray of the two constants.
9717         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9718         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9719                                             TD.getPrefTypeAlignment(FPTy));
9720         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9721
9722         // Get the offsets to the 0 and 1 element of the array so that we can
9723         // select between them.
9724         SDValue Zero = DAG.getIntPtrConstant(0);
9725         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9726         SDValue One = DAG.getIntPtrConstant(EltSize);
9727
9728         SDValue Cond = DAG.getSetCC(DL,
9729                                     TLI.getSetCCResultType(N0.getValueType()),
9730                                     N0, N1, CC);
9731         AddToWorkList(Cond.getNode());
9732         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
9733                                         Cond, One, Zero);
9734         AddToWorkList(CstOffset.getNode());
9735         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
9736                             CstOffset);
9737         AddToWorkList(CPIdx.getNode());
9738         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9739                            MachinePointerInfo::getConstantPool(), false,
9740                            false, false, Alignment);
9741
9742       }
9743     }
9744
9745   // Check to see if we can perform the "gzip trick", transforming
9746   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9747   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9748       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9749        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9750     EVT XType = N0.getValueType();
9751     EVT AType = N2.getValueType();
9752     if (XType.bitsGE(AType)) {
9753       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9754       // single-bit constant.
9755       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9756         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9757         ShCtV = XType.getSizeInBits()-ShCtV-1;
9758         SDValue ShCt = DAG.getConstant(ShCtV,
9759                                        getShiftAmountTy(N0.getValueType()));
9760         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
9761                                     XType, N0, ShCt);
9762         AddToWorkList(Shift.getNode());
9763
9764         if (XType.bitsGT(AType)) {
9765           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9766           AddToWorkList(Shift.getNode());
9767         }
9768
9769         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9770       }
9771
9772       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
9773                                   XType, N0,
9774                                   DAG.getConstant(XType.getSizeInBits()-1,
9775                                          getShiftAmountTy(N0.getValueType())));
9776       AddToWorkList(Shift.getNode());
9777
9778       if (XType.bitsGT(AType)) {
9779         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9780         AddToWorkList(Shift.getNode());
9781       }
9782
9783       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9784     }
9785   }
9786
9787   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9788   // where y is has a single bit set.
9789   // A plaintext description would be, we can turn the SELECT_CC into an AND
9790   // when the condition can be materialized as an all-ones register.  Any
9791   // single bit-test can be materialized as an all-ones register with
9792   // shift-left and shift-right-arith.
9793   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
9794       N0->getValueType(0) == VT &&
9795       N1C && N1C->isNullValue() &&
9796       N2C && N2C->isNullValue()) {
9797     SDValue AndLHS = N0->getOperand(0);
9798     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
9799     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
9800       // Shift the tested bit over the sign bit.
9801       APInt AndMask = ConstAndRHS->getAPIntValue();
9802       SDValue ShlAmt =
9803         DAG.getConstant(AndMask.countLeadingZeros(),
9804                         getShiftAmountTy(AndLHS.getValueType()));
9805       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
9806
9807       // Now arithmetic right shift it all the way over, so the result is either
9808       // all-ones, or zero.
9809       SDValue ShrAmt =
9810         DAG.getConstant(AndMask.getBitWidth()-1,
9811                         getShiftAmountTy(Shl.getValueType()));
9812       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
9813
9814       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
9815     }
9816   }
9817
9818   // fold select C, 16, 0 -> shl C, 4
9819   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
9820     TLI.getBooleanContents(N0.getValueType().isVector()) ==
9821       TargetLowering::ZeroOrOneBooleanContent) {
9822
9823     // If the caller doesn't want us to simplify this into a zext of a compare,
9824     // don't do it.
9825     if (NotExtCompare && N2C->getAPIntValue() == 1)
9826       return SDValue();
9827
9828     // Get a SetCC of the condition
9829     // NOTE: Don't create a SETCC if it's not legal on this target.
9830     if (!LegalOperations ||
9831         TLI.isOperationLegal(ISD::SETCC,
9832           LegalTypes ? TLI.getSetCCResultType(N0.getValueType()) : MVT::i1)) {
9833       SDValue Temp, SCC;
9834       // cast from setcc result type to select result type
9835       if (LegalTypes) {
9836         SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
9837                             N0, N1, CC);
9838         if (N2.getValueType().bitsLT(SCC.getValueType()))
9839           Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(),
9840                                         N2.getValueType());
9841         else
9842           Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9843                              N2.getValueType(), SCC);
9844       } else {
9845         SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
9846         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
9847                            N2.getValueType(), SCC);
9848       }
9849
9850       AddToWorkList(SCC.getNode());
9851       AddToWorkList(Temp.getNode());
9852
9853       if (N2C->getAPIntValue() == 1)
9854         return Temp;
9855
9856       // shl setcc result by log2 n2c
9857       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
9858                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
9859                                          getShiftAmountTy(Temp.getValueType())));
9860     }
9861   }
9862
9863   // Check to see if this is the equivalent of setcc
9864   // FIXME: Turn all of these into setcc if setcc if setcc is legal
9865   // otherwise, go ahead with the folds.
9866   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
9867     EVT XType = N0.getValueType();
9868     if (!LegalOperations ||
9869         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
9870       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
9871       if (Res.getValueType() != VT)
9872         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
9873       return Res;
9874     }
9875
9876     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
9877     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
9878         (!LegalOperations ||
9879          TLI.isOperationLegal(ISD::CTLZ, XType))) {
9880       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
9881       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
9882                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
9883                                        getShiftAmountTy(Ctlz.getValueType())));
9884     }
9885     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
9886     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
9887       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
9888                                   XType, DAG.getConstant(0, XType), N0);
9889       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
9890       return DAG.getNode(ISD::SRL, DL, XType,
9891                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
9892                          DAG.getConstant(XType.getSizeInBits()-1,
9893                                          getShiftAmountTy(XType)));
9894     }
9895     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
9896     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
9897       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
9898                                  DAG.getConstant(XType.getSizeInBits()-1,
9899                                          getShiftAmountTy(N0.getValueType())));
9900       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
9901     }
9902   }
9903
9904   // Check to see if this is an integer abs.
9905   // select_cc setg[te] X,  0,  X, -X ->
9906   // select_cc setgt    X, -1,  X, -X ->
9907   // select_cc setl[te] X,  0, -X,  X ->
9908   // select_cc setlt    X,  1, -X,  X ->
9909   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
9910   if (N1C) {
9911     ConstantSDNode *SubC = NULL;
9912     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
9913          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
9914         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
9915       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
9916     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
9917               (N1C->isOne() && CC == ISD::SETLT)) &&
9918              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
9919       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
9920
9921     EVT XType = N0.getValueType();
9922     if (SubC && SubC->isNullValue() && XType.isInteger()) {
9923       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
9924                                   N0,
9925                                   DAG.getConstant(XType.getSizeInBits()-1,
9926                                          getShiftAmountTy(N0.getValueType())));
9927       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
9928                                 XType, N0, Shift);
9929       AddToWorkList(Shift.getNode());
9930       AddToWorkList(Add.getNode());
9931       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
9932     }
9933   }
9934
9935   return SDValue();
9936 }
9937
9938 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
9939 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
9940                                    SDValue N1, ISD::CondCode Cond,
9941                                    DebugLoc DL, bool foldBooleans) {
9942   TargetLowering::DAGCombinerInfo
9943     DagCombineInfo(DAG, Level, false, this);
9944   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
9945 }
9946
9947 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
9948 /// return a DAG expression to select that will generate the same value by
9949 /// multiplying by a magic number.  See:
9950 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9951 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
9952   std::vector<SDNode*> Built;
9953   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
9954
9955   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9956        ii != ee; ++ii)
9957     AddToWorkList(*ii);
9958   return S;
9959 }
9960
9961 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
9962 /// return a DAG expression to select that will generate the same value by
9963 /// multiplying by a magic number.  See:
9964 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
9965 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
9966   std::vector<SDNode*> Built;
9967   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
9968
9969   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
9970        ii != ee; ++ii)
9971     AddToWorkList(*ii);
9972   return S;
9973 }
9974
9975 /// FindBaseOffset - Return true if base is a frame index, which is known not
9976 // to alias with anything but itself.  Provides base object and offset as
9977 // results.
9978 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
9979                            const GlobalValue *&GV, const void *&CV) {
9980   // Assume it is a primitive operation.
9981   Base = Ptr; Offset = 0; GV = 0; CV = 0;
9982
9983   // If it's an adding a simple constant then integrate the offset.
9984   if (Base.getOpcode() == ISD::ADD) {
9985     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
9986       Base = Base.getOperand(0);
9987       Offset += C->getZExtValue();
9988     }
9989   }
9990
9991   // Return the underlying GlobalValue, and update the Offset.  Return false
9992   // for GlobalAddressSDNode since the same GlobalAddress may be represented
9993   // by multiple nodes with different offsets.
9994   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
9995     GV = G->getGlobal();
9996     Offset += G->getOffset();
9997     return false;
9998   }
9999
10000   // Return the underlying Constant value, and update the Offset.  Return false
10001   // for ConstantSDNodes since the same constant pool entry may be represented
10002   // by multiple nodes with different offsets.
10003   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10004     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10005                                          : (const void *)C->getConstVal();
10006     Offset += C->getOffset();
10007     return false;
10008   }
10009   // If it's any of the following then it can't alias with anything but itself.
10010   return isa<FrameIndexSDNode>(Base);
10011 }
10012
10013 /// isAlias - Return true if there is any possibility that the two addresses
10014 /// overlap.
10015 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10016                           const Value *SrcValue1, int SrcValueOffset1,
10017                           unsigned SrcValueAlign1,
10018                           const MDNode *TBAAInfo1,
10019                           SDValue Ptr2, int64_t Size2,
10020                           const Value *SrcValue2, int SrcValueOffset2,
10021                           unsigned SrcValueAlign2,
10022                           const MDNode *TBAAInfo2) const {
10023   // If they are the same then they must be aliases.
10024   if (Ptr1 == Ptr2) return true;
10025
10026   // Gather base node and offset information.
10027   SDValue Base1, Base2;
10028   int64_t Offset1, Offset2;
10029   const GlobalValue *GV1, *GV2;
10030   const void *CV1, *CV2;
10031   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10032   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10033
10034   // If they have a same base address then check to see if they overlap.
10035   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10036     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10037
10038   // It is possible for different frame indices to alias each other, mostly
10039   // when tail call optimization reuses return address slots for arguments.
10040   // To catch this case, look up the actual index of frame indices to compute
10041   // the real alias relationship.
10042   if (isFrameIndex1 && isFrameIndex2) {
10043     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10044     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10045     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10046     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10047   }
10048
10049   // Otherwise, if we know what the bases are, and they aren't identical, then
10050   // we know they cannot alias.
10051   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10052     return false;
10053
10054   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10055   // compared to the size and offset of the access, we may be able to prove they
10056   // do not alias.  This check is conservative for now to catch cases created by
10057   // splitting vector types.
10058   if ((SrcValueAlign1 == SrcValueAlign2) &&
10059       (SrcValueOffset1 != SrcValueOffset2) &&
10060       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10061     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10062     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10063
10064     // There is no overlap between these relatively aligned accesses of similar
10065     // size, return no alias.
10066     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10067       return false;
10068   }
10069
10070   if (CombinerGlobalAA) {
10071     // Use alias analysis information.
10072     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10073     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10074     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10075     AliasAnalysis::AliasResult AAResult =
10076       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10077                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10078     if (AAResult == AliasAnalysis::NoAlias)
10079       return false;
10080   }
10081
10082   // Otherwise we have to assume they alias.
10083   return true;
10084 }
10085
10086 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10087   SDValue Ptr0, Ptr1;
10088   int64_t Size0, Size1;
10089   const Value *SrcValue0, *SrcValue1;
10090   int SrcValueOffset0, SrcValueOffset1;
10091   unsigned SrcValueAlign0, SrcValueAlign1;
10092   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10093   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10094                 SrcValueAlign0, SrcTBAAInfo0);
10095   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10096                 SrcValueAlign1, SrcTBAAInfo1);
10097   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10098                  SrcValueAlign0, SrcTBAAInfo0,
10099                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10100                  SrcValueAlign1, SrcTBAAInfo1);
10101 }
10102
10103 /// FindAliasInfo - Extracts the relevant alias information from the memory
10104 /// node.  Returns true if the operand was a load.
10105 bool DAGCombiner::FindAliasInfo(SDNode *N,
10106                                 SDValue &Ptr, int64_t &Size,
10107                                 const Value *&SrcValue,
10108                                 int &SrcValueOffset,
10109                                 unsigned &SrcValueAlign,
10110                                 const MDNode *&TBAAInfo) const {
10111   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10112
10113   Ptr = LS->getBasePtr();
10114   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10115   SrcValue = LS->getSrcValue();
10116   SrcValueOffset = LS->getSrcValueOffset();
10117   SrcValueAlign = LS->getOriginalAlignment();
10118   TBAAInfo = LS->getTBAAInfo();
10119   return isa<LoadSDNode>(LS);
10120 }
10121
10122 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10123 /// looking for aliasing nodes and adding them to the Aliases vector.
10124 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10125                                    SmallVector<SDValue, 8> &Aliases) {
10126   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10127   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10128
10129   // Get alias information for node.
10130   SDValue Ptr;
10131   int64_t Size;
10132   const Value *SrcValue;
10133   int SrcValueOffset;
10134   unsigned SrcValueAlign;
10135   const MDNode *SrcTBAAInfo;
10136   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10137                               SrcValueAlign, SrcTBAAInfo);
10138
10139   // Starting off.
10140   Chains.push_back(OriginalChain);
10141   unsigned Depth = 0;
10142
10143   // Look at each chain and determine if it is an alias.  If so, add it to the
10144   // aliases list.  If not, then continue up the chain looking for the next
10145   // candidate.
10146   while (!Chains.empty()) {
10147     SDValue Chain = Chains.back();
10148     Chains.pop_back();
10149
10150     // For TokenFactor nodes, look at each operand and only continue up the
10151     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10152     // find more and revert to original chain since the xform is unlikely to be
10153     // profitable.
10154     //
10155     // FIXME: The depth check could be made to return the last non-aliasing
10156     // chain we found before we hit a tokenfactor rather than the original
10157     // chain.
10158     if (Depth > 6 || Aliases.size() == 2) {
10159       Aliases.clear();
10160       Aliases.push_back(OriginalChain);
10161       break;
10162     }
10163
10164     // Don't bother if we've been before.
10165     if (!Visited.insert(Chain.getNode()))
10166       continue;
10167
10168     switch (Chain.getOpcode()) {
10169     case ISD::EntryToken:
10170       // Entry token is ideal chain operand, but handled in FindBetterChain.
10171       break;
10172
10173     case ISD::LOAD:
10174     case ISD::STORE: {
10175       // Get alias information for Chain.
10176       SDValue OpPtr;
10177       int64_t OpSize;
10178       const Value *OpSrcValue;
10179       int OpSrcValueOffset;
10180       unsigned OpSrcValueAlign;
10181       const MDNode *OpSrcTBAAInfo;
10182       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10183                                     OpSrcValue, OpSrcValueOffset,
10184                                     OpSrcValueAlign,
10185                                     OpSrcTBAAInfo);
10186
10187       // If chain is alias then stop here.
10188       if (!(IsLoad && IsOpLoad) &&
10189           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10190                   SrcTBAAInfo,
10191                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10192                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10193         Aliases.push_back(Chain);
10194       } else {
10195         // Look further up the chain.
10196         Chains.push_back(Chain.getOperand(0));
10197         ++Depth;
10198       }
10199       break;
10200     }
10201
10202     case ISD::TokenFactor:
10203       // We have to check each of the operands of the token factor for "small"
10204       // token factors, so we queue them up.  Adding the operands to the queue
10205       // (stack) in reverse order maintains the original order and increases the
10206       // likelihood that getNode will find a matching token factor (CSE.)
10207       if (Chain.getNumOperands() > 16) {
10208         Aliases.push_back(Chain);
10209         break;
10210       }
10211       for (unsigned n = Chain.getNumOperands(); n;)
10212         Chains.push_back(Chain.getOperand(--n));
10213       ++Depth;
10214       break;
10215
10216     default:
10217       // For all other instructions we will just have to take what we can get.
10218       Aliases.push_back(Chain);
10219       break;
10220     }
10221   }
10222 }
10223
10224 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10225 /// for a better chain (aliasing node.)
10226 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10227   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10228
10229   // Accumulate all the aliases to this node.
10230   GatherAllAliases(N, OldChain, Aliases);
10231
10232   // If no operands then chain to entry token.
10233   if (Aliases.size() == 0)
10234     return DAG.getEntryNode();
10235
10236   // If a single operand then chain to it.  We don't need to revisit it.
10237   if (Aliases.size() == 1)
10238     return Aliases[0];
10239
10240   // Construct a custom tailored token factor.
10241   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
10242                      &Aliases[0], Aliases.size());
10243 }
10244
10245 // SelectionDAG::Combine - This is the entry point for the file.
10246 //
10247 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10248                            CodeGenOpt::Level OptLevel) {
10249   /// run - This is the main entry point to this class.
10250   ///
10251   DAGCombiner(*this, AA, OptLevel).Run(Level);
10252 }