[DAGCombiner] Slightly improve readability of matchRotateSub
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Enable DAG combiner alias-analysis heuristics"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 //   1. Stack coloring does not update TBAA when merging allocas
61 //   2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 //      Because BasicAA does not handle inttoptr, we'll often miss basic type
63 //      punning idioms that we need to catch so we don't miscompile real-world
64 //      code.
65   static cl::opt<bool>
66     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67                cl::desc("Enable DAG combiner's use of TBAA"));
68
69 #ifndef NDEBUG
70   static cl::opt<std::string>
71     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72                cl::desc("Only use DAG-combiner alias analysis in this"
73                         " function"));
74 #endif
75
76   /// Hidden option to stress test load slicing, i.e., when this option
77   /// is enabled, load slicing bypasses most of its profitability guards.
78   static cl::opt<bool>
79   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80                     cl::desc("Bypass the profitability model of load "
81                              "slicing"),
82                     cl::init(false));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     // Worklist of all of the nodes that need to be simplified.
96     //
97     // This has the semantics that when adding to the worklist,
98     // the item added must be next to be processed. It should
99     // also only appear once. The naive approach to this takes
100     // linear time.
101     //
102     // To reduce the insert/remove time to logarithmic, we use
103     // a set and a vector to maintain our worklist.
104     //
105     // The set contains the items on the worklist, but does not
106     // maintain the order they should be visited.
107     //
108     // The vector maintains the order nodes should be visited, but may
109     // contain duplicate or removed nodes. When choosing a node to
110     // visit, we pop off the order stack until we find an item that is
111     // also in the contents set. All operations are O(log N).
112     SmallPtrSet<SDNode*, 64> WorkListContents;
113     SmallVector<SDNode*, 64> WorkListOrder;
114
115     // AA - Used for DAG load/store alias analysis.
116     AliasAnalysis &AA;
117
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(SDNode *N) {
123       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
124            UI != UE; ++UI)
125         AddToWorkList(*UI);
126     }
127
128     /// visit - call the node-specific routine that knows how to fold each
129     /// particular type of node.
130     SDValue visit(SDNode *N);
131
132   public:
133     /// AddToWorkList - Add to the work list making sure its instance is at the
134     /// back (next to be processed.)
135     void AddToWorkList(SDNode *N) {
136       WorkListContents.insert(N);
137       WorkListOrder.push_back(N);
138     }
139
140     /// removeFromWorkList - remove all instances of N from the worklist.
141     ///
142     void removeFromWorkList(SDNode *N) {
143       WorkListContents.erase(N);
144     }
145
146     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
147                       bool AddTo = true);
148
149     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150       return CombineTo(N, &Res, 1, AddTo);
151     }
152
153     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
154                       bool AddTo = true) {
155       SDValue To[] = { Res0, Res1 };
156       return CombineTo(N, To, 2, AddTo);
157     }
158
159     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
160
161   private:
162
163     /// SimplifyDemandedBits - Check the specified integer node value to see if
164     /// it can be simplified or if things it uses can be simplified by bit
165     /// propagation.  If so, return true.
166     bool SimplifyDemandedBits(SDValue Op) {
167       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168       APInt Demanded = APInt::getAllOnesValue(BitWidth);
169       return SimplifyDemandedBits(Op, Demanded);
170     }
171
172     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
173
174     bool CombineToPreIndexedLoadStore(SDNode *N);
175     bool CombineToPostIndexedLoadStore(SDNode *N);
176     bool SliceUpLoad(SDNode *N);
177
178     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182     SDValue PromoteIntBinOp(SDValue Op);
183     SDValue PromoteIntShiftOp(SDValue Op);
184     SDValue PromoteExtend(SDValue Op);
185     bool PromoteLoad(SDValue Op);
186
187     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189                          ISD::NodeType ExtType);
190
191     /// combine - call the node-specific routine that knows how to fold each
192     /// particular type of node. If that doesn't do anything, try the
193     /// target-specific DAG combines.
194     SDValue combine(SDNode *N);
195
196     // Visitation implementation - Implement dag node combining for different
197     // node types.  The semantics are as follows:
198     // Return Value:
199     //   SDValue.getNode() == 0 - No change was made
200     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
201     //   otherwise              - N should be replaced by the returned Operand.
202     //
203     SDValue visitTokenFactor(SDNode *N);
204     SDValue visitMERGE_VALUES(SDNode *N);
205     SDValue visitADD(SDNode *N);
206     SDValue visitSUB(SDNode *N);
207     SDValue visitADDC(SDNode *N);
208     SDValue visitSUBC(SDNode *N);
209     SDValue visitADDE(SDNode *N);
210     SDValue visitSUBE(SDNode *N);
211     SDValue visitMUL(SDNode *N);
212     SDValue visitSDIV(SDNode *N);
213     SDValue visitUDIV(SDNode *N);
214     SDValue visitSREM(SDNode *N);
215     SDValue visitUREM(SDNode *N);
216     SDValue visitMULHU(SDNode *N);
217     SDValue visitMULHS(SDNode *N);
218     SDValue visitSMUL_LOHI(SDNode *N);
219     SDValue visitUMUL_LOHI(SDNode *N);
220     SDValue visitSMULO(SDNode *N);
221     SDValue visitUMULO(SDNode *N);
222     SDValue visitSDIVREM(SDNode *N);
223     SDValue visitUDIVREM(SDNode *N);
224     SDValue visitAND(SDNode *N);
225     SDValue visitOR(SDNode *N);
226     SDValue visitXOR(SDNode *N);
227     SDValue SimplifyVBinOp(SDNode *N);
228     SDValue SimplifyVUnaryOp(SDNode *N);
229     SDValue visitSHL(SDNode *N);
230     SDValue visitSRA(SDNode *N);
231     SDValue visitSRL(SDNode *N);
232     SDValue visitCTLZ(SDNode *N);
233     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234     SDValue visitCTTZ(SDNode *N);
235     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236     SDValue visitCTPOP(SDNode *N);
237     SDValue visitSELECT(SDNode *N);
238     SDValue visitVSELECT(SDNode *N);
239     SDValue visitSELECT_CC(SDNode *N);
240     SDValue visitSETCC(SDNode *N);
241     SDValue visitSIGN_EXTEND(SDNode *N);
242     SDValue visitZERO_EXTEND(SDNode *N);
243     SDValue visitANY_EXTEND(SDNode *N);
244     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245     SDValue visitTRUNCATE(SDNode *N);
246     SDValue visitBITCAST(SDNode *N);
247     SDValue visitBUILD_PAIR(SDNode *N);
248     SDValue visitFADD(SDNode *N);
249     SDValue visitFSUB(SDNode *N);
250     SDValue visitFMUL(SDNode *N);
251     SDValue visitFMA(SDNode *N);
252     SDValue visitFDIV(SDNode *N);
253     SDValue visitFREM(SDNode *N);
254     SDValue visitFCOPYSIGN(SDNode *N);
255     SDValue visitSINT_TO_FP(SDNode *N);
256     SDValue visitUINT_TO_FP(SDNode *N);
257     SDValue visitFP_TO_SINT(SDNode *N);
258     SDValue visitFP_TO_UINT(SDNode *N);
259     SDValue visitFP_ROUND(SDNode *N);
260     SDValue visitFP_ROUND_INREG(SDNode *N);
261     SDValue visitFP_EXTEND(SDNode *N);
262     SDValue visitFNEG(SDNode *N);
263     SDValue visitFABS(SDNode *N);
264     SDValue visitFCEIL(SDNode *N);
265     SDValue visitFTRUNC(SDNode *N);
266     SDValue visitFFLOOR(SDNode *N);
267     SDValue visitBRCOND(SDNode *N);
268     SDValue visitBR_CC(SDNode *N);
269     SDValue visitLOAD(SDNode *N);
270     SDValue visitSTORE(SDNode *N);
271     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273     SDValue visitBUILD_VECTOR(SDNode *N);
274     SDValue visitCONCAT_VECTORS(SDNode *N);
275     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276     SDValue visitVECTOR_SHUFFLE(SDNode *N);
277     SDValue visitINSERT_SUBVECTOR(SDNode *N);
278
279     SDValue XformToShuffleWithZero(SDNode *N);
280     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
281
282     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
283
284     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288                              SDValue N3, ISD::CondCode CC,
289                              bool NotExtCompare = false);
290     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291                           SDLoc DL, bool foldBooleans = true);
292     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293                                          unsigned HiOp);
294     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296     SDValue BuildSDIV(SDNode *N);
297     SDValue BuildUDIV(SDNode *N);
298     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299                                bool DemandHighBits = true);
300     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302                               SDValue InnerPos, SDValue InnerNeg,
303                               unsigned PosOpcode, unsigned NegOpcode,
304                               SDLoc DL);
305     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306     SDValue ReduceLoadWidth(SDNode *N);
307     SDValue ReduceLoadOpStoreWidth(SDNode *N);
308     SDValue TransformFPLoadStorePair(SDNode *N);
309     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311
312     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313
314     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315     /// looking for aliasing nodes and adding them to the Aliases vector.
316     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317                           SmallVectorImpl<SDValue> &Aliases);
318
319     /// isAlias - Return true if there is any possibility that the two addresses
320     /// overlap.
321     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
322                  const Value *SrcValue1, int SrcValueOffset1,
323                  unsigned SrcValueAlign1,
324                  const MDNode *TBAAInfo1,
325                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
326                  const Value *SrcValue2, int SrcValueOffset2,
327                  unsigned SrcValueAlign2,
328                  const MDNode *TBAAInfo2) const;
329
330     /// isAlias - Return true if there is any possibility that the two addresses
331     /// overlap.
332     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
333
334     /// FindAliasInfo - Extracts the relevant alias information from the memory
335     /// node.  Returns true if the operand was a load.
336     bool FindAliasInfo(SDNode *N,
337                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
338                        const Value *&SrcValue, int &SrcValueOffset,
339                        unsigned &SrcValueAlignment,
340                        const MDNode *&TBAAInfo) const;
341
342     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343     /// looking for a better chain (aliasing node.)
344     SDValue FindBetterChain(SDNode *N, SDValue Chain);
345
346     /// Merge consecutive store operations into a wide store.
347     /// This optimization uses wide integers or vectors when possible.
348     /// \return True if some memory operations were changed.
349     bool MergeConsecutiveStores(StoreSDNode *N);
350
351     /// \brief Try to transform a truncation where C is a constant:
352     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
353     ///
354     /// \p N needs to be a truncation and its first operand an AND. Other
355     /// requirements are checked by the function (e.g. that trunc is
356     /// single-use) and if missed an empty SDValue is returned.
357     SDValue distributeTruncateThroughAnd(SDNode *N);
358
359   public:
360     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363       AttributeSet FnAttrs =
364           DAG.getMachineFunction().getFunction()->getAttributes();
365       ForCodeSize =
366           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367                                Attribute::OptimizeForSize) ||
368           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369     }
370
371     /// Run - runs the dag combiner on all nodes in the work list
372     void Run(CombineLevel AtLevel);
373
374     SelectionDAG &getDAG() const { return DAG; }
375
376     /// getShiftAmountTy - Returns a type large enough to hold any valid
377     /// shift amount - before type legalization these can be huge.
378     EVT getShiftAmountTy(EVT LHSTy) {
379       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380       if (LHSTy.isVector())
381         return LHSTy;
382       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383                         : TLI.getPointerTy();
384     }
385
386     /// isTypeLegal - This method returns true if we are running before type
387     /// legalization or if the specified VT is legal.
388     bool isTypeLegal(const EVT &VT) {
389       if (!LegalTypes) return true;
390       return TLI.isTypeLegal(VT);
391     }
392
393     /// getSetCCResultType - Convenience wrapper around
394     /// TargetLowering::getSetCCResultType
395     EVT getSetCCResultType(EVT VT) const {
396       return TLI.getSetCCResultType(*DAG.getContext(), VT);
397     }
398   };
399 }
400
401
402 namespace {
403 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
406   DAGCombiner &DC;
407 public:
408   explicit WorkListRemover(DAGCombiner &dc)
409     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
410
411   virtual void NodeDeleted(SDNode *N, SDNode *E) {
412     DC.removeFromWorkList(N);
413   }
414 };
415 }
416
417 //===----------------------------------------------------------------------===//
418 //  TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
420
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422   ((DAGCombiner*)DC)->AddToWorkList(N);
423 }
424
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426   ((DAGCombiner*)DC)->removeFromWorkList(N);
427 }
428
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
437 }
438
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
443 }
444
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448 }
449
450 //===----------------------------------------------------------------------===//
451 // Helper Functions
452 //===----------------------------------------------------------------------===//
453
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458                                const TargetLowering &TLI,
459                                const TargetOptions *Options,
460                                unsigned Depth = 0) {
461   // fneg is removable even if it has multiple uses.
462   if (Op.getOpcode() == ISD::FNEG) return 2;
463
464   // Don't allow anything with multiple uses.
465   if (!Op.hasOneUse()) return 0;
466
467   // Don't recurse exponentially.
468   if (Depth > 6) return 0;
469
470   switch (Op.getOpcode()) {
471   default: return false;
472   case ISD::ConstantFP:
473     // Don't invert constant FP values after legalize.  The negated constant
474     // isn't necessarily legal.
475     return LegalOperations ? 0 : 1;
476   case ISD::FADD:
477     // FIXME: determine better conditions for this xform.
478     if (!Options->UnsafeFPMath) return 0;
479
480     // After operation legalization, it might not be legal to create new FSUBs.
481     if (LegalOperations &&
482         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
483       return 0;
484
485     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487                                     Options, Depth + 1))
488       return V;
489     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
491                               Depth + 1);
492   case ISD::FSUB:
493     // We can't turn -(A-B) into B-A when we honor signed zeros.
494     if (!Options->UnsafeFPMath) return 0;
495
496     // fold (fneg (fsub A, B)) -> (fsub B, A)
497     return 1;
498
499   case ISD::FMUL:
500   case ISD::FDIV:
501     if (Options->HonorSignDependentRoundingFPMath()) return 0;
502
503     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505                                     Options, Depth + 1))
506       return V;
507
508     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
509                               Depth + 1);
510
511   case ISD::FP_EXTEND:
512   case ISD::FP_ROUND:
513   case ISD::FSIN:
514     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
515                               Depth + 1);
516   }
517 }
518
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522                                     bool LegalOperations, unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
525
526   // Don't allow anything with multiple uses.
527   assert(Op.hasOneUse() && "Unknown reuse!");
528
529   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530   switch (Op.getOpcode()) {
531   default: llvm_unreachable("Unknown code");
532   case ISD::ConstantFP: {
533     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534     V.changeSign();
535     return DAG.getConstantFP(V, Op.getValueType());
536   }
537   case ISD::FADD:
538     // FIXME: determine better conditions for this xform.
539     assert(DAG.getTarget().Options.UnsafeFPMath);
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                        GetNegatedExpression(Op.getOperand(1), DAG,
552                                             LegalOperations, Depth+1),
553                        Op.getOperand(0));
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     assert(DAG.getTarget().Options.UnsafeFPMath);
557
558     // fold (fneg (fsub 0, B)) -> B
559     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560       if (N0CFP->getValueAPF().isZero())
561         return Op.getOperand(1);
562
563     // fold (fneg (fsub A, B)) -> (fsub B, A)
564     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565                        Op.getOperand(1), Op.getOperand(0));
566
567   case ISD::FMUL:
568   case ISD::FDIV:
569     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
570
571     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573                            DAG.getTargetLoweringInfo(),
574                            &DAG.getTarget().Options, Depth+1))
575       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576                          GetNegatedExpression(Op.getOperand(0), DAG,
577                                               LegalOperations, Depth+1),
578                          Op.getOperand(1));
579
580     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
582                        Op.getOperand(0),
583                        GetNegatedExpression(Op.getOperand(1), DAG,
584                                             LegalOperations, Depth+1));
585
586   case ISD::FP_EXTEND:
587   case ISD::FSIN:
588     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589                        GetNegatedExpression(Op.getOperand(0), DAG,
590                                             LegalOperations, Depth+1));
591   case ISD::FP_ROUND:
592       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593                          GetNegatedExpression(Op.getOperand(0), DAG,
594                                               LegalOperations, Depth+1),
595                          Op.getOperand(1));
596   }
597 }
598
599
600 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
601 // that selects between the values 1 and 0, making it equivalent to a setcc.
602 // Also, set the incoming LHS, RHS, and CC references to the appropriate
603 // nodes based on the type of node we are checking.  This simplifies life a
604 // bit for the callers.
605 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
606                               SDValue &CC) {
607   if (N.getOpcode() == ISD::SETCC) {
608     LHS = N.getOperand(0);
609     RHS = N.getOperand(1);
610     CC  = N.getOperand(2);
611     return true;
612   }
613   if (N.getOpcode() == ISD::SELECT_CC &&
614       N.getOperand(2).getOpcode() == ISD::Constant &&
615       N.getOperand(3).getOpcode() == ISD::Constant &&
616       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
617       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
618     LHS = N.getOperand(0);
619     RHS = N.getOperand(1);
620     CC  = N.getOperand(4);
621     return true;
622   }
623   return false;
624 }
625
626 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
627 // one use.  If this is true, it allows the users to invert the operation for
628 // free when it is profitable to do so.
629 static bool isOneUseSetCC(SDValue N) {
630   SDValue N0, N1, N2;
631   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
632     return true;
633   return false;
634 }
635
636 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638   if (isa<ConstantSDNode>(N))
639     return N.getNode();
640   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641   if(BV && BV->isConstant())
642     return BV;
643   return NULL;
644 }
645
646 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
647                                     SDValue N0, SDValue N1) {
648   EVT VT = N0.getValueType();
649   if (N0.getOpcode() == Opc) {
650     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
651       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
652         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
653         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
654         if (!OpNode.getNode())
655           return SDValue();
656         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
657       }
658       if (N0.hasOneUse()) {
659         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
660         // use
661         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
662         if (!OpNode.getNode())
663           return SDValue();
664         AddToWorkList(OpNode.getNode());
665         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
666       }
667     }
668   }
669
670   if (N1.getOpcode() == Opc) {
671     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
672       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
673         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
674         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
675         if (!OpNode.getNode())
676           return SDValue();
677         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
678       }
679       if (N1.hasOneUse()) {
680         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
681         // use
682         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
683         if (!OpNode.getNode())
684           return SDValue();
685         AddToWorkList(OpNode.getNode());
686         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
687       }
688     }
689   }
690
691   return SDValue();
692 }
693
694 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
695                                bool AddTo) {
696   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
697   ++NodesCombined;
698   DEBUG(dbgs() << "\nReplacing.1 ";
699         N->dump(&DAG);
700         dbgs() << "\nWith: ";
701         To[0].getNode()->dump(&DAG);
702         dbgs() << " and " << NumTo-1 << " other values\n";
703         for (unsigned i = 0, e = NumTo; i != e; ++i)
704           assert((!To[i].getNode() ||
705                   N->getValueType(i) == To[i].getValueType()) &&
706                  "Cannot combine value to value of different type!"));
707   WorkListRemover DeadNodes(*this);
708   DAG.ReplaceAllUsesWith(N, To);
709   if (AddTo) {
710     // Push the new nodes and any users onto the worklist
711     for (unsigned i = 0, e = NumTo; i != e; ++i) {
712       if (To[i].getNode()) {
713         AddToWorkList(To[i].getNode());
714         AddUsersToWorkList(To[i].getNode());
715       }
716     }
717   }
718
719   // Finally, if the node is now dead, remove it from the graph.  The node
720   // may not be dead if the replacement process recursively simplified to
721   // something else needing this node.
722   if (N->use_empty()) {
723     // Nodes can be reintroduced into the worklist.  Make sure we do not
724     // process a node that has been replaced.
725     removeFromWorkList(N);
726
727     // Finally, since the node is now dead, remove it from the graph.
728     DAG.DeleteNode(N);
729   }
730   return SDValue(N, 0);
731 }
732
733 void DAGCombiner::
734 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
735   // Replace all uses.  If any nodes become isomorphic to other nodes and
736   // are deleted, make sure to remove them from our worklist.
737   WorkListRemover DeadNodes(*this);
738   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
739
740   // Push the new node and any (possibly new) users onto the worklist.
741   AddToWorkList(TLO.New.getNode());
742   AddUsersToWorkList(TLO.New.getNode());
743
744   // Finally, if the node is now dead, remove it from the graph.  The node
745   // may not be dead if the replacement process recursively simplified to
746   // something else needing this node.
747   if (TLO.Old.getNode()->use_empty()) {
748     removeFromWorkList(TLO.Old.getNode());
749
750     // If the operands of this node are only used by the node, they will now
751     // be dead.  Make sure to visit them first to delete dead nodes early.
752     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
753       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
754         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
755
756     DAG.DeleteNode(TLO.Old.getNode());
757   }
758 }
759
760 /// SimplifyDemandedBits - Check the specified integer node value to see if
761 /// it can be simplified or if things it uses can be simplified by bit
762 /// propagation.  If so, return true.
763 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
764   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
765   APInt KnownZero, KnownOne;
766   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
767     return false;
768
769   // Revisit the node.
770   AddToWorkList(Op.getNode());
771
772   // Replace the old value with the new one.
773   ++NodesCombined;
774   DEBUG(dbgs() << "\nReplacing.2 ";
775         TLO.Old.getNode()->dump(&DAG);
776         dbgs() << "\nWith: ";
777         TLO.New.getNode()->dump(&DAG);
778         dbgs() << '\n');
779
780   CommitTargetLoweringOpt(TLO);
781   return true;
782 }
783
784 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
785   SDLoc dl(Load);
786   EVT VT = Load->getValueType(0);
787   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
788
789   DEBUG(dbgs() << "\nReplacing.9 ";
790         Load->dump(&DAG);
791         dbgs() << "\nWith: ";
792         Trunc.getNode()->dump(&DAG);
793         dbgs() << '\n');
794   WorkListRemover DeadNodes(*this);
795   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
796   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
797   removeFromWorkList(Load);
798   DAG.DeleteNode(Load);
799   AddToWorkList(Trunc.getNode());
800 }
801
802 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
803   Replace = false;
804   SDLoc dl(Op);
805   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
806     EVT MemVT = LD->getMemoryVT();
807     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
808       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
809                                                   : ISD::EXTLOAD)
810       : LD->getExtensionType();
811     Replace = true;
812     return DAG.getExtLoad(ExtType, dl, PVT,
813                           LD->getChain(), LD->getBasePtr(),
814                           MemVT, LD->getMemOperand());
815   }
816
817   unsigned Opc = Op.getOpcode();
818   switch (Opc) {
819   default: break;
820   case ISD::AssertSext:
821     return DAG.getNode(ISD::AssertSext, dl, PVT,
822                        SExtPromoteOperand(Op.getOperand(0), PVT),
823                        Op.getOperand(1));
824   case ISD::AssertZext:
825     return DAG.getNode(ISD::AssertZext, dl, PVT,
826                        ZExtPromoteOperand(Op.getOperand(0), PVT),
827                        Op.getOperand(1));
828   case ISD::Constant: {
829     unsigned ExtOpc =
830       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
831     return DAG.getNode(ExtOpc, dl, PVT, Op);
832   }
833   }
834
835   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
836     return SDValue();
837   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
838 }
839
840 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
841   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
842     return SDValue();
843   EVT OldVT = Op.getValueType();
844   SDLoc dl(Op);
845   bool Replace = false;
846   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
847   if (NewOp.getNode() == 0)
848     return SDValue();
849   AddToWorkList(NewOp.getNode());
850
851   if (Replace)
852     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
853   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
854                      DAG.getValueType(OldVT));
855 }
856
857 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
858   EVT OldVT = Op.getValueType();
859   SDLoc dl(Op);
860   bool Replace = false;
861   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
862   if (NewOp.getNode() == 0)
863     return SDValue();
864   AddToWorkList(NewOp.getNode());
865
866   if (Replace)
867     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
868   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
869 }
870
871 /// PromoteIntBinOp - Promote the specified integer binary operation if the
872 /// target indicates it is beneficial. e.g. On x86, it's usually better to
873 /// promote i16 operations to i32 since i16 instructions are longer.
874 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
875   if (!LegalOperations)
876     return SDValue();
877
878   EVT VT = Op.getValueType();
879   if (VT.isVector() || !VT.isInteger())
880     return SDValue();
881
882   // If operation type is 'undesirable', e.g. i16 on x86, consider
883   // promoting it.
884   unsigned Opc = Op.getOpcode();
885   if (TLI.isTypeDesirableForOp(Opc, VT))
886     return SDValue();
887
888   EVT PVT = VT;
889   // Consult target whether it is a good idea to promote this operation and
890   // what's the right type to promote it to.
891   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
892     assert(PVT != VT && "Don't know what type to promote to!");
893
894     bool Replace0 = false;
895     SDValue N0 = Op.getOperand(0);
896     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
897     if (NN0.getNode() == 0)
898       return SDValue();
899
900     bool Replace1 = false;
901     SDValue N1 = Op.getOperand(1);
902     SDValue NN1;
903     if (N0 == N1)
904       NN1 = NN0;
905     else {
906       NN1 = PromoteOperand(N1, PVT, Replace1);
907       if (NN1.getNode() == 0)
908         return SDValue();
909     }
910
911     AddToWorkList(NN0.getNode());
912     if (NN1.getNode())
913       AddToWorkList(NN1.getNode());
914
915     if (Replace0)
916       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
917     if (Replace1)
918       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
919
920     DEBUG(dbgs() << "\nPromoting ";
921           Op.getNode()->dump(&DAG));
922     SDLoc dl(Op);
923     return DAG.getNode(ISD::TRUNCATE, dl, VT,
924                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
925   }
926   return SDValue();
927 }
928
929 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
930 /// target indicates it is beneficial. e.g. On x86, it's usually better to
931 /// promote i16 operations to i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
933   if (!LegalOperations)
934     return SDValue();
935
936   EVT VT = Op.getValueType();
937   if (VT.isVector() || !VT.isInteger())
938     return SDValue();
939
940   // If operation type is 'undesirable', e.g. i16 on x86, consider
941   // promoting it.
942   unsigned Opc = Op.getOpcode();
943   if (TLI.isTypeDesirableForOp(Opc, VT))
944     return SDValue();
945
946   EVT PVT = VT;
947   // Consult target whether it is a good idea to promote this operation and
948   // what's the right type to promote it to.
949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950     assert(PVT != VT && "Don't know what type to promote to!");
951
952     bool Replace = false;
953     SDValue N0 = Op.getOperand(0);
954     if (Opc == ISD::SRA)
955       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
956     else if (Opc == ISD::SRL)
957       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
958     else
959       N0 = PromoteOperand(N0, PVT, Replace);
960     if (N0.getNode() == 0)
961       return SDValue();
962
963     AddToWorkList(N0.getNode());
964     if (Replace)
965       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
966
967     DEBUG(dbgs() << "\nPromoting ";
968           Op.getNode()->dump(&DAG));
969     SDLoc dl(Op);
970     return DAG.getNode(ISD::TRUNCATE, dl, VT,
971                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
972   }
973   return SDValue();
974 }
975
976 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
977   if (!LegalOperations)
978     return SDValue();
979
980   EVT VT = Op.getValueType();
981   if (VT.isVector() || !VT.isInteger())
982     return SDValue();
983
984   // If operation type is 'undesirable', e.g. i16 on x86, consider
985   // promoting it.
986   unsigned Opc = Op.getOpcode();
987   if (TLI.isTypeDesirableForOp(Opc, VT))
988     return SDValue();
989
990   EVT PVT = VT;
991   // Consult target whether it is a good idea to promote this operation and
992   // what's the right type to promote it to.
993   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994     assert(PVT != VT && "Don't know what type to promote to!");
995     // fold (aext (aext x)) -> (aext x)
996     // fold (aext (zext x)) -> (zext x)
997     // fold (aext (sext x)) -> (sext x)
998     DEBUG(dbgs() << "\nPromoting ";
999           Op.getNode()->dump(&DAG));
1000     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1001   }
1002   return SDValue();
1003 }
1004
1005 bool DAGCombiner::PromoteLoad(SDValue Op) {
1006   if (!LegalOperations)
1007     return false;
1008
1009   EVT VT = Op.getValueType();
1010   if (VT.isVector() || !VT.isInteger())
1011     return false;
1012
1013   // If operation type is 'undesirable', e.g. i16 on x86, consider
1014   // promoting it.
1015   unsigned Opc = Op.getOpcode();
1016   if (TLI.isTypeDesirableForOp(Opc, VT))
1017     return false;
1018
1019   EVT PVT = VT;
1020   // Consult target whether it is a good idea to promote this operation and
1021   // what's the right type to promote it to.
1022   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023     assert(PVT != VT && "Don't know what type to promote to!");
1024
1025     SDLoc dl(Op);
1026     SDNode *N = Op.getNode();
1027     LoadSDNode *LD = cast<LoadSDNode>(N);
1028     EVT MemVT = LD->getMemoryVT();
1029     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1030       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1031                                                   : ISD::EXTLOAD)
1032       : LD->getExtensionType();
1033     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1034                                    LD->getChain(), LD->getBasePtr(),
1035                                    MemVT, LD->getMemOperand());
1036     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1037
1038     DEBUG(dbgs() << "\nPromoting ";
1039           N->dump(&DAG);
1040           dbgs() << "\nTo: ";
1041           Result.getNode()->dump(&DAG);
1042           dbgs() << '\n');
1043     WorkListRemover DeadNodes(*this);
1044     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1045     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1046     removeFromWorkList(N);
1047     DAG.DeleteNode(N);
1048     AddToWorkList(Result.getNode());
1049     return true;
1050   }
1051   return false;
1052 }
1053
1054
1055 //===----------------------------------------------------------------------===//
1056 //  Main DAG Combiner implementation
1057 //===----------------------------------------------------------------------===//
1058
1059 void DAGCombiner::Run(CombineLevel AtLevel) {
1060   // set the instance variables, so that the various visit routines may use it.
1061   Level = AtLevel;
1062   LegalOperations = Level >= AfterLegalizeVectorOps;
1063   LegalTypes = Level >= AfterLegalizeTypes;
1064
1065   // Add all the dag nodes to the worklist.
1066   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1067        E = DAG.allnodes_end(); I != E; ++I)
1068     AddToWorkList(I);
1069
1070   // Create a dummy node (which is not added to allnodes), that adds a reference
1071   // to the root node, preventing it from being deleted, and tracking any
1072   // changes of the root.
1073   HandleSDNode Dummy(DAG.getRoot());
1074
1075   // The root of the dag may dangle to deleted nodes until the dag combiner is
1076   // done.  Set it to null to avoid confusion.
1077   DAG.setRoot(SDValue());
1078
1079   // while the worklist isn't empty, find a node and
1080   // try and combine it.
1081   while (!WorkListContents.empty()) {
1082     SDNode *N;
1083     // The WorkListOrder holds the SDNodes in order, but it may contain
1084     // duplicates.
1085     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1086     // worklist *should* contain, and check the node we want to visit is should
1087     // actually be visited.
1088     do {
1089       N = WorkListOrder.pop_back_val();
1090     } while (!WorkListContents.erase(N));
1091
1092     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1093     // N is deleted from the DAG, since they too may now be dead or may have a
1094     // reduced number of uses, allowing other xforms.
1095     if (N->use_empty() && N != &Dummy) {
1096       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1097         AddToWorkList(N->getOperand(i).getNode());
1098
1099       DAG.DeleteNode(N);
1100       continue;
1101     }
1102
1103     SDValue RV = combine(N);
1104
1105     if (RV.getNode() == 0)
1106       continue;
1107
1108     ++NodesCombined;
1109
1110     // If we get back the same node we passed in, rather than a new node or
1111     // zero, we know that the node must have defined multiple values and
1112     // CombineTo was used.  Since CombineTo takes care of the worklist
1113     // mechanics for us, we have no work to do in this case.
1114     if (RV.getNode() == N)
1115       continue;
1116
1117     assert(N->getOpcode() != ISD::DELETED_NODE &&
1118            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1119            "Node was deleted but visit returned new node!");
1120
1121     DEBUG(dbgs() << "\nReplacing.3 ";
1122           N->dump(&DAG);
1123           dbgs() << "\nWith: ";
1124           RV.getNode()->dump(&DAG);
1125           dbgs() << '\n');
1126
1127     // Transfer debug value.
1128     DAG.TransferDbgValues(SDValue(N, 0), RV);
1129     WorkListRemover DeadNodes(*this);
1130     if (N->getNumValues() == RV.getNode()->getNumValues())
1131       DAG.ReplaceAllUsesWith(N, RV.getNode());
1132     else {
1133       assert(N->getValueType(0) == RV.getValueType() &&
1134              N->getNumValues() == 1 && "Type mismatch");
1135       SDValue OpV = RV;
1136       DAG.ReplaceAllUsesWith(N, &OpV);
1137     }
1138
1139     // Push the new node and any users onto the worklist
1140     AddToWorkList(RV.getNode());
1141     AddUsersToWorkList(RV.getNode());
1142
1143     // Add any uses of the old node to the worklist in case this node is the
1144     // last one that uses them.  They may become dead after this node is
1145     // deleted.
1146     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1147       AddToWorkList(N->getOperand(i).getNode());
1148
1149     // Finally, if the node is now dead, remove it from the graph.  The node
1150     // may not be dead if the replacement process recursively simplified to
1151     // something else needing this node.
1152     if (N->use_empty()) {
1153       // Nodes can be reintroduced into the worklist.  Make sure we do not
1154       // process a node that has been replaced.
1155       removeFromWorkList(N);
1156
1157       // Finally, since the node is now dead, remove it from the graph.
1158       DAG.DeleteNode(N);
1159     }
1160   }
1161
1162   // If the root changed (e.g. it was a dead load, update the root).
1163   DAG.setRoot(Dummy.getValue());
1164   DAG.RemoveDeadNodes();
1165 }
1166
1167 SDValue DAGCombiner::visit(SDNode *N) {
1168   switch (N->getOpcode()) {
1169   default: break;
1170   case ISD::TokenFactor:        return visitTokenFactor(N);
1171   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1172   case ISD::ADD:                return visitADD(N);
1173   case ISD::SUB:                return visitSUB(N);
1174   case ISD::ADDC:               return visitADDC(N);
1175   case ISD::SUBC:               return visitSUBC(N);
1176   case ISD::ADDE:               return visitADDE(N);
1177   case ISD::SUBE:               return visitSUBE(N);
1178   case ISD::MUL:                return visitMUL(N);
1179   case ISD::SDIV:               return visitSDIV(N);
1180   case ISD::UDIV:               return visitUDIV(N);
1181   case ISD::SREM:               return visitSREM(N);
1182   case ISD::UREM:               return visitUREM(N);
1183   case ISD::MULHU:              return visitMULHU(N);
1184   case ISD::MULHS:              return visitMULHS(N);
1185   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1186   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1187   case ISD::SMULO:              return visitSMULO(N);
1188   case ISD::UMULO:              return visitUMULO(N);
1189   case ISD::SDIVREM:            return visitSDIVREM(N);
1190   case ISD::UDIVREM:            return visitUDIVREM(N);
1191   case ISD::AND:                return visitAND(N);
1192   case ISD::OR:                 return visitOR(N);
1193   case ISD::XOR:                return visitXOR(N);
1194   case ISD::SHL:                return visitSHL(N);
1195   case ISD::SRA:                return visitSRA(N);
1196   case ISD::SRL:                return visitSRL(N);
1197   case ISD::CTLZ:               return visitCTLZ(N);
1198   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1199   case ISD::CTTZ:               return visitCTTZ(N);
1200   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1201   case ISD::CTPOP:              return visitCTPOP(N);
1202   case ISD::SELECT:             return visitSELECT(N);
1203   case ISD::VSELECT:            return visitVSELECT(N);
1204   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1205   case ISD::SETCC:              return visitSETCC(N);
1206   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1207   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1208   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1209   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1210   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1211   case ISD::BITCAST:            return visitBITCAST(N);
1212   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1213   case ISD::FADD:               return visitFADD(N);
1214   case ISD::FSUB:               return visitFSUB(N);
1215   case ISD::FMUL:               return visitFMUL(N);
1216   case ISD::FMA:                return visitFMA(N);
1217   case ISD::FDIV:               return visitFDIV(N);
1218   case ISD::FREM:               return visitFREM(N);
1219   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1220   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1221   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1222   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1223   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1224   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1225   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1226   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1227   case ISD::FNEG:               return visitFNEG(N);
1228   case ISD::FABS:               return visitFABS(N);
1229   case ISD::FFLOOR:             return visitFFLOOR(N);
1230   case ISD::FCEIL:              return visitFCEIL(N);
1231   case ISD::FTRUNC:             return visitFTRUNC(N);
1232   case ISD::BRCOND:             return visitBRCOND(N);
1233   case ISD::BR_CC:              return visitBR_CC(N);
1234   case ISD::LOAD:               return visitLOAD(N);
1235   case ISD::STORE:              return visitSTORE(N);
1236   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1237   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1238   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1239   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1240   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1241   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1242   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1243   }
1244   return SDValue();
1245 }
1246
1247 SDValue DAGCombiner::combine(SDNode *N) {
1248   SDValue RV = visit(N);
1249
1250   // If nothing happened, try a target-specific DAG combine.
1251   if (RV.getNode() == 0) {
1252     assert(N->getOpcode() != ISD::DELETED_NODE &&
1253            "Node was deleted but visit returned NULL!");
1254
1255     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1256         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1257
1258       // Expose the DAG combiner to the target combiner impls.
1259       TargetLowering::DAGCombinerInfo
1260         DagCombineInfo(DAG, Level, false, this);
1261
1262       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1263     }
1264   }
1265
1266   // If nothing happened still, try promoting the operation.
1267   if (RV.getNode() == 0) {
1268     switch (N->getOpcode()) {
1269     default: break;
1270     case ISD::ADD:
1271     case ISD::SUB:
1272     case ISD::MUL:
1273     case ISD::AND:
1274     case ISD::OR:
1275     case ISD::XOR:
1276       RV = PromoteIntBinOp(SDValue(N, 0));
1277       break;
1278     case ISD::SHL:
1279     case ISD::SRA:
1280     case ISD::SRL:
1281       RV = PromoteIntShiftOp(SDValue(N, 0));
1282       break;
1283     case ISD::SIGN_EXTEND:
1284     case ISD::ZERO_EXTEND:
1285     case ISD::ANY_EXTEND:
1286       RV = PromoteExtend(SDValue(N, 0));
1287       break;
1288     case ISD::LOAD:
1289       if (PromoteLoad(SDValue(N, 0)))
1290         RV = SDValue(N, 0);
1291       break;
1292     }
1293   }
1294
1295   // If N is a commutative binary node, try commuting it to enable more
1296   // sdisel CSE.
1297   if (RV.getNode() == 0 &&
1298       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1299       N->getNumValues() == 1) {
1300     SDValue N0 = N->getOperand(0);
1301     SDValue N1 = N->getOperand(1);
1302
1303     // Constant operands are canonicalized to RHS.
1304     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1305       SDValue Ops[] = { N1, N0 };
1306       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1307                                             Ops, 2);
1308       if (CSENode)
1309         return SDValue(CSENode, 0);
1310     }
1311   }
1312
1313   return RV;
1314 }
1315
1316 /// getInputChainForNode - Given a node, return its input chain if it has one,
1317 /// otherwise return a null sd operand.
1318 static SDValue getInputChainForNode(SDNode *N) {
1319   if (unsigned NumOps = N->getNumOperands()) {
1320     if (N->getOperand(0).getValueType() == MVT::Other)
1321       return N->getOperand(0);
1322     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1323       return N->getOperand(NumOps-1);
1324     for (unsigned i = 1; i < NumOps-1; ++i)
1325       if (N->getOperand(i).getValueType() == MVT::Other)
1326         return N->getOperand(i);
1327   }
1328   return SDValue();
1329 }
1330
1331 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1332   // If N has two operands, where one has an input chain equal to the other,
1333   // the 'other' chain is redundant.
1334   if (N->getNumOperands() == 2) {
1335     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1336       return N->getOperand(0);
1337     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1338       return N->getOperand(1);
1339   }
1340
1341   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1342   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1343   SmallPtrSet<SDNode*, 16> SeenOps;
1344   bool Changed = false;             // If we should replace this token factor.
1345
1346   // Start out with this token factor.
1347   TFs.push_back(N);
1348
1349   // Iterate through token factors.  The TFs grows when new token factors are
1350   // encountered.
1351   for (unsigned i = 0; i < TFs.size(); ++i) {
1352     SDNode *TF = TFs[i];
1353
1354     // Check each of the operands.
1355     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1356       SDValue Op = TF->getOperand(i);
1357
1358       switch (Op.getOpcode()) {
1359       case ISD::EntryToken:
1360         // Entry tokens don't need to be added to the list. They are
1361         // rededundant.
1362         Changed = true;
1363         break;
1364
1365       case ISD::TokenFactor:
1366         if (Op.hasOneUse() &&
1367             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1368           // Queue up for processing.
1369           TFs.push_back(Op.getNode());
1370           // Clean up in case the token factor is removed.
1371           AddToWorkList(Op.getNode());
1372           Changed = true;
1373           break;
1374         }
1375         // Fall thru
1376
1377       default:
1378         // Only add if it isn't already in the list.
1379         if (SeenOps.insert(Op.getNode()))
1380           Ops.push_back(Op);
1381         else
1382           Changed = true;
1383         break;
1384       }
1385     }
1386   }
1387
1388   SDValue Result;
1389
1390   // If we've change things around then replace token factor.
1391   if (Changed) {
1392     if (Ops.empty()) {
1393       // The entry token is the only possible outcome.
1394       Result = DAG.getEntryNode();
1395     } else {
1396       // New and improved token factor.
1397       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1398                            MVT::Other, &Ops[0], Ops.size());
1399     }
1400
1401     // Don't add users to work list.
1402     return CombineTo(N, Result, false);
1403   }
1404
1405   return Result;
1406 }
1407
1408 /// MERGE_VALUES can always be eliminated.
1409 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1410   WorkListRemover DeadNodes(*this);
1411   // Replacing results may cause a different MERGE_VALUES to suddenly
1412   // be CSE'd with N, and carry its uses with it. Iterate until no
1413   // uses remain, to ensure that the node can be safely deleted.
1414   // First add the users of this node to the work list so that they
1415   // can be tried again once they have new operands.
1416   AddUsersToWorkList(N);
1417   do {
1418     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1419       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1420   } while (!N->use_empty());
1421   removeFromWorkList(N);
1422   DAG.DeleteNode(N);
1423   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1424 }
1425
1426 static
1427 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1428                               SelectionDAG &DAG) {
1429   EVT VT = N0.getValueType();
1430   SDValue N00 = N0.getOperand(0);
1431   SDValue N01 = N0.getOperand(1);
1432   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1433
1434   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1435       isa<ConstantSDNode>(N00.getOperand(1))) {
1436     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1437     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1438                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1439                                  N00.getOperand(0), N01),
1440                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1441                                  N00.getOperand(1), N01));
1442     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1443   }
1444
1445   return SDValue();
1446 }
1447
1448 SDValue DAGCombiner::visitADD(SDNode *N) {
1449   SDValue N0 = N->getOperand(0);
1450   SDValue N1 = N->getOperand(1);
1451   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1452   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1453   EVT VT = N0.getValueType();
1454
1455   // fold vector ops
1456   if (VT.isVector()) {
1457     SDValue FoldedVOp = SimplifyVBinOp(N);
1458     if (FoldedVOp.getNode()) return FoldedVOp;
1459
1460     // fold (add x, 0) -> x, vector edition
1461     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1462       return N0;
1463     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1464       return N1;
1465   }
1466
1467   // fold (add x, undef) -> undef
1468   if (N0.getOpcode() == ISD::UNDEF)
1469     return N0;
1470   if (N1.getOpcode() == ISD::UNDEF)
1471     return N1;
1472   // fold (add c1, c2) -> c1+c2
1473   if (N0C && N1C)
1474     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1475   // canonicalize constant to RHS
1476   if (N0C && !N1C)
1477     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1478   // fold (add x, 0) -> x
1479   if (N1C && N1C->isNullValue())
1480     return N0;
1481   // fold (add Sym, c) -> Sym+c
1482   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1483     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1484         GA->getOpcode() == ISD::GlobalAddress)
1485       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1486                                   GA->getOffset() +
1487                                     (uint64_t)N1C->getSExtValue());
1488   // fold ((c1-A)+c2) -> (c1+c2)-A
1489   if (N1C && N0.getOpcode() == ISD::SUB)
1490     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1491       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492                          DAG.getConstant(N1C->getAPIntValue()+
1493                                          N0C->getAPIntValue(), VT),
1494                          N0.getOperand(1));
1495   // reassociate add
1496   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1497   if (RADD.getNode() != 0)
1498     return RADD;
1499   // fold ((0-A) + B) -> B-A
1500   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1501       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1502     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1503   // fold (A + (0-B)) -> A-B
1504   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1505       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1506     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1507   // fold (A+(B-A)) -> B
1508   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1509     return N1.getOperand(0);
1510   // fold ((B-A)+A) -> B
1511   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1512     return N0.getOperand(0);
1513   // fold (A+(B-(A+C))) to (B-C)
1514   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1515       N0 == N1.getOperand(1).getOperand(0))
1516     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1517                        N1.getOperand(1).getOperand(1));
1518   // fold (A+(B-(C+A))) to (B-C)
1519   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1520       N0 == N1.getOperand(1).getOperand(1))
1521     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1522                        N1.getOperand(1).getOperand(0));
1523   // fold (A+((B-A)+or-C)) to (B+or-C)
1524   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1525       N1.getOperand(0).getOpcode() == ISD::SUB &&
1526       N0 == N1.getOperand(0).getOperand(1))
1527     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1528                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1529
1530   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1531   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1532     SDValue N00 = N0.getOperand(0);
1533     SDValue N01 = N0.getOperand(1);
1534     SDValue N10 = N1.getOperand(0);
1535     SDValue N11 = N1.getOperand(1);
1536
1537     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1538       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1540                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1541   }
1542
1543   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1544     return SDValue(N, 0);
1545
1546   // fold (a+b) -> (a|b) iff a and b share no bits.
1547   if (VT.isInteger() && !VT.isVector()) {
1548     APInt LHSZero, LHSOne;
1549     APInt RHSZero, RHSOne;
1550     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1551
1552     if (LHSZero.getBoolValue()) {
1553       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1554
1555       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1556       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1557       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1558         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1559           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1560       }
1561     }
1562   }
1563
1564   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1565   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1566     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1567     if (Result.getNode()) return Result;
1568   }
1569   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1570     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1571     if (Result.getNode()) return Result;
1572   }
1573
1574   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1575   if (N1.getOpcode() == ISD::SHL &&
1576       N1.getOperand(0).getOpcode() == ISD::SUB)
1577     if (ConstantSDNode *C =
1578           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1579       if (C->getAPIntValue() == 0)
1580         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1581                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1582                                        N1.getOperand(0).getOperand(1),
1583                                        N1.getOperand(1)));
1584   if (N0.getOpcode() == ISD::SHL &&
1585       N0.getOperand(0).getOpcode() == ISD::SUB)
1586     if (ConstantSDNode *C =
1587           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1588       if (C->getAPIntValue() == 0)
1589         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1590                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1591                                        N0.getOperand(0).getOperand(1),
1592                                        N0.getOperand(1)));
1593
1594   if (N1.getOpcode() == ISD::AND) {
1595     SDValue AndOp0 = N1.getOperand(0);
1596     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1597     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1598     unsigned DestBits = VT.getScalarType().getSizeInBits();
1599
1600     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1601     // and similar xforms where the inner op is either ~0 or 0.
1602     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1603       SDLoc DL(N);
1604       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1605     }
1606   }
1607
1608   // add (sext i1), X -> sub X, (zext i1)
1609   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1610       N0.getOperand(0).getValueType() == MVT::i1 &&
1611       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1612     SDLoc DL(N);
1613     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1614     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1615   }
1616
1617   return SDValue();
1618 }
1619
1620 SDValue DAGCombiner::visitADDC(SDNode *N) {
1621   SDValue N0 = N->getOperand(0);
1622   SDValue N1 = N->getOperand(1);
1623   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1624   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1625   EVT VT = N0.getValueType();
1626
1627   // If the flag result is dead, turn this into an ADD.
1628   if (!N->hasAnyUseOfValue(1))
1629     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1630                      DAG.getNode(ISD::CARRY_FALSE,
1631                                  SDLoc(N), MVT::Glue));
1632
1633   // canonicalize constant to RHS.
1634   if (N0C && !N1C)
1635     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1636
1637   // fold (addc x, 0) -> x + no carry out
1638   if (N1C && N1C->isNullValue())
1639     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1640                                         SDLoc(N), MVT::Glue));
1641
1642   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1643   APInt LHSZero, LHSOne;
1644   APInt RHSZero, RHSOne;
1645   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1646
1647   if (LHSZero.getBoolValue()) {
1648     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1649
1650     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1651     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1652     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1653       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1654                        DAG.getNode(ISD::CARRY_FALSE,
1655                                    SDLoc(N), MVT::Glue));
1656   }
1657
1658   return SDValue();
1659 }
1660
1661 SDValue DAGCombiner::visitADDE(SDNode *N) {
1662   SDValue N0 = N->getOperand(0);
1663   SDValue N1 = N->getOperand(1);
1664   SDValue CarryIn = N->getOperand(2);
1665   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1666   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1667
1668   // canonicalize constant to RHS
1669   if (N0C && !N1C)
1670     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1671                        N1, N0, CarryIn);
1672
1673   // fold (adde x, y, false) -> (addc x, y)
1674   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1675     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1676
1677   return SDValue();
1678 }
1679
1680 // Since it may not be valid to emit a fold to zero for vector initializers
1681 // check if we can before folding.
1682 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1683                              SelectionDAG &DAG,
1684                              bool LegalOperations, bool LegalTypes) {
1685   if (!VT.isVector())
1686     return DAG.getConstant(0, VT);
1687   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1688     return DAG.getConstant(0, VT);
1689   return SDValue();
1690 }
1691
1692 SDValue DAGCombiner::visitSUB(SDNode *N) {
1693   SDValue N0 = N->getOperand(0);
1694   SDValue N1 = N->getOperand(1);
1695   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1696   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1697   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1698     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1699   EVT VT = N0.getValueType();
1700
1701   // fold vector ops
1702   if (VT.isVector()) {
1703     SDValue FoldedVOp = SimplifyVBinOp(N);
1704     if (FoldedVOp.getNode()) return FoldedVOp;
1705
1706     // fold (sub x, 0) -> x, vector edition
1707     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1708       return N0;
1709   }
1710
1711   // fold (sub x, x) -> 0
1712   // FIXME: Refactor this and xor and other similar operations together.
1713   if (N0 == N1)
1714     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1715   // fold (sub c1, c2) -> c1-c2
1716   if (N0C && N1C)
1717     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1718   // fold (sub x, c) -> (add x, -c)
1719   if (N1C)
1720     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1721                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1722   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1723   if (N0C && N0C->isAllOnesValue())
1724     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1725   // fold A-(A-B) -> B
1726   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1727     return N1.getOperand(1);
1728   // fold (A+B)-A -> B
1729   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1730     return N0.getOperand(1);
1731   // fold (A+B)-B -> A
1732   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1733     return N0.getOperand(0);
1734   // fold C2-(A+C1) -> (C2-C1)-A
1735   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1736     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1737                                    VT);
1738     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1739                        N1.getOperand(0));
1740   }
1741   // fold ((A+(B+or-C))-B) -> A+or-C
1742   if (N0.getOpcode() == ISD::ADD &&
1743       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1744        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1745       N0.getOperand(1).getOperand(0) == N1)
1746     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1747                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1748   // fold ((A+(C+B))-B) -> A+C
1749   if (N0.getOpcode() == ISD::ADD &&
1750       N0.getOperand(1).getOpcode() == ISD::ADD &&
1751       N0.getOperand(1).getOperand(1) == N1)
1752     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1753                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1754   // fold ((A-(B-C))-C) -> A-B
1755   if (N0.getOpcode() == ISD::SUB &&
1756       N0.getOperand(1).getOpcode() == ISD::SUB &&
1757       N0.getOperand(1).getOperand(1) == N1)
1758     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1759                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1760
1761   // If either operand of a sub is undef, the result is undef
1762   if (N0.getOpcode() == ISD::UNDEF)
1763     return N0;
1764   if (N1.getOpcode() == ISD::UNDEF)
1765     return N1;
1766
1767   // If the relocation model supports it, consider symbol offsets.
1768   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1769     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1770       // fold (sub Sym, c) -> Sym-c
1771       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1772         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1773                                     GA->getOffset() -
1774                                       (uint64_t)N1C->getSExtValue());
1775       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1776       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1777         if (GA->getGlobal() == GB->getGlobal())
1778           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1779                                  VT);
1780     }
1781
1782   return SDValue();
1783 }
1784
1785 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1786   SDValue N0 = N->getOperand(0);
1787   SDValue N1 = N->getOperand(1);
1788   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790   EVT VT = N0.getValueType();
1791
1792   // If the flag result is dead, turn this into an SUB.
1793   if (!N->hasAnyUseOfValue(1))
1794     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1795                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1796                                  MVT::Glue));
1797
1798   // fold (subc x, x) -> 0 + no borrow
1799   if (N0 == N1)
1800     return CombineTo(N, DAG.getConstant(0, VT),
1801                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1802                                  MVT::Glue));
1803
1804   // fold (subc x, 0) -> x + no borrow
1805   if (N1C && N1C->isNullValue())
1806     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1807                                         MVT::Glue));
1808
1809   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1810   if (N0C && N0C->isAllOnesValue())
1811     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1812                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1813                                  MVT::Glue));
1814
1815   return SDValue();
1816 }
1817
1818 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1819   SDValue N0 = N->getOperand(0);
1820   SDValue N1 = N->getOperand(1);
1821   SDValue CarryIn = N->getOperand(2);
1822
1823   // fold (sube x, y, false) -> (subc x, y)
1824   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1825     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1826
1827   return SDValue();
1828 }
1829
1830 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1831 /// elements are all the same constant or undefined.
1832 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1833   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1834   if (!C)
1835     return false;
1836
1837   APInt SplatUndef;
1838   unsigned SplatBitSize;
1839   bool HasAnyUndefs;
1840   EVT EltVT = N->getValueType(0).getVectorElementType();
1841   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1842                              HasAnyUndefs) &&
1843           EltVT.getSizeInBits() >= SplatBitSize);
1844 }
1845
1846 SDValue DAGCombiner::visitMUL(SDNode *N) {
1847   SDValue N0 = N->getOperand(0);
1848   SDValue N1 = N->getOperand(1);
1849   EVT VT = N0.getValueType();
1850
1851   // fold (mul x, undef) -> 0
1852   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1853     return DAG.getConstant(0, VT);
1854
1855   bool N0IsConst = false;
1856   bool N1IsConst = false;
1857   APInt ConstValue0, ConstValue1;
1858   // fold vector ops
1859   if (VT.isVector()) {
1860     SDValue FoldedVOp = SimplifyVBinOp(N);
1861     if (FoldedVOp.getNode()) return FoldedVOp;
1862
1863     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1864     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1865   } else {
1866     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1867     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1868                             : APInt();
1869     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1870     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1871                             : APInt();
1872   }
1873
1874   // fold (mul c1, c2) -> c1*c2
1875   if (N0IsConst && N1IsConst)
1876     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1877
1878   // canonicalize constant to RHS
1879   if (N0IsConst && !N1IsConst)
1880     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1881   // fold (mul x, 0) -> 0
1882   if (N1IsConst && ConstValue1 == 0)
1883     return N1;
1884   // We require a splat of the entire scalar bit width for non-contiguous
1885   // bit patterns.
1886   bool IsFullSplat =
1887     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1888   // fold (mul x, 1) -> x
1889   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1890     return N0;
1891   // fold (mul x, -1) -> 0-x
1892   if (N1IsConst && ConstValue1.isAllOnesValue())
1893     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1894                        DAG.getConstant(0, VT), N0);
1895   // fold (mul x, (1 << c)) -> x << c
1896   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1897     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1898                        DAG.getConstant(ConstValue1.logBase2(),
1899                                        getShiftAmountTy(N0.getValueType())));
1900   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1901   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1902     unsigned Log2Val = (-ConstValue1).logBase2();
1903     // FIXME: If the input is something that is easily negated (e.g. a
1904     // single-use add), we should put the negate there.
1905     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906                        DAG.getConstant(0, VT),
1907                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1908                             DAG.getConstant(Log2Val,
1909                                       getShiftAmountTy(N0.getValueType()))));
1910   }
1911
1912   APInt Val;
1913   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1914   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1915       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1916                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1917     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1918                              N1, N0.getOperand(1));
1919     AddToWorkList(C3.getNode());
1920     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1921                        N0.getOperand(0), C3);
1922   }
1923
1924   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1925   // use.
1926   {
1927     SDValue Sh(0,0), Y(0,0);
1928     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1929     if (N0.getOpcode() == ISD::SHL &&
1930         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1932         N0.getNode()->hasOneUse()) {
1933       Sh = N0; Y = N1;
1934     } else if (N1.getOpcode() == ISD::SHL &&
1935                isa<ConstantSDNode>(N1.getOperand(1)) &&
1936                N1.getNode()->hasOneUse()) {
1937       Sh = N1; Y = N0;
1938     }
1939
1940     if (Sh.getNode()) {
1941       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1942                                 Sh.getOperand(0), Y);
1943       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1944                          Mul, Sh.getOperand(1));
1945     }
1946   }
1947
1948   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1949   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1950       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1951                      isa<ConstantSDNode>(N0.getOperand(1))))
1952     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1953                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1954                                    N0.getOperand(0), N1),
1955                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1956                                    N0.getOperand(1), N1));
1957
1958   // reassociate mul
1959   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1960   if (RMUL.getNode() != 0)
1961     return RMUL;
1962
1963   return SDValue();
1964 }
1965
1966 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1967   SDValue N0 = N->getOperand(0);
1968   SDValue N1 = N->getOperand(1);
1969   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1970   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1971   EVT VT = N->getValueType(0);
1972
1973   // fold vector ops
1974   if (VT.isVector()) {
1975     SDValue FoldedVOp = SimplifyVBinOp(N);
1976     if (FoldedVOp.getNode()) return FoldedVOp;
1977   }
1978
1979   // fold (sdiv c1, c2) -> c1/c2
1980   if (N0C && N1C && !N1C->isNullValue())
1981     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1982   // fold (sdiv X, 1) -> X
1983   if (N1C && N1C->getAPIntValue() == 1LL)
1984     return N0;
1985   // fold (sdiv X, -1) -> 0-X
1986   if (N1C && N1C->isAllOnesValue())
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT), N0);
1989   // If we know the sign bits of both operands are zero, strength reduce to a
1990   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1991   if (!VT.isVector()) {
1992     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1993       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1994                          N0, N1);
1995   }
1996   // fold (sdiv X, pow2) -> simple ops after legalize
1997   if (N1C && !N1C->isNullValue() &&
1998       (N1C->getAPIntValue().isPowerOf2() ||
1999        (-N1C->getAPIntValue()).isPowerOf2())) {
2000     // If dividing by powers of two is cheap, then don't perform the following
2001     // fold.
2002     if (TLI.isPow2DivCheap())
2003       return SDValue();
2004
2005     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2006
2007     // Splat the sign bit into the register
2008     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2009                               DAG.getConstant(VT.getSizeInBits()-1,
2010                                        getShiftAmountTy(N0.getValueType())));
2011     AddToWorkList(SGN.getNode());
2012
2013     // Add (N0 < 0) ? abs2 - 1 : 0;
2014     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2015                               DAG.getConstant(VT.getSizeInBits() - lg2,
2016                                        getShiftAmountTy(SGN.getValueType())));
2017     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2018     AddToWorkList(SRL.getNode());
2019     AddToWorkList(ADD.getNode());    // Divide by pow2
2020     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2021                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2022
2023     // If we're dividing by a positive value, we're done.  Otherwise, we must
2024     // negate the result.
2025     if (N1C->getAPIntValue().isNonNegative())
2026       return SRA;
2027
2028     AddToWorkList(SRA.getNode());
2029     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2030                        DAG.getConstant(0, VT), SRA);
2031   }
2032
2033   // if integer divide is expensive and we satisfy the requirements, emit an
2034   // alternate sequence.
2035   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2036     SDValue Op = BuildSDIV(N);
2037     if (Op.getNode()) return Op;
2038   }
2039
2040   // undef / X -> 0
2041   if (N0.getOpcode() == ISD::UNDEF)
2042     return DAG.getConstant(0, VT);
2043   // X / undef -> undef
2044   if (N1.getOpcode() == ISD::UNDEF)
2045     return N1;
2046
2047   return SDValue();
2048 }
2049
2050 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2051   SDValue N0 = N->getOperand(0);
2052   SDValue N1 = N->getOperand(1);
2053   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2054   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2055   EVT VT = N->getValueType(0);
2056
2057   // fold vector ops
2058   if (VT.isVector()) {
2059     SDValue FoldedVOp = SimplifyVBinOp(N);
2060     if (FoldedVOp.getNode()) return FoldedVOp;
2061   }
2062
2063   // fold (udiv c1, c2) -> c1/c2
2064   if (N0C && N1C && !N1C->isNullValue())
2065     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2066   // fold (udiv x, (1 << c)) -> x >>u c
2067   if (N1C && N1C->getAPIntValue().isPowerOf2())
2068     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2069                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2070                                        getShiftAmountTy(N0.getValueType())));
2071   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2072   if (N1.getOpcode() == ISD::SHL) {
2073     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2074       if (SHC->getAPIntValue().isPowerOf2()) {
2075         EVT ADDVT = N1.getOperand(1).getValueType();
2076         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2077                                   N1.getOperand(1),
2078                                   DAG.getConstant(SHC->getAPIntValue()
2079                                                                   .logBase2(),
2080                                                   ADDVT));
2081         AddToWorkList(Add.getNode());
2082         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2083       }
2084     }
2085   }
2086   // fold (udiv x, c) -> alternate
2087   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2088     SDValue Op = BuildUDIV(N);
2089     if (Op.getNode()) return Op;
2090   }
2091
2092   // undef / X -> 0
2093   if (N0.getOpcode() == ISD::UNDEF)
2094     return DAG.getConstant(0, VT);
2095   // X / undef -> undef
2096   if (N1.getOpcode() == ISD::UNDEF)
2097     return N1;
2098
2099   return SDValue();
2100 }
2101
2102 SDValue DAGCombiner::visitSREM(SDNode *N) {
2103   SDValue N0 = N->getOperand(0);
2104   SDValue N1 = N->getOperand(1);
2105   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2106   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2107   EVT VT = N->getValueType(0);
2108
2109   // fold (srem c1, c2) -> c1%c2
2110   if (N0C && N1C && !N1C->isNullValue())
2111     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2112   // If we know the sign bits of both operands are zero, strength reduce to a
2113   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2114   if (!VT.isVector()) {
2115     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2116       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2117   }
2118
2119   // If X/C can be simplified by the division-by-constant logic, lower
2120   // X%C to the equivalent of X-X/C*C.
2121   if (N1C && !N1C->isNullValue()) {
2122     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2123     AddToWorkList(Div.getNode());
2124     SDValue OptimizedDiv = combine(Div.getNode());
2125     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2126       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2127                                 OptimizedDiv, N1);
2128       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2129       AddToWorkList(Mul.getNode());
2130       return Sub;
2131     }
2132   }
2133
2134   // undef % X -> 0
2135   if (N0.getOpcode() == ISD::UNDEF)
2136     return DAG.getConstant(0, VT);
2137   // X % undef -> undef
2138   if (N1.getOpcode() == ISD::UNDEF)
2139     return N1;
2140
2141   return SDValue();
2142 }
2143
2144 SDValue DAGCombiner::visitUREM(SDNode *N) {
2145   SDValue N0 = N->getOperand(0);
2146   SDValue N1 = N->getOperand(1);
2147   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2148   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2149   EVT VT = N->getValueType(0);
2150
2151   // fold (urem c1, c2) -> c1%c2
2152   if (N0C && N1C && !N1C->isNullValue())
2153     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2154   // fold (urem x, pow2) -> (and x, pow2-1)
2155   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2156     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2157                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2158   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2159   if (N1.getOpcode() == ISD::SHL) {
2160     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2161       if (SHC->getAPIntValue().isPowerOf2()) {
2162         SDValue Add =
2163           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2164                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2165                                  VT));
2166         AddToWorkList(Add.getNode());
2167         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2168       }
2169     }
2170   }
2171
2172   // If X/C can be simplified by the division-by-constant logic, lower
2173   // X%C to the equivalent of X-X/C*C.
2174   if (N1C && !N1C->isNullValue()) {
2175     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2176     AddToWorkList(Div.getNode());
2177     SDValue OptimizedDiv = combine(Div.getNode());
2178     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2179       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2180                                 OptimizedDiv, N1);
2181       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2182       AddToWorkList(Mul.getNode());
2183       return Sub;
2184     }
2185   }
2186
2187   // undef % X -> 0
2188   if (N0.getOpcode() == ISD::UNDEF)
2189     return DAG.getConstant(0, VT);
2190   // X % undef -> undef
2191   if (N1.getOpcode() == ISD::UNDEF)
2192     return N1;
2193
2194   return SDValue();
2195 }
2196
2197 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2198   SDValue N0 = N->getOperand(0);
2199   SDValue N1 = N->getOperand(1);
2200   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2201   EVT VT = N->getValueType(0);
2202   SDLoc DL(N);
2203
2204   // fold (mulhs x, 0) -> 0
2205   if (N1C && N1C->isNullValue())
2206     return N1;
2207   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2208   if (N1C && N1C->getAPIntValue() == 1)
2209     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2210                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2211                                        getShiftAmountTy(N0.getValueType())));
2212   // fold (mulhs x, undef) -> 0
2213   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2214     return DAG.getConstant(0, VT);
2215
2216   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2217   // plus a shift.
2218   if (VT.isSimple() && !VT.isVector()) {
2219     MVT Simple = VT.getSimpleVT();
2220     unsigned SimpleSize = Simple.getSizeInBits();
2221     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2222     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2223       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2224       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2225       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2226       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2227             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2228       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2229     }
2230   }
2231
2232   return SDValue();
2233 }
2234
2235 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2236   SDValue N0 = N->getOperand(0);
2237   SDValue N1 = N->getOperand(1);
2238   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2239   EVT VT = N->getValueType(0);
2240   SDLoc DL(N);
2241
2242   // fold (mulhu x, 0) -> 0
2243   if (N1C && N1C->isNullValue())
2244     return N1;
2245   // fold (mulhu x, 1) -> 0
2246   if (N1C && N1C->getAPIntValue() == 1)
2247     return DAG.getConstant(0, N0.getValueType());
2248   // fold (mulhu x, undef) -> 0
2249   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2250     return DAG.getConstant(0, VT);
2251
2252   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2253   // plus a shift.
2254   if (VT.isSimple() && !VT.isVector()) {
2255     MVT Simple = VT.getSimpleVT();
2256     unsigned SimpleSize = Simple.getSizeInBits();
2257     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2258     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2259       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2260       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2261       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2262       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2263             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2264       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2265     }
2266   }
2267
2268   return SDValue();
2269 }
2270
2271 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2272 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2273 /// that are being performed. Return true if a simplification was made.
2274 ///
2275 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2276                                                 unsigned HiOp) {
2277   // If the high half is not needed, just compute the low half.
2278   bool HiExists = N->hasAnyUseOfValue(1);
2279   if (!HiExists &&
2280       (!LegalOperations ||
2281        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2282     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2283                               N->op_begin(), N->getNumOperands());
2284     return CombineTo(N, Res, Res);
2285   }
2286
2287   // If the low half is not needed, just compute the high half.
2288   bool LoExists = N->hasAnyUseOfValue(0);
2289   if (!LoExists &&
2290       (!LegalOperations ||
2291        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2292     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2293                               N->op_begin(), N->getNumOperands());
2294     return CombineTo(N, Res, Res);
2295   }
2296
2297   // If both halves are used, return as it is.
2298   if (LoExists && HiExists)
2299     return SDValue();
2300
2301   // If the two computed results can be simplified separately, separate them.
2302   if (LoExists) {
2303     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2304                              N->op_begin(), N->getNumOperands());
2305     AddToWorkList(Lo.getNode());
2306     SDValue LoOpt = combine(Lo.getNode());
2307     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2308         (!LegalOperations ||
2309          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2310       return CombineTo(N, LoOpt, LoOpt);
2311   }
2312
2313   if (HiExists) {
2314     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2315                              N->op_begin(), N->getNumOperands());
2316     AddToWorkList(Hi.getNode());
2317     SDValue HiOpt = combine(Hi.getNode());
2318     if (HiOpt.getNode() && HiOpt != Hi &&
2319         (!LegalOperations ||
2320          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2321       return CombineTo(N, HiOpt, HiOpt);
2322   }
2323
2324   return SDValue();
2325 }
2326
2327 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2328   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2329   if (Res.getNode()) return Res;
2330
2331   EVT VT = N->getValueType(0);
2332   SDLoc DL(N);
2333
2334   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2335   // plus a shift.
2336   if (VT.isSimple() && !VT.isVector()) {
2337     MVT Simple = VT.getSimpleVT();
2338     unsigned SimpleSize = Simple.getSizeInBits();
2339     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2342       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2343       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2344       // Compute the high part as N1.
2345       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2346             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2347       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2348       // Compute the low part as N0.
2349       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2350       return CombineTo(N, Lo, Hi);
2351     }
2352   }
2353
2354   return SDValue();
2355 }
2356
2357 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2358   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2359   if (Res.getNode()) return Res;
2360
2361   EVT VT = N->getValueType(0);
2362   SDLoc DL(N);
2363
2364   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2365   // plus a shift.
2366   if (VT.isSimple() && !VT.isVector()) {
2367     MVT Simple = VT.getSimpleVT();
2368     unsigned SimpleSize = Simple.getSizeInBits();
2369     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2370     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2371       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2372       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2373       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2374       // Compute the high part as N1.
2375       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2376             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2377       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2378       // Compute the low part as N0.
2379       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2380       return CombineTo(N, Lo, Hi);
2381     }
2382   }
2383
2384   return SDValue();
2385 }
2386
2387 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2388   // (smulo x, 2) -> (saddo x, x)
2389   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2390     if (C2->getAPIntValue() == 2)
2391       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2392                          N->getOperand(0), N->getOperand(0));
2393
2394   return SDValue();
2395 }
2396
2397 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2398   // (umulo x, 2) -> (uaddo x, x)
2399   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400     if (C2->getAPIntValue() == 2)
2401       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2402                          N->getOperand(0), N->getOperand(0));
2403
2404   return SDValue();
2405 }
2406
2407 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2408   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2409   if (Res.getNode()) return Res;
2410
2411   return SDValue();
2412 }
2413
2414 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2415   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2416   if (Res.getNode()) return Res;
2417
2418   return SDValue();
2419 }
2420
2421 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2422 /// two operands of the same opcode, try to simplify it.
2423 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2424   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2425   EVT VT = N0.getValueType();
2426   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2427
2428   // Bail early if none of these transforms apply.
2429   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2430
2431   // For each of OP in AND/OR/XOR:
2432   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2433   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2434   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2435   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2436   //
2437   // do not sink logical op inside of a vector extend, since it may combine
2438   // into a vsetcc.
2439   EVT Op0VT = N0.getOperand(0).getValueType();
2440   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2441        N0.getOpcode() == ISD::SIGN_EXTEND ||
2442        // Avoid infinite looping with PromoteIntBinOp.
2443        (N0.getOpcode() == ISD::ANY_EXTEND &&
2444         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2445        (N0.getOpcode() == ISD::TRUNCATE &&
2446         (!TLI.isZExtFree(VT, Op0VT) ||
2447          !TLI.isTruncateFree(Op0VT, VT)) &&
2448         TLI.isTypeLegal(Op0VT))) &&
2449       !VT.isVector() &&
2450       Op0VT == N1.getOperand(0).getValueType() &&
2451       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2452     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2453                                  N0.getOperand(0).getValueType(),
2454                                  N0.getOperand(0), N1.getOperand(0));
2455     AddToWorkList(ORNode.getNode());
2456     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2457   }
2458
2459   // For each of OP in SHL/SRL/SRA/AND...
2460   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2461   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2462   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2463   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2464        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2465       N0.getOperand(1) == N1.getOperand(1)) {
2466     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2467                                  N0.getOperand(0).getValueType(),
2468                                  N0.getOperand(0), N1.getOperand(0));
2469     AddToWorkList(ORNode.getNode());
2470     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2471                        ORNode, N0.getOperand(1));
2472   }
2473
2474   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2475   // Only perform this optimization after type legalization and before
2476   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2477   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2478   // we don't want to undo this promotion.
2479   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2480   // on scalars.
2481   if ((N0.getOpcode() == ISD::BITCAST ||
2482        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2483       Level == AfterLegalizeTypes) {
2484     SDValue In0 = N0.getOperand(0);
2485     SDValue In1 = N1.getOperand(0);
2486     EVT In0Ty = In0.getValueType();
2487     EVT In1Ty = In1.getValueType();
2488     SDLoc DL(N);
2489     // If both incoming values are integers, and the original types are the
2490     // same.
2491     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2492       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2493       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2494       AddToWorkList(Op.getNode());
2495       return BC;
2496     }
2497   }
2498
2499   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2500   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2501   // If both shuffles use the same mask, and both shuffle within a single
2502   // vector, then it is worthwhile to move the swizzle after the operation.
2503   // The type-legalizer generates this pattern when loading illegal
2504   // vector types from memory. In many cases this allows additional shuffle
2505   // optimizations.
2506   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2507       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2508       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2509     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2511
2512     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2513            "Inputs to shuffles are not the same type");
2514
2515     unsigned NumElts = VT.getVectorNumElements();
2516
2517     // Check that both shuffles use the same mask. The masks are known to be of
2518     // the same length because the result vector type is the same.
2519     bool SameMask = true;
2520     for (unsigned i = 0; i != NumElts; ++i) {
2521       int Idx0 = SVN0->getMaskElt(i);
2522       int Idx1 = SVN1->getMaskElt(i);
2523       if (Idx0 != Idx1) {
2524         SameMask = false;
2525         break;
2526       }
2527     }
2528
2529     if (SameMask) {
2530       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2531                                N0.getOperand(0), N1.getOperand(0));
2532       AddToWorkList(Op.getNode());
2533       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2534                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2535     }
2536   }
2537
2538   return SDValue();
2539 }
2540
2541 SDValue DAGCombiner::visitAND(SDNode *N) {
2542   SDValue N0 = N->getOperand(0);
2543   SDValue N1 = N->getOperand(1);
2544   SDValue LL, LR, RL, RR, CC0, CC1;
2545   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2546   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2547   EVT VT = N1.getValueType();
2548   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2549
2550   // fold vector ops
2551   if (VT.isVector()) {
2552     SDValue FoldedVOp = SimplifyVBinOp(N);
2553     if (FoldedVOp.getNode()) return FoldedVOp;
2554
2555     // fold (and x, 0) -> 0, vector edition
2556     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2557       return N0;
2558     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2559       return N1;
2560
2561     // fold (and x, -1) -> x, vector edition
2562     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2563       return N1;
2564     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2565       return N0;
2566   }
2567
2568   // fold (and x, undef) -> 0
2569   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2570     return DAG.getConstant(0, VT);
2571   // fold (and c1, c2) -> c1&c2
2572   if (N0C && N1C)
2573     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2574   // canonicalize constant to RHS
2575   if (N0C && !N1C)
2576     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2577   // fold (and x, -1) -> x
2578   if (N1C && N1C->isAllOnesValue())
2579     return N0;
2580   // if (and x, c) is known to be zero, return 0
2581   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2582                                    APInt::getAllOnesValue(BitWidth)))
2583     return DAG.getConstant(0, VT);
2584   // reassociate and
2585   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2586   if (RAND.getNode() != 0)
2587     return RAND;
2588   // fold (and (or x, C), D) -> D if (C & D) == D
2589   if (N1C && N0.getOpcode() == ISD::OR)
2590     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2591       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2592         return N1;
2593   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2594   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2595     SDValue N0Op0 = N0.getOperand(0);
2596     APInt Mask = ~N1C->getAPIntValue();
2597     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2598     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2599       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2600                                  N0.getValueType(), N0Op0);
2601
2602       // Replace uses of the AND with uses of the Zero extend node.
2603       CombineTo(N, Zext);
2604
2605       // We actually want to replace all uses of the any_extend with the
2606       // zero_extend, to avoid duplicating things.  This will later cause this
2607       // AND to be folded.
2608       CombineTo(N0.getNode(), Zext);
2609       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2610     }
2611   }
2612   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2613   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2614   // already be zero by virtue of the width of the base type of the load.
2615   //
2616   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2617   // more cases.
2618   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2619        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2620       N0.getOpcode() == ISD::LOAD) {
2621     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2622                                          N0 : N0.getOperand(0) );
2623
2624     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2625     // This can be a pure constant or a vector splat, in which case we treat the
2626     // vector as a scalar and use the splat value.
2627     APInt Constant = APInt::getNullValue(1);
2628     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2629       Constant = C->getAPIntValue();
2630     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2631       APInt SplatValue, SplatUndef;
2632       unsigned SplatBitSize;
2633       bool HasAnyUndefs;
2634       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2635                                              SplatBitSize, HasAnyUndefs);
2636       if (IsSplat) {
2637         // Undef bits can contribute to a possible optimisation if set, so
2638         // set them.
2639         SplatValue |= SplatUndef;
2640
2641         // The splat value may be something like "0x00FFFFFF", which means 0 for
2642         // the first vector value and FF for the rest, repeating. We need a mask
2643         // that will apply equally to all members of the vector, so AND all the
2644         // lanes of the constant together.
2645         EVT VT = Vector->getValueType(0);
2646         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2647
2648         // If the splat value has been compressed to a bitlength lower
2649         // than the size of the vector lane, we need to re-expand it to
2650         // the lane size.
2651         if (BitWidth > SplatBitSize)
2652           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2653                SplatBitSize < BitWidth;
2654                SplatBitSize = SplatBitSize * 2)
2655             SplatValue |= SplatValue.shl(SplatBitSize);
2656
2657         Constant = APInt::getAllOnesValue(BitWidth);
2658         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2659           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2660       }
2661     }
2662
2663     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2664     // actually legal and isn't going to get expanded, else this is a false
2665     // optimisation.
2666     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2667                                                     Load->getMemoryVT());
2668
2669     // Resize the constant to the same size as the original memory access before
2670     // extension. If it is still the AllOnesValue then this AND is completely
2671     // unneeded.
2672     Constant =
2673       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2674
2675     bool B;
2676     switch (Load->getExtensionType()) {
2677     default: B = false; break;
2678     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2679     case ISD::ZEXTLOAD:
2680     case ISD::NON_EXTLOAD: B = true; break;
2681     }
2682
2683     if (B && Constant.isAllOnesValue()) {
2684       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2685       // preserve semantics once we get rid of the AND.
2686       SDValue NewLoad(Load, 0);
2687       if (Load->getExtensionType() == ISD::EXTLOAD) {
2688         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2689                               Load->getValueType(0), SDLoc(Load),
2690                               Load->getChain(), Load->getBasePtr(),
2691                               Load->getOffset(), Load->getMemoryVT(),
2692                               Load->getMemOperand());
2693         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2694         if (Load->getNumValues() == 3) {
2695           // PRE/POST_INC loads have 3 values.
2696           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2697                            NewLoad.getValue(2) };
2698           CombineTo(Load, To, 3, true);
2699         } else {
2700           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2701         }
2702       }
2703
2704       // Fold the AND away, taking care not to fold to the old load node if we
2705       // replaced it.
2706       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2707
2708       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2709     }
2710   }
2711   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2712   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2715
2716     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717         LL.getValueType().isInteger()) {
2718       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721                                      LR.getValueType(), LL, RL);
2722         AddToWorkList(ORNode.getNode());
2723         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2724       }
2725       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728                                       LR.getValueType(), LL, RL);
2729         AddToWorkList(ANDNode.getNode());
2730         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2731       }
2732       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2733       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735                                      LR.getValueType(), LL, RL);
2736         AddToWorkList(ORNode.getNode());
2737         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2738       }
2739     }
2740     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742         Op0 == Op1 && LL.getValueType().isInteger() &&
2743       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2747       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748                                     LL, DAG.getConstant(1, LL.getValueType()));
2749       AddToWorkList(ADDNode.getNode());
2750       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2751                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2752     }
2753     // canonicalize equivalent to ll == rl
2754     if (LL == RR && LR == RL) {
2755       Op1 = ISD::getSetCCSwappedOperands(Op1);
2756       std::swap(RL, RR);
2757     }
2758     if (LL == RL && LR == RR) {
2759       bool isInteger = LL.getValueType().isInteger();
2760       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761       if (Result != ISD::SETCC_INVALID &&
2762           (!LegalOperations ||
2763            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764             TLI.isOperationLegal(ISD::SETCC,
2765                             getSetCCResultType(N0.getSimpleValueType())))))
2766         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2767                             LL, LR, Result);
2768     }
2769   }
2770
2771   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2772   if (N0.getOpcode() == N1.getOpcode()) {
2773     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2774     if (Tmp.getNode()) return Tmp;
2775   }
2776
2777   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2778   // fold (and (sra)) -> (and (srl)) when possible.
2779   if (!VT.isVector() &&
2780       SimplifyDemandedBits(SDValue(N, 0)))
2781     return SDValue(N, 0);
2782
2783   // fold (zext_inreg (extload x)) -> (zextload x)
2784   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2785     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2786     EVT MemVT = LN0->getMemoryVT();
2787     // If we zero all the possible extended bits, then we can turn this into
2788     // a zextload if we are running before legalize or the operation is legal.
2789     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2790     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2791                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2792         ((!LegalOperations && !LN0->isVolatile()) ||
2793          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2794       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2795                                        LN0->getChain(), LN0->getBasePtr(),
2796                                        MemVT, LN0->getMemOperand());
2797       AddToWorkList(N);
2798       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2799       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2800     }
2801   }
2802   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2803   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2804       N0.hasOneUse()) {
2805     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2806     EVT MemVT = LN0->getMemoryVT();
2807     // If we zero all the possible extended bits, then we can turn this into
2808     // a zextload if we are running before legalize or the operation is legal.
2809     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2810     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2811                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2812         ((!LegalOperations && !LN0->isVolatile()) ||
2813          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2814       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2815                                        LN0->getChain(), LN0->getBasePtr(),
2816                                        MemVT, LN0->getMemOperand());
2817       AddToWorkList(N);
2818       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2819       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2820     }
2821   }
2822
2823   // fold (and (load x), 255) -> (zextload x, i8)
2824   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2825   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2826   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2827               (N0.getOpcode() == ISD::ANY_EXTEND &&
2828                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2829     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2830     LoadSDNode *LN0 = HasAnyExt
2831       ? cast<LoadSDNode>(N0.getOperand(0))
2832       : cast<LoadSDNode>(N0);
2833     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2834         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2835       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2836       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2837         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2838         EVT LoadedVT = LN0->getMemoryVT();
2839
2840         if (ExtVT == LoadedVT &&
2841             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2842           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2843
2844           SDValue NewLoad =
2845             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2846                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2847                            LN0->getMemOperand());
2848           AddToWorkList(N);
2849           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2850           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2851         }
2852
2853         // Do not change the width of a volatile load.
2854         // Do not generate loads of non-round integer types since these can
2855         // be expensive (and would be wrong if the type is not byte sized).
2856         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2857             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2858           EVT PtrType = LN0->getOperand(1).getValueType();
2859
2860           unsigned Alignment = LN0->getAlignment();
2861           SDValue NewPtr = LN0->getBasePtr();
2862
2863           // For big endian targets, we need to add an offset to the pointer
2864           // to load the correct bytes.  For little endian systems, we merely
2865           // need to read fewer bytes from the same pointer.
2866           if (TLI.isBigEndian()) {
2867             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2868             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2869             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2870             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2871                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2872             Alignment = MinAlign(Alignment, PtrOff);
2873           }
2874
2875           AddToWorkList(NewPtr.getNode());
2876
2877           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2878           SDValue Load =
2879             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2880                            LN0->getChain(), NewPtr,
2881                            LN0->getPointerInfo(),
2882                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2883                            Alignment, LN0->getTBAAInfo());
2884           AddToWorkList(N);
2885           CombineTo(LN0, Load, Load.getValue(1));
2886           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2887         }
2888       }
2889     }
2890   }
2891
2892   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2893       VT.getSizeInBits() <= 64) {
2894     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2895       APInt ADDC = ADDI->getAPIntValue();
2896       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2897         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2898         // immediate for an add, but it is legal if its top c2 bits are set,
2899         // transform the ADD so the immediate doesn't need to be materialized
2900         // in a register.
2901         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2902           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2903                                              SRLI->getZExtValue());
2904           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2905             ADDC |= Mask;
2906             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2907               SDValue NewAdd =
2908                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2909                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2910               CombineTo(N0.getNode(), NewAdd);
2911               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2912             }
2913           }
2914         }
2915       }
2916     }
2917   }
2918
2919   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2920   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2921     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2922                                        N0.getOperand(1), false);
2923     if (BSwap.getNode())
2924       return BSwap;
2925   }
2926
2927   return SDValue();
2928 }
2929
2930 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2931 ///
2932 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2933                                         bool DemandHighBits) {
2934   if (!LegalOperations)
2935     return SDValue();
2936
2937   EVT VT = N->getValueType(0);
2938   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2939     return SDValue();
2940   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2941     return SDValue();
2942
2943   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2944   bool LookPassAnd0 = false;
2945   bool LookPassAnd1 = false;
2946   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2947       std::swap(N0, N1);
2948   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2949       std::swap(N0, N1);
2950   if (N0.getOpcode() == ISD::AND) {
2951     if (!N0.getNode()->hasOneUse())
2952       return SDValue();
2953     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2954     if (!N01C || N01C->getZExtValue() != 0xFF00)
2955       return SDValue();
2956     N0 = N0.getOperand(0);
2957     LookPassAnd0 = true;
2958   }
2959
2960   if (N1.getOpcode() == ISD::AND) {
2961     if (!N1.getNode()->hasOneUse())
2962       return SDValue();
2963     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2964     if (!N11C || N11C->getZExtValue() != 0xFF)
2965       return SDValue();
2966     N1 = N1.getOperand(0);
2967     LookPassAnd1 = true;
2968   }
2969
2970   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2971     std::swap(N0, N1);
2972   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2973     return SDValue();
2974   if (!N0.getNode()->hasOneUse() ||
2975       !N1.getNode()->hasOneUse())
2976     return SDValue();
2977
2978   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2979   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2980   if (!N01C || !N11C)
2981     return SDValue();
2982   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2983     return SDValue();
2984
2985   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2986   SDValue N00 = N0->getOperand(0);
2987   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2988     if (!N00.getNode()->hasOneUse())
2989       return SDValue();
2990     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2991     if (!N001C || N001C->getZExtValue() != 0xFF)
2992       return SDValue();
2993     N00 = N00.getOperand(0);
2994     LookPassAnd0 = true;
2995   }
2996
2997   SDValue N10 = N1->getOperand(0);
2998   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2999     if (!N10.getNode()->hasOneUse())
3000       return SDValue();
3001     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3002     if (!N101C || N101C->getZExtValue() != 0xFF00)
3003       return SDValue();
3004     N10 = N10.getOperand(0);
3005     LookPassAnd1 = true;
3006   }
3007
3008   if (N00 != N10)
3009     return SDValue();
3010
3011   // Make sure everything beyond the low halfword gets set to zero since the SRL
3012   // 16 will clear the top bits.
3013   unsigned OpSizeInBits = VT.getSizeInBits();
3014   if (DemandHighBits && OpSizeInBits > 16) {
3015     // If the left-shift isn't masked out then the only way this is a bswap is
3016     // if all bits beyond the low 8 are 0. In that case the entire pattern
3017     // reduces to a left shift anyway: leave it for other parts of the combiner.
3018     if (!LookPassAnd0)
3019       return SDValue();
3020
3021     // However, if the right shift isn't masked out then it might be because
3022     // it's not needed. See if we can spot that too.
3023     if (!LookPassAnd1 &&
3024         !DAG.MaskedValueIsZero(
3025             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3026       return SDValue();
3027   }
3028
3029   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3030   if (OpSizeInBits > 16)
3031     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3032                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3033   return Res;
3034 }
3035
3036 /// isBSwapHWordElement - Return true if the specified node is an element
3037 /// that makes up a 32-bit packed halfword byteswap. i.e.
3038 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3039 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3040   if (!N.getNode()->hasOneUse())
3041     return false;
3042
3043   unsigned Opc = N.getOpcode();
3044   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3045     return false;
3046
3047   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3048   if (!N1C)
3049     return false;
3050
3051   unsigned Num;
3052   switch (N1C->getZExtValue()) {
3053   default:
3054     return false;
3055   case 0xFF:       Num = 0; break;
3056   case 0xFF00:     Num = 1; break;
3057   case 0xFF0000:   Num = 2; break;
3058   case 0xFF000000: Num = 3; break;
3059   }
3060
3061   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3062   SDValue N0 = N.getOperand(0);
3063   if (Opc == ISD::AND) {
3064     if (Num == 0 || Num == 2) {
3065       // (x >> 8) & 0xff
3066       // (x >> 8) & 0xff0000
3067       if (N0.getOpcode() != ISD::SRL)
3068         return false;
3069       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070       if (!C || C->getZExtValue() != 8)
3071         return false;
3072     } else {
3073       // (x << 8) & 0xff00
3074       // (x << 8) & 0xff000000
3075       if (N0.getOpcode() != ISD::SHL)
3076         return false;
3077       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078       if (!C || C->getZExtValue() != 8)
3079         return false;
3080     }
3081   } else if (Opc == ISD::SHL) {
3082     // (x & 0xff) << 8
3083     // (x & 0xff0000) << 8
3084     if (Num != 0 && Num != 2)
3085       return false;
3086     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087     if (!C || C->getZExtValue() != 8)
3088       return false;
3089   } else { // Opc == ISD::SRL
3090     // (x & 0xff00) >> 8
3091     // (x & 0xff000000) >> 8
3092     if (Num != 1 && Num != 3)
3093       return false;
3094     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3095     if (!C || C->getZExtValue() != 8)
3096       return false;
3097   }
3098
3099   if (Parts[Num])
3100     return false;
3101
3102   Parts[Num] = N0.getOperand(0).getNode();
3103   return true;
3104 }
3105
3106 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3107 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3108 /// => (rotl (bswap x), 16)
3109 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3110   if (!LegalOperations)
3111     return SDValue();
3112
3113   EVT VT = N->getValueType(0);
3114   if (VT != MVT::i32)
3115     return SDValue();
3116   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3117     return SDValue();
3118
3119   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3120   // Look for either
3121   // (or (or (and), (and)), (or (and), (and)))
3122   // (or (or (or (and), (and)), (and)), (and))
3123   if (N0.getOpcode() != ISD::OR)
3124     return SDValue();
3125   SDValue N00 = N0.getOperand(0);
3126   SDValue N01 = N0.getOperand(1);
3127
3128   if (N1.getOpcode() == ISD::OR &&
3129       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3130     // (or (or (and), (and)), (or (and), (and)))
3131     SDValue N000 = N00.getOperand(0);
3132     if (!isBSwapHWordElement(N000, Parts))
3133       return SDValue();
3134
3135     SDValue N001 = N00.getOperand(1);
3136     if (!isBSwapHWordElement(N001, Parts))
3137       return SDValue();
3138     SDValue N010 = N01.getOperand(0);
3139     if (!isBSwapHWordElement(N010, Parts))
3140       return SDValue();
3141     SDValue N011 = N01.getOperand(1);
3142     if (!isBSwapHWordElement(N011, Parts))
3143       return SDValue();
3144   } else {
3145     // (or (or (or (and), (and)), (and)), (and))
3146     if (!isBSwapHWordElement(N1, Parts))
3147       return SDValue();
3148     if (!isBSwapHWordElement(N01, Parts))
3149       return SDValue();
3150     if (N00.getOpcode() != ISD::OR)
3151       return SDValue();
3152     SDValue N000 = N00.getOperand(0);
3153     if (!isBSwapHWordElement(N000, Parts))
3154       return SDValue();
3155     SDValue N001 = N00.getOperand(1);
3156     if (!isBSwapHWordElement(N001, Parts))
3157       return SDValue();
3158   }
3159
3160   // Make sure the parts are all coming from the same node.
3161   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3162     return SDValue();
3163
3164   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3165                               SDValue(Parts[0],0));
3166
3167   // Result of the bswap should be rotated by 16. If it's not legal, then
3168   // do  (x << 16) | (x >> 16).
3169   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3170   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3171     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3172   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3173     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3174   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3175                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3176                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3177 }
3178
3179 SDValue DAGCombiner::visitOR(SDNode *N) {
3180   SDValue N0 = N->getOperand(0);
3181   SDValue N1 = N->getOperand(1);
3182   SDValue LL, LR, RL, RR, CC0, CC1;
3183   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3184   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3185   EVT VT = N1.getValueType();
3186
3187   // fold vector ops
3188   if (VT.isVector()) {
3189     SDValue FoldedVOp = SimplifyVBinOp(N);
3190     if (FoldedVOp.getNode()) return FoldedVOp;
3191
3192     // fold (or x, 0) -> x, vector edition
3193     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3194       return N1;
3195     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3196       return N0;
3197
3198     // fold (or x, -1) -> -1, vector edition
3199     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3200       return N0;
3201     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3202       return N1;
3203
3204     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3205     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3206     // Do this only if the resulting shuffle is legal.
3207     if (isa<ShuffleVectorSDNode>(N0) &&
3208         isa<ShuffleVectorSDNode>(N1) &&
3209         N0->getOperand(1) == N1->getOperand(1) &&
3210         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3211       bool CanFold = true;
3212       unsigned NumElts = VT.getVectorNumElements();
3213       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3214       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3215       // We construct two shuffle masks:
3216       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3217       // and N1 as the second operand.
3218       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3219       // and N0 as the second operand.
3220       // We do this because OR is commutable and therefore there might be
3221       // two ways to fold this node into a shuffle.
3222       SmallVector<int,4> Mask1;
3223       SmallVector<int,4> Mask2;
3224       
3225       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3226         int M0 = SV0->getMaskElt(i);
3227         int M1 = SV1->getMaskElt(i);
3228    
3229         // Both shuffle indexes are undef. Propagate Undef.
3230         if (M0 < 0 && M1 < 0) {
3231           Mask1.push_back(M0);
3232           Mask2.push_back(M0);
3233           continue;
3234         }
3235
3236         if (M0 < 0 || M1 < 0 ||
3237             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3238             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3239           CanFold = false;
3240           break;
3241         }
3242         
3243         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3244         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3245       }
3246
3247       if (CanFold) {
3248         // Fold this sequence only if the resulting shuffle is 'legal'.
3249         if (TLI.isShuffleMaskLegal(Mask1, VT))
3250           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3251                                       N1->getOperand(0), &Mask1[0]);
3252         if (TLI.isShuffleMaskLegal(Mask2, VT))
3253           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3254                                       N0->getOperand(0), &Mask2[0]);
3255       }
3256     }
3257   }
3258
3259   // fold (or x, undef) -> -1
3260   if (!LegalOperations &&
3261       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3262     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3263     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3264   }
3265   // fold (or c1, c2) -> c1|c2
3266   if (N0C && N1C)
3267     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3268   // canonicalize constant to RHS
3269   if (N0C && !N1C)
3270     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3271   // fold (or x, 0) -> x
3272   if (N1C && N1C->isNullValue())
3273     return N0;
3274   // fold (or x, -1) -> -1
3275   if (N1C && N1C->isAllOnesValue())
3276     return N1;
3277   // fold (or x, c) -> c iff (x & ~c) == 0
3278   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3279     return N1;
3280
3281   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3282   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3283   if (BSwap.getNode() != 0)
3284     return BSwap;
3285   BSwap = MatchBSwapHWordLow(N, N0, N1);
3286   if (BSwap.getNode() != 0)
3287     return BSwap;
3288
3289   // reassociate or
3290   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3291   if (ROR.getNode() != 0)
3292     return ROR;
3293   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3294   // iff (c1 & c2) == 0.
3295   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3296              isa<ConstantSDNode>(N0.getOperand(1))) {
3297     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3298     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3299       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3300       if (!COR.getNode())
3301         return SDValue();
3302       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3303                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3304                                      N0.getOperand(0), N1), COR);
3305     }
3306   }
3307   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3308   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3309     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3310     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3311
3312     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3313         LL.getValueType().isInteger()) {
3314       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3315       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3316       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3317           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3318         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3319                                      LR.getValueType(), LL, RL);
3320         AddToWorkList(ORNode.getNode());
3321         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3322       }
3323       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3324       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3325       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3326           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3327         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3328                                       LR.getValueType(), LL, RL);
3329         AddToWorkList(ANDNode.getNode());
3330         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3331       }
3332     }
3333     // canonicalize equivalent to ll == rl
3334     if (LL == RR && LR == RL) {
3335       Op1 = ISD::getSetCCSwappedOperands(Op1);
3336       std::swap(RL, RR);
3337     }
3338     if (LL == RL && LR == RR) {
3339       bool isInteger = LL.getValueType().isInteger();
3340       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3341       if (Result != ISD::SETCC_INVALID &&
3342           (!LegalOperations ||
3343            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3344             TLI.isOperationLegal(ISD::SETCC,
3345               getSetCCResultType(N0.getValueType())))))
3346         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3347                             LL, LR, Result);
3348     }
3349   }
3350
3351   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3352   if (N0.getOpcode() == N1.getOpcode()) {
3353     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3354     if (Tmp.getNode()) return Tmp;
3355   }
3356
3357   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3358   if (N0.getOpcode() == ISD::AND &&
3359       N1.getOpcode() == ISD::AND &&
3360       N0.getOperand(1).getOpcode() == ISD::Constant &&
3361       N1.getOperand(1).getOpcode() == ISD::Constant &&
3362       // Don't increase # computations.
3363       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3364     // We can only do this xform if we know that bits from X that are set in C2
3365     // but not in C1 are already zero.  Likewise for Y.
3366     const APInt &LHSMask =
3367       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3368     const APInt &RHSMask =
3369       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3370
3371     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3372         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3373       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3374                               N0.getOperand(0), N1.getOperand(0));
3375       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3376                          DAG.getConstant(LHSMask | RHSMask, VT));
3377     }
3378   }
3379
3380   // See if this is some rotate idiom.
3381   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3382     return SDValue(Rot, 0);
3383
3384   // Simplify the operands using demanded-bits information.
3385   if (!VT.isVector() &&
3386       SimplifyDemandedBits(SDValue(N, 0)))
3387     return SDValue(N, 0);
3388
3389   return SDValue();
3390 }
3391
3392 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3393 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3394   if (Op.getOpcode() == ISD::AND) {
3395     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3396       Mask = Op.getOperand(1);
3397       Op = Op.getOperand(0);
3398     } else {
3399       return false;
3400     }
3401   }
3402
3403   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3404     Shift = Op;
3405     return true;
3406   }
3407
3408   return false;
3409 }
3410
3411 // Return true if we can prove that, whenever Neg and Pos are both in the
3412 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3413 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3414 //
3415 //     (or (shift1 X, Neg), (shift2 X, Pos))
3416 //
3417 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3418 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3419 // to consider shift amounts with defined behavior.
3420 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3421   // If OpSize is a power of 2 then:
3422   //
3423   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3424   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3425   //
3426   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3427   // for the stronger condition:
3428   //
3429   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3430   //
3431   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3432   // we can just replace Neg with Neg' for the rest of the function.
3433   //
3434   // In other cases we check for the even stronger condition:
3435   //
3436   //     Neg == OpSize - Pos                                    [B]
3437   //
3438   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3439   // behavior if Pos == 0 (and consequently Neg == OpSize).
3440   //
3441   // We could actually use [A] whenever OpSize is a power of 2, but the
3442   // only extra cases that it would match are those uninteresting ones
3443   // where Neg and Pos are never in range at the same time.  E.g. for
3444   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3445   // as well as (sub 32, Pos), but:
3446   //
3447   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3448   //
3449   // always invokes undefined behavior for 32-bit X.
3450   //
3451   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3452   unsigned MaskLoBits = 0;
3453   if (Neg.getOpcode() == ISD::AND &&
3454       isPowerOf2_64(OpSize) &&
3455       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3456       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3457     Neg = Neg.getOperand(0);
3458     MaskLoBits = Log2_64(OpSize);
3459   }
3460
3461   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3462   if (Neg.getOpcode() != ISD::SUB)
3463     return 0;
3464   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3465   if (!NegC)
3466     return 0;
3467   SDValue NegOp1 = Neg.getOperand(1);
3468
3469   // The condition we need is now:
3470   //
3471   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3472   //
3473   // If NegOp1 == Pos then we need:
3474   //
3475   //              OpSize & Mask == NegC & Mask
3476   //
3477   // (because "x & Mask" is a truncation and distributes through subtraction).
3478   APInt Width;
3479   if (Pos == NegOp1)
3480     Width = NegC->getAPIntValue();
3481   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3482   // Then the condition we want to prove becomes:
3483   //
3484   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3485   //
3486   // which, again because "x & Mask" is a truncation, becomes:
3487   //
3488   //                NegC & Mask == (OpSize - PosC) & Mask
3489   //              OpSize & Mask == (NegC + PosC) & Mask
3490   else if (Pos.getOpcode() == ISD::ADD &&
3491            Pos.getOperand(0) == NegOp1 &&
3492            Pos.getOperand(1).getOpcode() == ISD::Constant)
3493     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3494              NegC->getAPIntValue());
3495   else
3496     return false;
3497
3498   // Now we just need to check that OpSize & Mask == Width & Mask.
3499   if (MaskLoBits)
3500     // Opsize & Mask is 0 since Mask is Opsize - 1.
3501     return Width.getLoBits(MaskLoBits) == 0;
3502   return Width == OpSize;
3503 }
3504
3505 // A subroutine of MatchRotate used once we have found an OR of two opposite
3506 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3507 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3508 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3509 // Neg with outer conversions stripped away.
3510 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3511                                        SDValue Neg, SDValue InnerPos,
3512                                        SDValue InnerNeg, unsigned PosOpcode,
3513                                        unsigned NegOpcode, SDLoc DL) {
3514   // fold (or (shl x, (*ext y)),
3515   //          (srl x, (*ext (sub 32, y)))) ->
3516   //   (rotl x, y) or (rotr x, (sub 32, y))
3517   //
3518   // fold (or (shl x, (*ext (sub 32, y))),
3519   //          (srl x, (*ext y))) ->
3520   //   (rotr x, y) or (rotl x, (sub 32, y))
3521   EVT VT = Shifted.getValueType();
3522   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3523     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3524     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3525                        HasPos ? Pos : Neg).getNode();
3526   }
3527
3528   // fold (or (shl (*ext x), (*ext y)),
3529   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3530   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3531   //
3532   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3533   //          (srl (*ext x), (*ext y))) ->
3534   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3535   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3536       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3537     SDValue InnerShifted = Shifted.getOperand(0);
3538     EVT InnerVT = InnerShifted.getValueType();
3539     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3540     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3541       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3542         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3543                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3544         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3545       }
3546     }
3547   }
3548
3549   return 0;
3550 }
3551
3552 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3553 // idioms for rotate, and if the target supports rotation instructions, generate
3554 // a rot[lr].
3555 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3556   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3557   EVT VT = LHS.getValueType();
3558   if (!TLI.isTypeLegal(VT)) return 0;
3559
3560   // The target must have at least one rotate flavor.
3561   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3562   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3563   if (!HasROTL && !HasROTR) return 0;
3564
3565   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3566   SDValue LHSShift;   // The shift.
3567   SDValue LHSMask;    // AND value if any.
3568   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3569     return 0; // Not part of a rotate.
3570
3571   SDValue RHSShift;   // The shift.
3572   SDValue RHSMask;    // AND value if any.
3573   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3574     return 0; // Not part of a rotate.
3575
3576   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3577     return 0;   // Not shifting the same value.
3578
3579   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3580     return 0;   // Shifts must disagree.
3581
3582   // Canonicalize shl to left side in a shl/srl pair.
3583   if (RHSShift.getOpcode() == ISD::SHL) {
3584     std::swap(LHS, RHS);
3585     std::swap(LHSShift, RHSShift);
3586     std::swap(LHSMask , RHSMask );
3587   }
3588
3589   unsigned OpSizeInBits = VT.getSizeInBits();
3590   SDValue LHSShiftArg = LHSShift.getOperand(0);
3591   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3592   SDValue RHSShiftArg = RHSShift.getOperand(0);
3593   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3594
3595   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3596   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3597   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3598       RHSShiftAmt.getOpcode() == ISD::Constant) {
3599     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3600     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3601     if ((LShVal + RShVal) != OpSizeInBits)
3602       return 0;
3603
3604     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3605                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3606
3607     // If there is an AND of either shifted operand, apply it to the result.
3608     if (LHSMask.getNode() || RHSMask.getNode()) {
3609       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3610
3611       if (LHSMask.getNode()) {
3612         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3613         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3614       }
3615       if (RHSMask.getNode()) {
3616         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3617         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3618       }
3619
3620       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3621     }
3622
3623     return Rot.getNode();
3624   }
3625
3626   // If there is a mask here, and we have a variable shift, we can't be sure
3627   // that we're masking out the right stuff.
3628   if (LHSMask.getNode() || RHSMask.getNode())
3629     return 0;
3630
3631   // If the shift amount is sign/zext/any-extended just peel it off.
3632   SDValue LExtOp0 = LHSShiftAmt;
3633   SDValue RExtOp0 = RHSShiftAmt;
3634   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3635        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3636        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3637        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3638       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3639        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3640        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3641        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3642     LExtOp0 = LHSShiftAmt.getOperand(0);
3643     RExtOp0 = RHSShiftAmt.getOperand(0);
3644   }
3645
3646   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3647                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3648   if (TryL)
3649     return TryL;
3650
3651   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3652                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3653   if (TryR)
3654     return TryR;
3655
3656   return 0;
3657 }
3658
3659 SDValue DAGCombiner::visitXOR(SDNode *N) {
3660   SDValue N0 = N->getOperand(0);
3661   SDValue N1 = N->getOperand(1);
3662   SDValue LHS, RHS, CC;
3663   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3664   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3665   EVT VT = N0.getValueType();
3666
3667   // fold vector ops
3668   if (VT.isVector()) {
3669     SDValue FoldedVOp = SimplifyVBinOp(N);
3670     if (FoldedVOp.getNode()) return FoldedVOp;
3671
3672     // fold (xor x, 0) -> x, vector edition
3673     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3674       return N1;
3675     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3676       return N0;
3677   }
3678
3679   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3680   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3681     return DAG.getConstant(0, VT);
3682   // fold (xor x, undef) -> undef
3683   if (N0.getOpcode() == ISD::UNDEF)
3684     return N0;
3685   if (N1.getOpcode() == ISD::UNDEF)
3686     return N1;
3687   // fold (xor c1, c2) -> c1^c2
3688   if (N0C && N1C)
3689     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3690   // canonicalize constant to RHS
3691   if (N0C && !N1C)
3692     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3693   // fold (xor x, 0) -> x
3694   if (N1C && N1C->isNullValue())
3695     return N0;
3696   // reassociate xor
3697   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3698   if (RXOR.getNode() != 0)
3699     return RXOR;
3700
3701   // fold !(x cc y) -> (x !cc y)
3702   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3703     bool isInt = LHS.getValueType().isInteger();
3704     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3705                                                isInt);
3706
3707     if (!LegalOperations ||
3708         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3709       switch (N0.getOpcode()) {
3710       default:
3711         llvm_unreachable("Unhandled SetCC Equivalent!");
3712       case ISD::SETCC:
3713         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3714       case ISD::SELECT_CC:
3715         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3716                                N0.getOperand(3), NotCC);
3717       }
3718     }
3719   }
3720
3721   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3722   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3723       N0.getNode()->hasOneUse() &&
3724       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3725     SDValue V = N0.getOperand(0);
3726     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3727                     DAG.getConstant(1, V.getValueType()));
3728     AddToWorkList(V.getNode());
3729     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3730   }
3731
3732   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3733   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3734       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3735     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3736     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3737       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3738       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3739       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3740       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3741       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3742     }
3743   }
3744   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3745   if (N1C && N1C->isAllOnesValue() &&
3746       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3747     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3748     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3749       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3750       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3751       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3752       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3753       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3754     }
3755   }
3756   // fold (xor (and x, y), y) -> (and (not x), y)
3757   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3758       N0->getOperand(1) == N1) {
3759     SDValue X = N0->getOperand(0);
3760     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3761     AddToWorkList(NotX.getNode());
3762     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3763   }
3764   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3765   if (N1C && N0.getOpcode() == ISD::XOR) {
3766     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3767     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3768     if (N00C)
3769       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3770                          DAG.getConstant(N1C->getAPIntValue() ^
3771                                          N00C->getAPIntValue(), VT));
3772     if (N01C)
3773       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3774                          DAG.getConstant(N1C->getAPIntValue() ^
3775                                          N01C->getAPIntValue(), VT));
3776   }
3777   // fold (xor x, x) -> 0
3778   if (N0 == N1)
3779     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3780
3781   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3782   if (N0.getOpcode() == N1.getOpcode()) {
3783     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3784     if (Tmp.getNode()) return Tmp;
3785   }
3786
3787   // Simplify the expression using non-local knowledge.
3788   if (!VT.isVector() &&
3789       SimplifyDemandedBits(SDValue(N, 0)))
3790     return SDValue(N, 0);
3791
3792   return SDValue();
3793 }
3794
3795 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3796 /// the shift amount is a constant.
3797 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3798   assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3799          "Expected an ConstantSDNode operand.");
3800   // We can't and shouldn't fold opaque constants.
3801   if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3802     return SDValue();
3803
3804   SDNode *LHS = N->getOperand(0).getNode();
3805   if (!LHS->hasOneUse()) return SDValue();
3806
3807   // We want to pull some binops through shifts, so that we have (and (shift))
3808   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3809   // thing happens with address calculations, so it's important to canonicalize
3810   // it.
3811   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3812
3813   switch (LHS->getOpcode()) {
3814   default: return SDValue();
3815   case ISD::OR:
3816   case ISD::XOR:
3817     HighBitSet = false; // We can only transform sra if the high bit is clear.
3818     break;
3819   case ISD::AND:
3820     HighBitSet = true;  // We can only transform sra if the high bit is set.
3821     break;
3822   case ISD::ADD:
3823     if (N->getOpcode() != ISD::SHL)
3824       return SDValue(); // only shl(add) not sr[al](add).
3825     HighBitSet = false; // We can only transform sra if the high bit is clear.
3826     break;
3827   }
3828
3829   // We require the RHS of the binop to be a constant and not opaque as well.
3830   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3831   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3832
3833   // FIXME: disable this unless the input to the binop is a shift by a constant.
3834   // If it is not a shift, it pessimizes some common cases like:
3835   //
3836   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3837   //    int bar(int *X, int i) { return X[i & 255]; }
3838   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3839   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3840        BinOpLHSVal->getOpcode() != ISD::SRA &&
3841        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3842       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3843     return SDValue();
3844
3845   EVT VT = N->getValueType(0);
3846
3847   // If this is a signed shift right, and the high bit is modified by the
3848   // logical operation, do not perform the transformation. The highBitSet
3849   // boolean indicates the value of the high bit of the constant which would
3850   // cause it to be modified for this operation.
3851   if (N->getOpcode() == ISD::SRA) {
3852     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3853     if (BinOpRHSSignSet != HighBitSet)
3854       return SDValue();
3855   }
3856
3857   // Fold the constants, shifting the binop RHS by the shift amount.
3858   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3859                                N->getValueType(0),
3860                                LHS->getOperand(1), N->getOperand(1));
3861   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3862
3863   // Create the new shift.
3864   SDValue NewShift = DAG.getNode(N->getOpcode(),
3865                                  SDLoc(LHS->getOperand(0)),
3866                                  VT, LHS->getOperand(0), N->getOperand(1));
3867
3868   // Create the new binop.
3869   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3870 }
3871
3872 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3873   assert(N->getOpcode() == ISD::TRUNCATE);
3874   assert(N->getOperand(0).getOpcode() == ISD::AND);
3875
3876   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3877   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3878     SDValue N01 = N->getOperand(0).getOperand(1);
3879
3880     if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01)) {
3881       EVT TruncVT = N->getValueType(0);
3882       SDValue N00 = N->getOperand(0).getOperand(0);
3883       APInt TruncC = N01C->getAPIntValue();
3884       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3885
3886       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3887                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3888                          DAG.getConstant(TruncC, TruncVT));
3889     }
3890   }
3891
3892   return SDValue();
3893 }
3894 SDValue DAGCombiner::visitSHL(SDNode *N) {
3895   SDValue N0 = N->getOperand(0);
3896   SDValue N1 = N->getOperand(1);
3897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3899   EVT VT = N0.getValueType();
3900   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3901
3902   // fold vector ops
3903   if (VT.isVector()) {
3904     SDValue FoldedVOp = SimplifyVBinOp(N);
3905     if (FoldedVOp.getNode()) return FoldedVOp;
3906
3907     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3908     // If setcc produces all-one true value then:
3909     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3910     if (N1CV && N1CV->isConstant() &&
3911         TLI.getBooleanContents(true) ==
3912           TargetLowering::ZeroOrNegativeOneBooleanContent &&
3913         N0.getOpcode() == ISD::AND) {
3914       SDValue N00 = N0->getOperand(0);
3915       SDValue N01 = N0->getOperand(1);
3916       BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3917
3918       if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3919         SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3920         if (C.getNode())
3921           return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3922       }
3923     }
3924   }
3925
3926   // fold (shl c1, c2) -> c1<<c2
3927   if (N0C && N1C)
3928     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3929   // fold (shl 0, x) -> 0
3930   if (N0C && N0C->isNullValue())
3931     return N0;
3932   // fold (shl x, c >= size(x)) -> undef
3933   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3934     return DAG.getUNDEF(VT);
3935   // fold (shl x, 0) -> x
3936   if (N1C && N1C->isNullValue())
3937     return N0;
3938   // fold (shl undef, x) -> 0
3939   if (N0.getOpcode() == ISD::UNDEF)
3940     return DAG.getConstant(0, VT);
3941   // if (shl x, c) is known to be zero, return 0
3942   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3943                             APInt::getAllOnesValue(OpSizeInBits)))
3944     return DAG.getConstant(0, VT);
3945   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3946   if (N1.getOpcode() == ISD::TRUNCATE &&
3947       N1.getOperand(0).getOpcode() == ISD::AND) {
3948     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3949     if (NewOp1.getNode())
3950       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3951   }
3952
3953   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3954     return SDValue(N, 0);
3955
3956   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3957   if (N1C && N0.getOpcode() == ISD::SHL &&
3958       N0.getOperand(1).getOpcode() == ISD::Constant) {
3959     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3960     uint64_t c2 = N1C->getZExtValue();
3961     if (c1 + c2 >= OpSizeInBits)
3962       return DAG.getConstant(0, VT);
3963     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3964                        DAG.getConstant(c1 + c2, N1.getValueType()));
3965   }
3966
3967   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3968   // For this to be valid, the second form must not preserve any of the bits
3969   // that are shifted out by the inner shift in the first form.  This means
3970   // the outer shift size must be >= the number of bits added by the ext.
3971   // As a corollary, we don't care what kind of ext it is.
3972   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3973               N0.getOpcode() == ISD::ANY_EXTEND ||
3974               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3975       N0.getOperand(0).getOpcode() == ISD::SHL &&
3976       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3977     uint64_t c1 =
3978       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3979     uint64_t c2 = N1C->getZExtValue();
3980     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3981     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3982     if (c2 >= OpSizeInBits - InnerShiftSize) {
3983       if (c1 + c2 >= OpSizeInBits)
3984         return DAG.getConstant(0, VT);
3985       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3986                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3987                                      N0.getOperand(0)->getOperand(0)),
3988                          DAG.getConstant(c1 + c2, N1.getValueType()));
3989     }
3990   }
3991
3992   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3993   // Only fold this if the inner zext has no other uses to avoid increasing
3994   // the total number of instructions.
3995   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3996       N0.getOperand(0).getOpcode() == ISD::SRL &&
3997       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3998     uint64_t c1 =
3999       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4000     if (c1 < VT.getSizeInBits()) {
4001       uint64_t c2 = N1C->getZExtValue();
4002       if (c1 == c2) {
4003         SDValue NewOp0 = N0.getOperand(0);
4004         EVT CountVT = NewOp0.getOperand(1).getValueType();
4005         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4006                                      NewOp0, DAG.getConstant(c2, CountVT));
4007         AddToWorkList(NewSHL.getNode());
4008         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4009       }
4010     }
4011   }
4012
4013   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4014   //                               (and (srl x, (sub c1, c2), MASK)
4015   // Only fold this if the inner shift has no other uses -- if it does, folding
4016   // this will increase the total number of instructions.
4017   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
4018       N0.getOperand(1).getOpcode() == ISD::Constant) {
4019     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4020     if (c1 < VT.getSizeInBits()) {
4021       uint64_t c2 = N1C->getZExtValue();
4022       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
4023                                          VT.getSizeInBits() - c1);
4024       SDValue Shift;
4025       if (c2 > c1) {
4026         Mask = Mask.shl(c2-c1);
4027         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4028                             DAG.getConstant(c2-c1, N1.getValueType()));
4029       } else {
4030         Mask = Mask.lshr(c1-c2);
4031         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4032                             DAG.getConstant(c1-c2, N1.getValueType()));
4033       }
4034       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4035                          DAG.getConstant(Mask, VT));
4036     }
4037   }
4038   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4039   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4040     SDValue HiBitsMask =
4041       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
4042                                             VT.getSizeInBits() -
4043                                               N1C->getZExtValue()),
4044                       VT);
4045     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4046                        HiBitsMask);
4047   }
4048
4049   if (N1C) {
4050     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
4051     if (NewSHL.getNode())
4052       return NewSHL;
4053   }
4054
4055   return SDValue();
4056 }
4057
4058 SDValue DAGCombiner::visitSRA(SDNode *N) {
4059   SDValue N0 = N->getOperand(0);
4060   SDValue N1 = N->getOperand(1);
4061   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4062   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4063   EVT VT = N0.getValueType();
4064   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4065
4066   // fold vector ops
4067   if (VT.isVector()) {
4068     SDValue FoldedVOp = SimplifyVBinOp(N);
4069     if (FoldedVOp.getNode()) return FoldedVOp;
4070   }
4071
4072   // fold (sra c1, c2) -> (sra c1, c2)
4073   if (N0C && N1C)
4074     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4075   // fold (sra 0, x) -> 0
4076   if (N0C && N0C->isNullValue())
4077     return N0;
4078   // fold (sra -1, x) -> -1
4079   if (N0C && N0C->isAllOnesValue())
4080     return N0;
4081   // fold (sra x, (setge c, size(x))) -> undef
4082   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4083     return DAG.getUNDEF(VT);
4084   // fold (sra x, 0) -> x
4085   if (N1C && N1C->isNullValue())
4086     return N0;
4087   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4088   // sext_inreg.
4089   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4090     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4091     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4092     if (VT.isVector())
4093       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4094                                ExtVT, VT.getVectorNumElements());
4095     if ((!LegalOperations ||
4096          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4097       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4098                          N0.getOperand(0), DAG.getValueType(ExtVT));
4099   }
4100
4101   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4102   if (N1C && N0.getOpcode() == ISD::SRA) {
4103     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4104       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4105       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
4106       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4107                          DAG.getConstant(Sum, N1C->getValueType(0)));
4108     }
4109   }
4110
4111   // fold (sra (shl X, m), (sub result_size, n))
4112   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4113   // result_size - n != m.
4114   // If truncate is free for the target sext(shl) is likely to result in better
4115   // code.
4116   if (N0.getOpcode() == ISD::SHL) {
4117     // Get the two constanst of the shifts, CN0 = m, CN = n.
4118     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4119     if (N01C && N1C) {
4120       // Determine what the truncate's result bitsize and type would be.
4121       EVT TruncVT =
4122         EVT::getIntegerVT(*DAG.getContext(),
4123                           OpSizeInBits - N1C->getZExtValue());
4124       // Determine the residual right-shift amount.
4125       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4126
4127       // If the shift is not a no-op (in which case this should be just a sign
4128       // extend already), the truncated to type is legal, sign_extend is legal
4129       // on that type, and the truncate to that type is both legal and free,
4130       // perform the transform.
4131       if ((ShiftAmt > 0) &&
4132           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4133           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4134           TLI.isTruncateFree(VT, TruncVT)) {
4135
4136           SDValue Amt = DAG.getConstant(ShiftAmt,
4137               getShiftAmountTy(N0.getOperand(0).getValueType()));
4138           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4139                                       N0.getOperand(0), Amt);
4140           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4141                                       Shift);
4142           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4143                              N->getValueType(0), Trunc);
4144       }
4145     }
4146   }
4147
4148   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4149   if (N1.getOpcode() == ISD::TRUNCATE &&
4150       N1.getOperand(0).getOpcode() == ISD::AND) {
4151     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4152     if (NewOp1.getNode())
4153       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4154   }
4155
4156   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4157   //      if c1 is equal to the number of bits the trunc removes
4158   if (N0.getOpcode() == ISD::TRUNCATE &&
4159       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4160        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4161       N0.getOperand(0).hasOneUse() &&
4162       N0.getOperand(0).getOperand(1).hasOneUse() &&
4163       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4164     EVT LargeVT = N0.getOperand(0).getValueType();
4165     ConstantSDNode *LargeShiftAmt =
4166       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4167
4168     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4169         LargeShiftAmt->getZExtValue()) {
4170       SDValue Amt =
4171         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4172               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4173       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4174                                 N0.getOperand(0).getOperand(0), Amt);
4175       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4176     }
4177   }
4178
4179   // Simplify, based on bits shifted out of the LHS.
4180   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4181     return SDValue(N, 0);
4182
4183
4184   // If the sign bit is known to be zero, switch this to a SRL.
4185   if (DAG.SignBitIsZero(N0))
4186     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4187
4188   if (N1C) {
4189     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4190     if (NewSRA.getNode())
4191       return NewSRA;
4192   }
4193
4194   return SDValue();
4195 }
4196
4197 SDValue DAGCombiner::visitSRL(SDNode *N) {
4198   SDValue N0 = N->getOperand(0);
4199   SDValue N1 = N->getOperand(1);
4200   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   EVT VT = N0.getValueType();
4203   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4204
4205   // fold vector ops
4206   if (VT.isVector()) {
4207     SDValue FoldedVOp = SimplifyVBinOp(N);
4208     if (FoldedVOp.getNode()) return FoldedVOp;
4209   }
4210
4211   // fold (srl c1, c2) -> c1 >>u c2
4212   if (N0C && N1C)
4213     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4214   // fold (srl 0, x) -> 0
4215   if (N0C && N0C->isNullValue())
4216     return N0;
4217   // fold (srl x, c >= size(x)) -> undef
4218   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4219     return DAG.getUNDEF(VT);
4220   // fold (srl x, 0) -> x
4221   if (N1C && N1C->isNullValue())
4222     return N0;
4223   // if (srl x, c) is known to be zero, return 0
4224   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4225                                    APInt::getAllOnesValue(OpSizeInBits)))
4226     return DAG.getConstant(0, VT);
4227
4228   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4229   if (N1C && N0.getOpcode() == ISD::SRL &&
4230       N0.getOperand(1).getOpcode() == ISD::Constant) {
4231     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4232     uint64_t c2 = N1C->getZExtValue();
4233     if (c1 + c2 >= OpSizeInBits)
4234       return DAG.getConstant(0, VT);
4235     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4236                        DAG.getConstant(c1 + c2, N1.getValueType()));
4237   }
4238
4239   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4240   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4241       N0.getOperand(0).getOpcode() == ISD::SRL &&
4242       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4243     uint64_t c1 =
4244       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4245     uint64_t c2 = N1C->getZExtValue();
4246     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4247     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4248     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4249     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4250     if (c1 + OpSizeInBits == InnerShiftSize) {
4251       if (c1 + c2 >= InnerShiftSize)
4252         return DAG.getConstant(0, VT);
4253       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4254                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4255                                      N0.getOperand(0)->getOperand(0),
4256                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4257     }
4258   }
4259
4260   // fold (srl (shl x, c), c) -> (and x, cst2)
4261   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4262       N0.getValueSizeInBits() <= 64) {
4263     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4264     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4265                        DAG.getConstant(~0ULL >> ShAmt, VT));
4266   }
4267
4268   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4269   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4270     // Shifting in all undef bits?
4271     EVT SmallVT = N0.getOperand(0).getValueType();
4272     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4273       return DAG.getUNDEF(VT);
4274
4275     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4276       uint64_t ShiftAmt = N1C->getZExtValue();
4277       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4278                                        N0.getOperand(0),
4279                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4280       AddToWorkList(SmallShift.getNode());
4281       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4282       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4283                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4284                          DAG.getConstant(Mask, VT));
4285     }
4286   }
4287
4288   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4289   // bit, which is unmodified by sra.
4290   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4291     if (N0.getOpcode() == ISD::SRA)
4292       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4293   }
4294
4295   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4296   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4297       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4298     APInt KnownZero, KnownOne;
4299     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4300
4301     // If any of the input bits are KnownOne, then the input couldn't be all
4302     // zeros, thus the result of the srl will always be zero.
4303     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4304
4305     // If all of the bits input the to ctlz node are known to be zero, then
4306     // the result of the ctlz is "32" and the result of the shift is one.
4307     APInt UnknownBits = ~KnownZero;
4308     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4309
4310     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4311     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4312       // Okay, we know that only that the single bit specified by UnknownBits
4313       // could be set on input to the CTLZ node. If this bit is set, the SRL
4314       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4315       // to an SRL/XOR pair, which is likely to simplify more.
4316       unsigned ShAmt = UnknownBits.countTrailingZeros();
4317       SDValue Op = N0.getOperand(0);
4318
4319       if (ShAmt) {
4320         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4321                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4322         AddToWorkList(Op.getNode());
4323       }
4324
4325       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4326                          Op, DAG.getConstant(1, VT));
4327     }
4328   }
4329
4330   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4331   if (N1.getOpcode() == ISD::TRUNCATE &&
4332       N1.getOperand(0).getOpcode() == ISD::AND) {
4333     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4334     if (NewOp1.getNode())
4335       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4336   }
4337
4338   // fold operands of srl based on knowledge that the low bits are not
4339   // demanded.
4340   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4341     return SDValue(N, 0);
4342
4343   if (N1C) {
4344     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4345     if (NewSRL.getNode())
4346       return NewSRL;
4347   }
4348
4349   // Attempt to convert a srl of a load into a narrower zero-extending load.
4350   SDValue NarrowLoad = ReduceLoadWidth(N);
4351   if (NarrowLoad.getNode())
4352     return NarrowLoad;
4353
4354   // Here is a common situation. We want to optimize:
4355   //
4356   //   %a = ...
4357   //   %b = and i32 %a, 2
4358   //   %c = srl i32 %b, 1
4359   //   brcond i32 %c ...
4360   //
4361   // into
4362   //
4363   //   %a = ...
4364   //   %b = and %a, 2
4365   //   %c = setcc eq %b, 0
4366   //   brcond %c ...
4367   //
4368   // However when after the source operand of SRL is optimized into AND, the SRL
4369   // itself may not be optimized further. Look for it and add the BRCOND into
4370   // the worklist.
4371   if (N->hasOneUse()) {
4372     SDNode *Use = *N->use_begin();
4373     if (Use->getOpcode() == ISD::BRCOND)
4374       AddToWorkList(Use);
4375     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4376       // Also look pass the truncate.
4377       Use = *Use->use_begin();
4378       if (Use->getOpcode() == ISD::BRCOND)
4379         AddToWorkList(Use);
4380     }
4381   }
4382
4383   return SDValue();
4384 }
4385
4386 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4387   SDValue N0 = N->getOperand(0);
4388   EVT VT = N->getValueType(0);
4389
4390   // fold (ctlz c1) -> c2
4391   if (isa<ConstantSDNode>(N0))
4392     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4393   return SDValue();
4394 }
4395
4396 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4397   SDValue N0 = N->getOperand(0);
4398   EVT VT = N->getValueType(0);
4399
4400   // fold (ctlz_zero_undef c1) -> c2
4401   if (isa<ConstantSDNode>(N0))
4402     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4403   return SDValue();
4404 }
4405
4406 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4407   SDValue N0 = N->getOperand(0);
4408   EVT VT = N->getValueType(0);
4409
4410   // fold (cttz c1) -> c2
4411   if (isa<ConstantSDNode>(N0))
4412     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4413   return SDValue();
4414 }
4415
4416 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4417   SDValue N0 = N->getOperand(0);
4418   EVT VT = N->getValueType(0);
4419
4420   // fold (cttz_zero_undef c1) -> c2
4421   if (isa<ConstantSDNode>(N0))
4422     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4423   return SDValue();
4424 }
4425
4426 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4427   SDValue N0 = N->getOperand(0);
4428   EVT VT = N->getValueType(0);
4429
4430   // fold (ctpop c1) -> c2
4431   if (isa<ConstantSDNode>(N0))
4432     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4433   return SDValue();
4434 }
4435
4436 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4437   SDValue N0 = N->getOperand(0);
4438   SDValue N1 = N->getOperand(1);
4439   SDValue N2 = N->getOperand(2);
4440   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4441   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4442   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4443   EVT VT = N->getValueType(0);
4444   EVT VT0 = N0.getValueType();
4445
4446   // fold (select C, X, X) -> X
4447   if (N1 == N2)
4448     return N1;
4449   // fold (select true, X, Y) -> X
4450   if (N0C && !N0C->isNullValue())
4451     return N1;
4452   // fold (select false, X, Y) -> Y
4453   if (N0C && N0C->isNullValue())
4454     return N2;
4455   // fold (select C, 1, X) -> (or C, X)
4456   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4457     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4458   // fold (select C, 0, 1) -> (xor C, 1)
4459   if (VT.isInteger() &&
4460       (VT0 == MVT::i1 ||
4461        (VT0.isInteger() &&
4462         TLI.getBooleanContents(false) ==
4463         TargetLowering::ZeroOrOneBooleanContent)) &&
4464       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4465     SDValue XORNode;
4466     if (VT == VT0)
4467       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4468                          N0, DAG.getConstant(1, VT0));
4469     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4470                           N0, DAG.getConstant(1, VT0));
4471     AddToWorkList(XORNode.getNode());
4472     if (VT.bitsGT(VT0))
4473       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4474     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4475   }
4476   // fold (select C, 0, X) -> (and (not C), X)
4477   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4478     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4479     AddToWorkList(NOTNode.getNode());
4480     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4481   }
4482   // fold (select C, X, 1) -> (or (not C), X)
4483   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4484     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4485     AddToWorkList(NOTNode.getNode());
4486     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4487   }
4488   // fold (select C, X, 0) -> (and C, X)
4489   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4490     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4491   // fold (select X, X, Y) -> (or X, Y)
4492   // fold (select X, 1, Y) -> (or X, Y)
4493   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4494     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4495   // fold (select X, Y, X) -> (and X, Y)
4496   // fold (select X, Y, 0) -> (and X, Y)
4497   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4498     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4499
4500   // If we can fold this based on the true/false value, do so.
4501   if (SimplifySelectOps(N, N1, N2))
4502     return SDValue(N, 0);  // Don't revisit N.
4503
4504   // fold selects based on a setcc into other things, such as min/max/abs
4505   if (N0.getOpcode() == ISD::SETCC) {
4506     // FIXME:
4507     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4508     // having to say they don't support SELECT_CC on every type the DAG knows
4509     // about, since there is no way to mark an opcode illegal at all value types
4510     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4511         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4512       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4513                          N0.getOperand(0), N0.getOperand(1),
4514                          N1, N2, N0.getOperand(2));
4515     return SimplifySelect(SDLoc(N), N0, N1, N2);
4516   }
4517
4518   return SDValue();
4519 }
4520
4521 static
4522 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4523   SDLoc DL(N);
4524   EVT LoVT, HiVT;
4525   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4526
4527   // Split the inputs.
4528   SDValue Lo, Hi, LL, LH, RL, RH;
4529   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4530   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4531
4532   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4533   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4534
4535   return std::make_pair(Lo, Hi);
4536 }
4537
4538 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   SDValue N1 = N->getOperand(1);
4541   SDValue N2 = N->getOperand(2);
4542   SDLoc DL(N);
4543
4544   // Canonicalize integer abs.
4545   // vselect (setg[te] X,  0),  X, -X ->
4546   // vselect (setgt    X, -1),  X, -X ->
4547   // vselect (setl[te] X,  0), -X,  X ->
4548   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4549   if (N0.getOpcode() == ISD::SETCC) {
4550     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4551     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4552     bool isAbs = false;
4553     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4554
4555     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4556          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4557         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4558       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4559     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4560              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4561       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4562
4563     if (isAbs) {
4564       EVT VT = LHS.getValueType();
4565       SDValue Shift = DAG.getNode(
4566           ISD::SRA, DL, VT, LHS,
4567           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4568       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4569       AddToWorkList(Shift.getNode());
4570       AddToWorkList(Add.getNode());
4571       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4572     }
4573   }
4574
4575   // If the VSELECT result requires splitting and the mask is provided by a
4576   // SETCC, then split both nodes and its operands before legalization. This
4577   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4578   // and enables future optimizations (e.g. min/max pattern matching on X86).
4579   if (N0.getOpcode() == ISD::SETCC) {
4580     EVT VT = N->getValueType(0);
4581
4582     // Check if any splitting is required.
4583     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4584         TargetLowering::TypeSplitVector)
4585       return SDValue();
4586
4587     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4588     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4589     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4590     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4591
4592     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4593     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4594
4595     // Add the new VSELECT nodes to the work list in case they need to be split
4596     // again.
4597     AddToWorkList(Lo.getNode());
4598     AddToWorkList(Hi.getNode());
4599
4600     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4601   }
4602
4603   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4604   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4605     return N1;
4606   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4607   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4608     return N2;
4609
4610   return SDValue();
4611 }
4612
4613 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4614   SDValue N0 = N->getOperand(0);
4615   SDValue N1 = N->getOperand(1);
4616   SDValue N2 = N->getOperand(2);
4617   SDValue N3 = N->getOperand(3);
4618   SDValue N4 = N->getOperand(4);
4619   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4620
4621   // fold select_cc lhs, rhs, x, x, cc -> x
4622   if (N2 == N3)
4623     return N2;
4624
4625   // Determine if the condition we're dealing with is constant
4626   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4627                               N0, N1, CC, SDLoc(N), false);
4628   if (SCC.getNode()) {
4629     AddToWorkList(SCC.getNode());
4630
4631     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4632       if (!SCCC->isNullValue())
4633         return N2;    // cond always true -> true val
4634       else
4635         return N3;    // cond always false -> false val
4636     }
4637
4638     // Fold to a simpler select_cc
4639     if (SCC.getOpcode() == ISD::SETCC)
4640       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4641                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4642                          SCC.getOperand(2));
4643   }
4644
4645   // If we can fold this based on the true/false value, do so.
4646   if (SimplifySelectOps(N, N2, N3))
4647     return SDValue(N, 0);  // Don't revisit N.
4648
4649   // fold select_cc into other things, such as min/max/abs
4650   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4651 }
4652
4653 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4654   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4655                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4656                        SDLoc(N));
4657 }
4658
4659 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4660 // dag node into a ConstantSDNode or a build_vector of constants.
4661 // This function is called by the DAGCombiner when visiting sext/zext/aext
4662 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4663 // Vector extends are not folded if operations are legal; this is to
4664 // avoid introducing illegal build_vector dag nodes.
4665 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4666                                          SelectionDAG &DAG, bool LegalTypes,
4667                                          bool LegalOperations) {
4668   unsigned Opcode = N->getOpcode();
4669   SDValue N0 = N->getOperand(0);
4670   EVT VT = N->getValueType(0);
4671
4672   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4673          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4674
4675   // fold (sext c1) -> c1
4676   // fold (zext c1) -> c1
4677   // fold (aext c1) -> c1
4678   if (isa<ConstantSDNode>(N0))
4679     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4680
4681   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4682   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4683   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4684   EVT SVT = VT.getScalarType();
4685   if (!(VT.isVector() &&
4686       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4687       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4688     return 0;
4689   
4690   // We can fold this node into a build_vector.
4691   unsigned VTBits = SVT.getSizeInBits();
4692   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4693   unsigned ShAmt = VTBits - EVTBits;
4694   SmallVector<SDValue, 8> Elts;
4695   unsigned NumElts = N0->getNumOperands();
4696   SDLoc DL(N);
4697
4698   for (unsigned i=0; i != NumElts; ++i) {
4699     SDValue Op = N0->getOperand(i);
4700     if (Op->getOpcode() == ISD::UNDEF) {
4701       Elts.push_back(DAG.getUNDEF(SVT));
4702       continue;
4703     }
4704
4705     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4706     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4707     if (Opcode == ISD::SIGN_EXTEND)
4708       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4709                                      SVT));
4710     else
4711       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4712                                      SVT));
4713   }
4714
4715   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4716 }
4717
4718 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4719 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4720 // transformation. Returns true if extension are possible and the above
4721 // mentioned transformation is profitable.
4722 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4723                                     unsigned ExtOpc,
4724                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4725                                     const TargetLowering &TLI) {
4726   bool HasCopyToRegUses = false;
4727   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4728   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4729                             UE = N0.getNode()->use_end();
4730        UI != UE; ++UI) {
4731     SDNode *User = *UI;
4732     if (User == N)
4733       continue;
4734     if (UI.getUse().getResNo() != N0.getResNo())
4735       continue;
4736     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4737     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4738       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4739       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4740         // Sign bits will be lost after a zext.
4741         return false;
4742       bool Add = false;
4743       for (unsigned i = 0; i != 2; ++i) {
4744         SDValue UseOp = User->getOperand(i);
4745         if (UseOp == N0)
4746           continue;
4747         if (!isa<ConstantSDNode>(UseOp))
4748           return false;
4749         Add = true;
4750       }
4751       if (Add)
4752         ExtendNodes.push_back(User);
4753       continue;
4754     }
4755     // If truncates aren't free and there are users we can't
4756     // extend, it isn't worthwhile.
4757     if (!isTruncFree)
4758       return false;
4759     // Remember if this value is live-out.
4760     if (User->getOpcode() == ISD::CopyToReg)
4761       HasCopyToRegUses = true;
4762   }
4763
4764   if (HasCopyToRegUses) {
4765     bool BothLiveOut = false;
4766     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4767          UI != UE; ++UI) {
4768       SDUse &Use = UI.getUse();
4769       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4770         BothLiveOut = true;
4771         break;
4772       }
4773     }
4774     if (BothLiveOut)
4775       // Both unextended and extended values are live out. There had better be
4776       // a good reason for the transformation.
4777       return ExtendNodes.size();
4778   }
4779   return true;
4780 }
4781
4782 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4783                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4784                                   ISD::NodeType ExtType) {
4785   // Extend SetCC uses if necessary.
4786   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4787     SDNode *SetCC = SetCCs[i];
4788     SmallVector<SDValue, 4> Ops;
4789
4790     for (unsigned j = 0; j != 2; ++j) {
4791       SDValue SOp = SetCC->getOperand(j);
4792       if (SOp == Trunc)
4793         Ops.push_back(ExtLoad);
4794       else
4795         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4796     }
4797
4798     Ops.push_back(SetCC->getOperand(2));
4799     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4800                                  &Ops[0], Ops.size()));
4801   }
4802 }
4803
4804 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4805   SDValue N0 = N->getOperand(0);
4806   EVT VT = N->getValueType(0);
4807
4808   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4809                                               LegalOperations))
4810     return SDValue(Res, 0);
4811
4812   // fold (sext (sext x)) -> (sext x)
4813   // fold (sext (aext x)) -> (sext x)
4814   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4815     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4816                        N0.getOperand(0));
4817
4818   if (N0.getOpcode() == ISD::TRUNCATE) {
4819     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4820     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4821     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4822     if (NarrowLoad.getNode()) {
4823       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4824       if (NarrowLoad.getNode() != N0.getNode()) {
4825         CombineTo(N0.getNode(), NarrowLoad);
4826         // CombineTo deleted the truncate, if needed, but not what's under it.
4827         AddToWorkList(oye);
4828       }
4829       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4830     }
4831
4832     // See if the value being truncated is already sign extended.  If so, just
4833     // eliminate the trunc/sext pair.
4834     SDValue Op = N0.getOperand(0);
4835     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4836     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4837     unsigned DestBits = VT.getScalarType().getSizeInBits();
4838     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4839
4840     if (OpBits == DestBits) {
4841       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4842       // bits, it is already ready.
4843       if (NumSignBits > DestBits-MidBits)
4844         return Op;
4845     } else if (OpBits < DestBits) {
4846       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4847       // bits, just sext from i32.
4848       if (NumSignBits > OpBits-MidBits)
4849         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4850     } else {
4851       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4852       // bits, just truncate to i32.
4853       if (NumSignBits > OpBits-MidBits)
4854         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4855     }
4856
4857     // fold (sext (truncate x)) -> (sextinreg x).
4858     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4859                                                  N0.getValueType())) {
4860       if (OpBits < DestBits)
4861         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4862       else if (OpBits > DestBits)
4863         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4864       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4865                          DAG.getValueType(N0.getValueType()));
4866     }
4867   }
4868
4869   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4870   // None of the supported targets knows how to perform load and sign extend
4871   // on vectors in one instruction.  We only perform this transformation on
4872   // scalars.
4873   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4874       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4875        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4876     bool DoXform = true;
4877     SmallVector<SDNode*, 4> SetCCs;
4878     if (!N0.hasOneUse())
4879       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4880     if (DoXform) {
4881       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4882       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4883                                        LN0->getChain(),
4884                                        LN0->getBasePtr(), N0.getValueType(),
4885                                        LN0->getMemOperand());
4886       CombineTo(N, ExtLoad);
4887       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4888                                   N0.getValueType(), ExtLoad);
4889       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4890       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4891                       ISD::SIGN_EXTEND);
4892       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4893     }
4894   }
4895
4896   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4897   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4898   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4899       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4900     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4901     EVT MemVT = LN0->getMemoryVT();
4902     if ((!LegalOperations && !LN0->isVolatile()) ||
4903         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4904       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4905                                        LN0->getChain(),
4906                                        LN0->getBasePtr(), MemVT,
4907                                        LN0->getMemOperand());
4908       CombineTo(N, ExtLoad);
4909       CombineTo(N0.getNode(),
4910                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4911                             N0.getValueType(), ExtLoad),
4912                 ExtLoad.getValue(1));
4913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4914     }
4915   }
4916
4917   // fold (sext (and/or/xor (load x), cst)) ->
4918   //      (and/or/xor (sextload x), (sext cst))
4919   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4920        N0.getOpcode() == ISD::XOR) &&
4921       isa<LoadSDNode>(N0.getOperand(0)) &&
4922       N0.getOperand(1).getOpcode() == ISD::Constant &&
4923       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4924       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4925     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4926     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4927       bool DoXform = true;
4928       SmallVector<SDNode*, 4> SetCCs;
4929       if (!N0.hasOneUse())
4930         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4931                                           SetCCs, TLI);
4932       if (DoXform) {
4933         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4934                                          LN0->getChain(), LN0->getBasePtr(),
4935                                          LN0->getMemoryVT(),
4936                                          LN0->getMemOperand());
4937         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4938         Mask = Mask.sext(VT.getSizeInBits());
4939         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4940                                   ExtLoad, DAG.getConstant(Mask, VT));
4941         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4942                                     SDLoc(N0.getOperand(0)),
4943                                     N0.getOperand(0).getValueType(), ExtLoad);
4944         CombineTo(N, And);
4945         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4946         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4947                         ISD::SIGN_EXTEND);
4948         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4949       }
4950     }
4951   }
4952
4953   if (N0.getOpcode() == ISD::SETCC) {
4954     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4955     // Only do this before legalize for now.
4956     if (VT.isVector() && !LegalOperations &&
4957         TLI.getBooleanContents(true) ==
4958           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4959       EVT N0VT = N0.getOperand(0).getValueType();
4960       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4961       // of the same size as the compared operands. Only optimize sext(setcc())
4962       // if this is the case.
4963       EVT SVT = getSetCCResultType(N0VT);
4964
4965       // We know that the # elements of the results is the same as the
4966       // # elements of the compare (and the # elements of the compare result
4967       // for that matter).  Check to see that they are the same size.  If so,
4968       // we know that the element size of the sext'd result matches the
4969       // element size of the compare operands.
4970       if (VT.getSizeInBits() == SVT.getSizeInBits())
4971         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4972                              N0.getOperand(1),
4973                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4974
4975       // If the desired elements are smaller or larger than the source
4976       // elements we can use a matching integer vector type and then
4977       // truncate/sign extend
4978       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4979       if (SVT == MatchingVectorType) {
4980         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4981                                N0.getOperand(0), N0.getOperand(1),
4982                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4983         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4984       }
4985     }
4986
4987     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
4988     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4989     SDValue NegOne =
4990       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4991     SDValue SCC =
4992       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4993                        NegOne, DAG.getConstant(0, VT),
4994                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4995     if (SCC.getNode()) return SCC;
4996
4997     if (!VT.isVector()) {
4998       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4999       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5000         SDLoc DL(N);
5001         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5002         SDValue SetCC = DAG.getSetCC(DL,
5003                                      SetCCVT,
5004                                      N0.getOperand(0), N0.getOperand(1), CC);
5005         EVT SelectVT = getSetCCResultType(VT);
5006         return DAG.getSelect(DL, VT,
5007                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5008                              NegOne, DAG.getConstant(0, VT));
5009
5010       }
5011     }
5012   }
5013
5014   // fold (sext x) -> (zext x) if the sign bit is known zero.
5015   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5016       DAG.SignBitIsZero(N0))
5017     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5018
5019   return SDValue();
5020 }
5021
5022 // isTruncateOf - If N is a truncate of some other value, return true, record
5023 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5024 // This function computes KnownZero to avoid a duplicated call to
5025 // ComputeMaskedBits in the caller.
5026 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5027                          APInt &KnownZero) {
5028   APInt KnownOne;
5029   if (N->getOpcode() == ISD::TRUNCATE) {
5030     Op = N->getOperand(0);
5031     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5032     return true;
5033   }
5034
5035   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5036       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5037     return false;
5038
5039   SDValue Op0 = N->getOperand(0);
5040   SDValue Op1 = N->getOperand(1);
5041   assert(Op0.getValueType() == Op1.getValueType());
5042
5043   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5044   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5045   if (COp0 && COp0->isNullValue())
5046     Op = Op1;
5047   else if (COp1 && COp1->isNullValue())
5048     Op = Op0;
5049   else
5050     return false;
5051
5052   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5053
5054   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5055     return false;
5056
5057   return true;
5058 }
5059
5060 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5061   SDValue N0 = N->getOperand(0);
5062   EVT VT = N->getValueType(0);
5063
5064   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5065                                               LegalOperations))
5066     return SDValue(Res, 0);
5067
5068   // fold (zext (zext x)) -> (zext x)
5069   // fold (zext (aext x)) -> (zext x)
5070   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5071     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5072                        N0.getOperand(0));
5073
5074   // fold (zext (truncate x)) -> (zext x) or
5075   //      (zext (truncate x)) -> (truncate x)
5076   // This is valid when the truncated bits of x are already zero.
5077   // FIXME: We should extend this to work for vectors too.
5078   SDValue Op;
5079   APInt KnownZero;
5080   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5081     APInt TruncatedBits =
5082       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5083       APInt(Op.getValueSizeInBits(), 0) :
5084       APInt::getBitsSet(Op.getValueSizeInBits(),
5085                         N0.getValueSizeInBits(),
5086                         std::min(Op.getValueSizeInBits(),
5087                                  VT.getSizeInBits()));
5088     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5089       if (VT.bitsGT(Op.getValueType()))
5090         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5091       if (VT.bitsLT(Op.getValueType()))
5092         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5093
5094       return Op;
5095     }
5096   }
5097
5098   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5099   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5100   if (N0.getOpcode() == ISD::TRUNCATE) {
5101     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5102     if (NarrowLoad.getNode()) {
5103       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5104       if (NarrowLoad.getNode() != N0.getNode()) {
5105         CombineTo(N0.getNode(), NarrowLoad);
5106         // CombineTo deleted the truncate, if needed, but not what's under it.
5107         AddToWorkList(oye);
5108       }
5109       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5110     }
5111   }
5112
5113   // fold (zext (truncate x)) -> (and x, mask)
5114   if (N0.getOpcode() == ISD::TRUNCATE &&
5115       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5116
5117     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5118     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5119     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5120     if (NarrowLoad.getNode()) {
5121       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5122       if (NarrowLoad.getNode() != N0.getNode()) {
5123         CombineTo(N0.getNode(), NarrowLoad);
5124         // CombineTo deleted the truncate, if needed, but not what's under it.
5125         AddToWorkList(oye);
5126       }
5127       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5128     }
5129
5130     SDValue Op = N0.getOperand(0);
5131     if (Op.getValueType().bitsLT(VT)) {
5132       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5133       AddToWorkList(Op.getNode());
5134     } else if (Op.getValueType().bitsGT(VT)) {
5135       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5136       AddToWorkList(Op.getNode());
5137     }
5138     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5139                                   N0.getValueType().getScalarType());
5140   }
5141
5142   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5143   // if either of the casts is not free.
5144   if (N0.getOpcode() == ISD::AND &&
5145       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5146       N0.getOperand(1).getOpcode() == ISD::Constant &&
5147       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5148                            N0.getValueType()) ||
5149        !TLI.isZExtFree(N0.getValueType(), VT))) {
5150     SDValue X = N0.getOperand(0).getOperand(0);
5151     if (X.getValueType().bitsLT(VT)) {
5152       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5153     } else if (X.getValueType().bitsGT(VT)) {
5154       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5155     }
5156     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5157     Mask = Mask.zext(VT.getSizeInBits());
5158     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5159                        X, DAG.getConstant(Mask, VT));
5160   }
5161
5162   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5163   // None of the supported targets knows how to perform load and vector_zext
5164   // on vectors in one instruction.  We only perform this transformation on
5165   // scalars.
5166   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5167       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5168        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5169     bool DoXform = true;
5170     SmallVector<SDNode*, 4> SetCCs;
5171     if (!N0.hasOneUse())
5172       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5173     if (DoXform) {
5174       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5175       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5176                                        LN0->getChain(),
5177                                        LN0->getBasePtr(), N0.getValueType(),
5178                                        LN0->getMemOperand());
5179       CombineTo(N, ExtLoad);
5180       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5181                                   N0.getValueType(), ExtLoad);
5182       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5183
5184       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5185                       ISD::ZERO_EXTEND);
5186       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5187     }
5188   }
5189
5190   // fold (zext (and/or/xor (load x), cst)) ->
5191   //      (and/or/xor (zextload x), (zext cst))
5192   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5193        N0.getOpcode() == ISD::XOR) &&
5194       isa<LoadSDNode>(N0.getOperand(0)) &&
5195       N0.getOperand(1).getOpcode() == ISD::Constant &&
5196       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5197       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5198     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5199     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5200       bool DoXform = true;
5201       SmallVector<SDNode*, 4> SetCCs;
5202       if (!N0.hasOneUse())
5203         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5204                                           SetCCs, TLI);
5205       if (DoXform) {
5206         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5207                                          LN0->getChain(), LN0->getBasePtr(),
5208                                          LN0->getMemoryVT(),
5209                                          LN0->getMemOperand());
5210         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5211         Mask = Mask.zext(VT.getSizeInBits());
5212         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5213                                   ExtLoad, DAG.getConstant(Mask, VT));
5214         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5215                                     SDLoc(N0.getOperand(0)),
5216                                     N0.getOperand(0).getValueType(), ExtLoad);
5217         CombineTo(N, And);
5218         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5219         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5220                         ISD::ZERO_EXTEND);
5221         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5222       }
5223     }
5224   }
5225
5226   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5227   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5228   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5229       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5230     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5231     EVT MemVT = LN0->getMemoryVT();
5232     if ((!LegalOperations && !LN0->isVolatile()) ||
5233         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5234       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5235                                        LN0->getChain(),
5236                                        LN0->getBasePtr(), MemVT,
5237                                        LN0->getMemOperand());
5238       CombineTo(N, ExtLoad);
5239       CombineTo(N0.getNode(),
5240                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5241                             ExtLoad),
5242                 ExtLoad.getValue(1));
5243       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5244     }
5245   }
5246
5247   if (N0.getOpcode() == ISD::SETCC) {
5248     if (!LegalOperations && VT.isVector() &&
5249         N0.getValueType().getVectorElementType() == MVT::i1) {
5250       EVT N0VT = N0.getOperand(0).getValueType();
5251       if (getSetCCResultType(N0VT) == N0.getValueType())
5252         return SDValue();
5253
5254       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5255       // Only do this before legalize for now.
5256       EVT EltVT = VT.getVectorElementType();
5257       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5258                                     DAG.getConstant(1, EltVT));
5259       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5260         // We know that the # elements of the results is the same as the
5261         // # elements of the compare (and the # elements of the compare result
5262         // for that matter).  Check to see that they are the same size.  If so,
5263         // we know that the element size of the sext'd result matches the
5264         // element size of the compare operands.
5265         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5266                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5267                                          N0.getOperand(1),
5268                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5269                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5270                                        &OneOps[0], OneOps.size()));
5271
5272       // If the desired elements are smaller or larger than the source
5273       // elements we can use a matching integer vector type and then
5274       // truncate/sign extend
5275       EVT MatchingElementType =
5276         EVT::getIntegerVT(*DAG.getContext(),
5277                           N0VT.getScalarType().getSizeInBits());
5278       EVT MatchingVectorType =
5279         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5280                          N0VT.getVectorNumElements());
5281       SDValue VsetCC =
5282         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5283                       N0.getOperand(1),
5284                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5285       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5286                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5287                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5288                                      &OneOps[0], OneOps.size()));
5289     }
5290
5291     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5292     SDValue SCC =
5293       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5294                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5295                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5296     if (SCC.getNode()) return SCC;
5297   }
5298
5299   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5300   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5301       isa<ConstantSDNode>(N0.getOperand(1)) &&
5302       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5303       N0.hasOneUse()) {
5304     SDValue ShAmt = N0.getOperand(1);
5305     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5306     if (N0.getOpcode() == ISD::SHL) {
5307       SDValue InnerZExt = N0.getOperand(0);
5308       // If the original shl may be shifting out bits, do not perform this
5309       // transformation.
5310       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5311         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5312       if (ShAmtVal > KnownZeroBits)
5313         return SDValue();
5314     }
5315
5316     SDLoc DL(N);
5317
5318     // Ensure that the shift amount is wide enough for the shifted value.
5319     if (VT.getSizeInBits() >= 256)
5320       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5321
5322     return DAG.getNode(N0.getOpcode(), DL, VT,
5323                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5324                        ShAmt);
5325   }
5326
5327   return SDValue();
5328 }
5329
5330 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5331   SDValue N0 = N->getOperand(0);
5332   EVT VT = N->getValueType(0);
5333
5334   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5335                                               LegalOperations))
5336     return SDValue(Res, 0);
5337
5338   // fold (aext (aext x)) -> (aext x)
5339   // fold (aext (zext x)) -> (zext x)
5340   // fold (aext (sext x)) -> (sext x)
5341   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5342       N0.getOpcode() == ISD::ZERO_EXTEND ||
5343       N0.getOpcode() == ISD::SIGN_EXTEND)
5344     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5345
5346   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5347   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5348   if (N0.getOpcode() == ISD::TRUNCATE) {
5349     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5350     if (NarrowLoad.getNode()) {
5351       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5352       if (NarrowLoad.getNode() != N0.getNode()) {
5353         CombineTo(N0.getNode(), NarrowLoad);
5354         // CombineTo deleted the truncate, if needed, but not what's under it.
5355         AddToWorkList(oye);
5356       }
5357       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5358     }
5359   }
5360
5361   // fold (aext (truncate x))
5362   if (N0.getOpcode() == ISD::TRUNCATE) {
5363     SDValue TruncOp = N0.getOperand(0);
5364     if (TruncOp.getValueType() == VT)
5365       return TruncOp; // x iff x size == zext size.
5366     if (TruncOp.getValueType().bitsGT(VT))
5367       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5368     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5369   }
5370
5371   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5372   // if the trunc is not free.
5373   if (N0.getOpcode() == ISD::AND &&
5374       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5375       N0.getOperand(1).getOpcode() == ISD::Constant &&
5376       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5377                           N0.getValueType())) {
5378     SDValue X = N0.getOperand(0).getOperand(0);
5379     if (X.getValueType().bitsLT(VT)) {
5380       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5381     } else if (X.getValueType().bitsGT(VT)) {
5382       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5383     }
5384     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5385     Mask = Mask.zext(VT.getSizeInBits());
5386     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5387                        X, DAG.getConstant(Mask, VT));
5388   }
5389
5390   // fold (aext (load x)) -> (aext (truncate (extload x)))
5391   // None of the supported targets knows how to perform load and any_ext
5392   // on vectors in one instruction.  We only perform this transformation on
5393   // scalars.
5394   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5395       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5396        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5397     bool DoXform = true;
5398     SmallVector<SDNode*, 4> SetCCs;
5399     if (!N0.hasOneUse())
5400       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5401     if (DoXform) {
5402       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5403       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5404                                        LN0->getChain(),
5405                                        LN0->getBasePtr(), N0.getValueType(),
5406                                        LN0->getMemOperand());
5407       CombineTo(N, ExtLoad);
5408       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5409                                   N0.getValueType(), ExtLoad);
5410       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5411       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5412                       ISD::ANY_EXTEND);
5413       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5414     }
5415   }
5416
5417   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5418   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5419   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5420   if (N0.getOpcode() == ISD::LOAD &&
5421       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5422       N0.hasOneUse()) {
5423     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5424     EVT MemVT = LN0->getMemoryVT();
5425     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5426                                      VT, LN0->getChain(), LN0->getBasePtr(),
5427                                      MemVT, LN0->getMemOperand());
5428     CombineTo(N, ExtLoad);
5429     CombineTo(N0.getNode(),
5430               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5431                           N0.getValueType(), ExtLoad),
5432               ExtLoad.getValue(1));
5433     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5434   }
5435
5436   if (N0.getOpcode() == ISD::SETCC) {
5437     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5438     // Only do this before legalize for now.
5439     if (VT.isVector() && !LegalOperations) {
5440       EVT N0VT = N0.getOperand(0).getValueType();
5441         // We know that the # elements of the results is the same as the
5442         // # elements of the compare (and the # elements of the compare result
5443         // for that matter).  Check to see that they are the same size.  If so,
5444         // we know that the element size of the sext'd result matches the
5445         // element size of the compare operands.
5446       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5447         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5448                              N0.getOperand(1),
5449                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5450       // If the desired elements are smaller or larger than the source
5451       // elements we can use a matching integer vector type and then
5452       // truncate/sign extend
5453       else {
5454         EVT MatchingElementType =
5455           EVT::getIntegerVT(*DAG.getContext(),
5456                             N0VT.getScalarType().getSizeInBits());
5457         EVT MatchingVectorType =
5458           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5459                            N0VT.getVectorNumElements());
5460         SDValue VsetCC =
5461           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5462                         N0.getOperand(1),
5463                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5464         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5465       }
5466     }
5467
5468     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5469     SDValue SCC =
5470       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5471                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5472                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5473     if (SCC.getNode())
5474       return SCC;
5475   }
5476
5477   return SDValue();
5478 }
5479
5480 /// GetDemandedBits - See if the specified operand can be simplified with the
5481 /// knowledge that only the bits specified by Mask are used.  If so, return the
5482 /// simpler operand, otherwise return a null SDValue.
5483 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5484   switch (V.getOpcode()) {
5485   default: break;
5486   case ISD::Constant: {
5487     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5488     assert(CV != 0 && "Const value should be ConstSDNode.");
5489     const APInt &CVal = CV->getAPIntValue();
5490     APInt NewVal = CVal & Mask;
5491     if (NewVal != CVal)
5492       return DAG.getConstant(NewVal, V.getValueType());
5493     break;
5494   }
5495   case ISD::OR:
5496   case ISD::XOR:
5497     // If the LHS or RHS don't contribute bits to the or, drop them.
5498     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5499       return V.getOperand(1);
5500     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5501       return V.getOperand(0);
5502     break;
5503   case ISD::SRL:
5504     // Only look at single-use SRLs.
5505     if (!V.getNode()->hasOneUse())
5506       break;
5507     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5508       // See if we can recursively simplify the LHS.
5509       unsigned Amt = RHSC->getZExtValue();
5510
5511       // Watch out for shift count overflow though.
5512       if (Amt >= Mask.getBitWidth()) break;
5513       APInt NewMask = Mask << Amt;
5514       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5515       if (SimplifyLHS.getNode())
5516         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5517                            SimplifyLHS, V.getOperand(1));
5518     }
5519   }
5520   return SDValue();
5521 }
5522
5523 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5524 /// bits and then truncated to a narrower type and where N is a multiple
5525 /// of number of bits of the narrower type, transform it to a narrower load
5526 /// from address + N / num of bits of new type. If the result is to be
5527 /// extended, also fold the extension to form a extending load.
5528 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5529   unsigned Opc = N->getOpcode();
5530
5531   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5532   SDValue N0 = N->getOperand(0);
5533   EVT VT = N->getValueType(0);
5534   EVT ExtVT = VT;
5535
5536   // This transformation isn't valid for vector loads.
5537   if (VT.isVector())
5538     return SDValue();
5539
5540   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5541   // extended to VT.
5542   if (Opc == ISD::SIGN_EXTEND_INREG) {
5543     ExtType = ISD::SEXTLOAD;
5544     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5545   } else if (Opc == ISD::SRL) {
5546     // Another special-case: SRL is basically zero-extending a narrower value.
5547     ExtType = ISD::ZEXTLOAD;
5548     N0 = SDValue(N, 0);
5549     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5550     if (!N01) return SDValue();
5551     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5552                               VT.getSizeInBits() - N01->getZExtValue());
5553   }
5554   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5555     return SDValue();
5556
5557   unsigned EVTBits = ExtVT.getSizeInBits();
5558
5559   // Do not generate loads of non-round integer types since these can
5560   // be expensive (and would be wrong if the type is not byte sized).
5561   if (!ExtVT.isRound())
5562     return SDValue();
5563
5564   unsigned ShAmt = 0;
5565   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5566     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5567       ShAmt = N01->getZExtValue();
5568       // Is the shift amount a multiple of size of VT?
5569       if ((ShAmt & (EVTBits-1)) == 0) {
5570         N0 = N0.getOperand(0);
5571         // Is the load width a multiple of size of VT?
5572         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5573           return SDValue();
5574       }
5575
5576       // At this point, we must have a load or else we can't do the transform.
5577       if (!isa<LoadSDNode>(N0)) return SDValue();
5578
5579       // Because a SRL must be assumed to *need* to zero-extend the high bits
5580       // (as opposed to anyext the high bits), we can't combine the zextload
5581       // lowering of SRL and an sextload.
5582       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5583         return SDValue();
5584
5585       // If the shift amount is larger than the input type then we're not
5586       // accessing any of the loaded bytes.  If the load was a zextload/extload
5587       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5588       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5589         return SDValue();
5590     }
5591   }
5592
5593   // If the load is shifted left (and the result isn't shifted back right),
5594   // we can fold the truncate through the shift.
5595   unsigned ShLeftAmt = 0;
5596   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5597       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5598     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5599       ShLeftAmt = N01->getZExtValue();
5600       N0 = N0.getOperand(0);
5601     }
5602   }
5603
5604   // If we haven't found a load, we can't narrow it.  Don't transform one with
5605   // multiple uses, this would require adding a new load.
5606   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5607     return SDValue();
5608
5609   // Don't change the width of a volatile load.
5610   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611   if (LN0->isVolatile())
5612     return SDValue();
5613
5614   // Verify that we are actually reducing a load width here.
5615   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5616     return SDValue();
5617
5618   // For the transform to be legal, the load must produce only two values
5619   // (the value loaded and the chain).  Don't transform a pre-increment
5620   // load, for example, which produces an extra value.  Otherwise the
5621   // transformation is not equivalent, and the downstream logic to replace
5622   // uses gets things wrong.
5623   if (LN0->getNumValues() > 2)
5624     return SDValue();
5625
5626   // If the load that we're shrinking is an extload and we're not just
5627   // discarding the extension we can't simply shrink the load. Bail.
5628   // TODO: It would be possible to merge the extensions in some cases.
5629   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5630       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5631     return SDValue();
5632
5633   EVT PtrType = N0.getOperand(1).getValueType();
5634
5635   if (PtrType == MVT::Untyped || PtrType.isExtended())
5636     // It's not possible to generate a constant of extended or untyped type.
5637     return SDValue();
5638
5639   // For big endian targets, we need to adjust the offset to the pointer to
5640   // load the correct bytes.
5641   if (TLI.isBigEndian()) {
5642     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5643     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5644     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5645   }
5646
5647   uint64_t PtrOff = ShAmt / 8;
5648   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5649   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5650                                PtrType, LN0->getBasePtr(),
5651                                DAG.getConstant(PtrOff, PtrType));
5652   AddToWorkList(NewPtr.getNode());
5653
5654   SDValue Load;
5655   if (ExtType == ISD::NON_EXTLOAD)
5656     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5657                         LN0->getPointerInfo().getWithOffset(PtrOff),
5658                         LN0->isVolatile(), LN0->isNonTemporal(),
5659                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5660   else
5661     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5662                           LN0->getPointerInfo().getWithOffset(PtrOff),
5663                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5664                           NewAlign, LN0->getTBAAInfo());
5665
5666   // Replace the old load's chain with the new load's chain.
5667   WorkListRemover DeadNodes(*this);
5668   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5669
5670   // Shift the result left, if we've swallowed a left shift.
5671   SDValue Result = Load;
5672   if (ShLeftAmt != 0) {
5673     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5674     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5675       ShImmTy = VT;
5676     // If the shift amount is as large as the result size (but, presumably,
5677     // no larger than the source) then the useful bits of the result are
5678     // zero; we can't simply return the shortened shift, because the result
5679     // of that operation is undefined.
5680     if (ShLeftAmt >= VT.getSizeInBits())
5681       Result = DAG.getConstant(0, VT);
5682     else
5683       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5684                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5685   }
5686
5687   // Return the new loaded value.
5688   return Result;
5689 }
5690
5691 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5692   SDValue N0 = N->getOperand(0);
5693   SDValue N1 = N->getOperand(1);
5694   EVT VT = N->getValueType(0);
5695   EVT EVT = cast<VTSDNode>(N1)->getVT();
5696   unsigned VTBits = VT.getScalarType().getSizeInBits();
5697   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5698
5699   // fold (sext_in_reg c1) -> c1
5700   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5701     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5702
5703   // If the input is already sign extended, just drop the extension.
5704   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5705     return N0;
5706
5707   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5708   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5709       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5710     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5711                        N0.getOperand(0), N1);
5712
5713   // fold (sext_in_reg (sext x)) -> (sext x)
5714   // fold (sext_in_reg (aext x)) -> (sext x)
5715   // if x is small enough.
5716   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5717     SDValue N00 = N0.getOperand(0);
5718     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5719         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5720       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5721   }
5722
5723   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5724   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5725     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5726
5727   // fold operands of sext_in_reg based on knowledge that the top bits are not
5728   // demanded.
5729   if (SimplifyDemandedBits(SDValue(N, 0)))
5730     return SDValue(N, 0);
5731
5732   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5733   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5734   SDValue NarrowLoad = ReduceLoadWidth(N);
5735   if (NarrowLoad.getNode())
5736     return NarrowLoad;
5737
5738   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5739   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5740   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5741   if (N0.getOpcode() == ISD::SRL) {
5742     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5743       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5744         // We can turn this into an SRA iff the input to the SRL is already sign
5745         // extended enough.
5746         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5747         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5748           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5749                              N0.getOperand(0), N0.getOperand(1));
5750       }
5751   }
5752
5753   // fold (sext_inreg (extload x)) -> (sextload x)
5754   if (ISD::isEXTLoad(N0.getNode()) &&
5755       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5756       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5757       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5758        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5759     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5760     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5761                                      LN0->getChain(),
5762                                      LN0->getBasePtr(), EVT,
5763                                      LN0->getMemOperand());
5764     CombineTo(N, ExtLoad);
5765     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5766     AddToWorkList(ExtLoad.getNode());
5767     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5768   }
5769   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5770   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5771       N0.hasOneUse() &&
5772       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5773       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5774        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5775     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5776     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5777                                      LN0->getChain(),
5778                                      LN0->getBasePtr(), EVT,
5779                                      LN0->getMemOperand());
5780     CombineTo(N, ExtLoad);
5781     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5782     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5783   }
5784
5785   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5786   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5787     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5788                                        N0.getOperand(1), false);
5789     if (BSwap.getNode() != 0)
5790       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5791                          BSwap, N1);
5792   }
5793
5794   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5795   // into a build_vector.
5796   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5797     SmallVector<SDValue, 8> Elts;
5798     unsigned NumElts = N0->getNumOperands();
5799     unsigned ShAmt = VTBits - EVTBits;
5800
5801     for (unsigned i = 0; i != NumElts; ++i) {
5802       SDValue Op = N0->getOperand(i);
5803       if (Op->getOpcode() == ISD::UNDEF) {
5804         Elts.push_back(Op);
5805         continue;
5806       }
5807
5808       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5809       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5810       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5811                                      Op.getValueType()));
5812     }
5813
5814     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5815   }
5816
5817   return SDValue();
5818 }
5819
5820 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5821   SDValue N0 = N->getOperand(0);
5822   EVT VT = N->getValueType(0);
5823   bool isLE = TLI.isLittleEndian();
5824
5825   // noop truncate
5826   if (N0.getValueType() == N->getValueType(0))
5827     return N0;
5828   // fold (truncate c1) -> c1
5829   if (isa<ConstantSDNode>(N0))
5830     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5831   // fold (truncate (truncate x)) -> (truncate x)
5832   if (N0.getOpcode() == ISD::TRUNCATE)
5833     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5834   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5835   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5836       N0.getOpcode() == ISD::SIGN_EXTEND ||
5837       N0.getOpcode() == ISD::ANY_EXTEND) {
5838     if (N0.getOperand(0).getValueType().bitsLT(VT))
5839       // if the source is smaller than the dest, we still need an extend
5840       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5841                          N0.getOperand(0));
5842     if (N0.getOperand(0).getValueType().bitsGT(VT))
5843       // if the source is larger than the dest, than we just need the truncate
5844       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5845     // if the source and dest are the same type, we can drop both the extend
5846     // and the truncate.
5847     return N0.getOperand(0);
5848   }
5849
5850   // Fold extract-and-trunc into a narrow extract. For example:
5851   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5852   //   i32 y = TRUNCATE(i64 x)
5853   //        -- becomes --
5854   //   v16i8 b = BITCAST (v2i64 val)
5855   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5856   //
5857   // Note: We only run this optimization after type legalization (which often
5858   // creates this pattern) and before operation legalization after which
5859   // we need to be more careful about the vector instructions that we generate.
5860   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5861       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5862
5863     EVT VecTy = N0.getOperand(0).getValueType();
5864     EVT ExTy = N0.getValueType();
5865     EVT TrTy = N->getValueType(0);
5866
5867     unsigned NumElem = VecTy.getVectorNumElements();
5868     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5869
5870     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5871     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5872
5873     SDValue EltNo = N0->getOperand(1);
5874     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5875       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5876       EVT IndexTy = TLI.getVectorIdxTy();
5877       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5878
5879       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5880                               NVT, N0.getOperand(0));
5881
5882       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5883                          SDLoc(N), TrTy, V,
5884                          DAG.getConstant(Index, IndexTy));
5885     }
5886   }
5887
5888   // Fold a series of buildvector, bitcast, and truncate if possible.
5889   // For example fold
5890   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5891   //   (2xi32 (buildvector x, y)).
5892   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5893       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5894       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5895       N0.getOperand(0).hasOneUse()) {
5896
5897     SDValue BuildVect = N0.getOperand(0);
5898     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5899     EVT TruncVecEltTy = VT.getVectorElementType();
5900
5901     // Check that the element types match.
5902     if (BuildVectEltTy == TruncVecEltTy) {
5903       // Now we only need to compute the offset of the truncated elements.
5904       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5905       unsigned TruncVecNumElts = VT.getVectorNumElements();
5906       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5907
5908       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5909              "Invalid number of elements");
5910
5911       SmallVector<SDValue, 8> Opnds;
5912       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5913         Opnds.push_back(BuildVect.getOperand(i));
5914
5915       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5916                          Opnds.size());
5917     }
5918   }
5919
5920   // See if we can simplify the input to this truncate through knowledge that
5921   // only the low bits are being used.
5922   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5923   // Currently we only perform this optimization on scalars because vectors
5924   // may have different active low bits.
5925   if (!VT.isVector()) {
5926     SDValue Shorter =
5927       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5928                                                VT.getSizeInBits()));
5929     if (Shorter.getNode())
5930       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5931   }
5932   // fold (truncate (load x)) -> (smaller load x)
5933   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5934   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5935     SDValue Reduced = ReduceLoadWidth(N);
5936     if (Reduced.getNode())
5937       return Reduced;
5938     // Handle the case where the load remains an extending load even
5939     // after truncation.
5940     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5941       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5942       if (!LN0->isVolatile() &&
5943           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5944         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5945                                          VT, LN0->getChain(), LN0->getBasePtr(),
5946                                          LN0->getMemoryVT(),
5947                                          LN0->getMemOperand());
5948         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5949         return NewLoad;
5950       }
5951     }
5952   }
5953   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5954   // where ... are all 'undef'.
5955   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5956     SmallVector<EVT, 8> VTs;
5957     SDValue V;
5958     unsigned Idx = 0;
5959     unsigned NumDefs = 0;
5960
5961     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5962       SDValue X = N0.getOperand(i);
5963       if (X.getOpcode() != ISD::UNDEF) {
5964         V = X;
5965         Idx = i;
5966         NumDefs++;
5967       }
5968       // Stop if more than one members are non-undef.
5969       if (NumDefs > 1)
5970         break;
5971       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5972                                      VT.getVectorElementType(),
5973                                      X.getValueType().getVectorNumElements()));
5974     }
5975
5976     if (NumDefs == 0)
5977       return DAG.getUNDEF(VT);
5978
5979     if (NumDefs == 1) {
5980       assert(V.getNode() && "The single defined operand is empty!");
5981       SmallVector<SDValue, 8> Opnds;
5982       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5983         if (i != Idx) {
5984           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5985           continue;
5986         }
5987         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5988         AddToWorkList(NV.getNode());
5989         Opnds.push_back(NV);
5990       }
5991       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5992                          &Opnds[0], Opnds.size());
5993     }
5994   }
5995
5996   // Simplify the operands using demanded-bits information.
5997   if (!VT.isVector() &&
5998       SimplifyDemandedBits(SDValue(N, 0)))
5999     return SDValue(N, 0);
6000
6001   return SDValue();
6002 }
6003
6004 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6005   SDValue Elt = N->getOperand(i);
6006   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6007     return Elt.getNode();
6008   return Elt.getOperand(Elt.getResNo()).getNode();
6009 }
6010
6011 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6012 /// if load locations are consecutive.
6013 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6014   assert(N->getOpcode() == ISD::BUILD_PAIR);
6015
6016   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6017   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6018   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6019       LD1->getAddressSpace() != LD2->getAddressSpace())
6020     return SDValue();
6021   EVT LD1VT = LD1->getValueType(0);
6022
6023   if (ISD::isNON_EXTLoad(LD2) &&
6024       LD2->hasOneUse() &&
6025       // If both are volatile this would reduce the number of volatile loads.
6026       // If one is volatile it might be ok, but play conservative and bail out.
6027       !LD1->isVolatile() &&
6028       !LD2->isVolatile() &&
6029       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6030     unsigned Align = LD1->getAlignment();
6031     unsigned NewAlign = TLI.getDataLayout()->
6032       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6033
6034     if (NewAlign <= Align &&
6035         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6036       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6037                          LD1->getBasePtr(), LD1->getPointerInfo(),
6038                          false, false, false, Align);
6039   }
6040
6041   return SDValue();
6042 }
6043
6044 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6045   SDValue N0 = N->getOperand(0);
6046   EVT VT = N->getValueType(0);
6047
6048   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6049   // Only do this before legalize, since afterward the target may be depending
6050   // on the bitconvert.
6051   // First check to see if this is all constant.
6052   if (!LegalTypes &&
6053       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6054       VT.isVector()) {
6055     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6056
6057     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6058     assert(!DestEltVT.isVector() &&
6059            "Element type of vector ValueType must not be vector!");
6060     if (isSimple)
6061       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6062   }
6063
6064   // If the input is a constant, let getNode fold it.
6065   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6066     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6067     if (Res.getNode() != N) {
6068       if (!LegalOperations ||
6069           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6070         return Res;
6071
6072       // Folding it resulted in an illegal node, and it's too late to
6073       // do that. Clean up the old node and forego the transformation.
6074       // Ideally this won't happen very often, because instcombine
6075       // and the earlier dagcombine runs (where illegal nodes are
6076       // permitted) should have folded most of them already.
6077       DAG.DeleteNode(Res.getNode());
6078     }
6079   }
6080
6081   // (conv (conv x, t1), t2) -> (conv x, t2)
6082   if (N0.getOpcode() == ISD::BITCAST)
6083     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6084                        N0.getOperand(0));
6085
6086   // fold (conv (load x)) -> (load (conv*)x)
6087   // If the resultant load doesn't need a higher alignment than the original!
6088   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6089       // Do not change the width of a volatile load.
6090       !cast<LoadSDNode>(N0)->isVolatile() &&
6091       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6092       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6093     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6094     unsigned Align = TLI.getDataLayout()->
6095       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6096     unsigned OrigAlign = LN0->getAlignment();
6097
6098     if (Align <= OrigAlign) {
6099       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6100                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6101                                  LN0->isVolatile(), LN0->isNonTemporal(),
6102                                  LN0->isInvariant(), OrigAlign,
6103                                  LN0->getTBAAInfo());
6104       AddToWorkList(N);
6105       CombineTo(N0.getNode(),
6106                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6107                             N0.getValueType(), Load),
6108                 Load.getValue(1));
6109       return Load;
6110     }
6111   }
6112
6113   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6114   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6115   // This often reduces constant pool loads.
6116   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6117        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6118       N0.getNode()->hasOneUse() && VT.isInteger() &&
6119       !VT.isVector() && !N0.getValueType().isVector()) {
6120     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6121                                   N0.getOperand(0));
6122     AddToWorkList(NewConv.getNode());
6123
6124     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6125     if (N0.getOpcode() == ISD::FNEG)
6126       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6127                          NewConv, DAG.getConstant(SignBit, VT));
6128     assert(N0.getOpcode() == ISD::FABS);
6129     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6130                        NewConv, DAG.getConstant(~SignBit, VT));
6131   }
6132
6133   // fold (bitconvert (fcopysign cst, x)) ->
6134   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6135   // Note that we don't handle (copysign x, cst) because this can always be
6136   // folded to an fneg or fabs.
6137   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6138       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6139       VT.isInteger() && !VT.isVector()) {
6140     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6141     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6142     if (isTypeLegal(IntXVT)) {
6143       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6144                               IntXVT, N0.getOperand(1));
6145       AddToWorkList(X.getNode());
6146
6147       // If X has a different width than the result/lhs, sext it or truncate it.
6148       unsigned VTWidth = VT.getSizeInBits();
6149       if (OrigXWidth < VTWidth) {
6150         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6151         AddToWorkList(X.getNode());
6152       } else if (OrigXWidth > VTWidth) {
6153         // To get the sign bit in the right place, we have to shift it right
6154         // before truncating.
6155         X = DAG.getNode(ISD::SRL, SDLoc(X),
6156                         X.getValueType(), X,
6157                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6158         AddToWorkList(X.getNode());
6159         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6160         AddToWorkList(X.getNode());
6161       }
6162
6163       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6164       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6165                       X, DAG.getConstant(SignBit, VT));
6166       AddToWorkList(X.getNode());
6167
6168       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6169                                 VT, N0.getOperand(0));
6170       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6171                         Cst, DAG.getConstant(~SignBit, VT));
6172       AddToWorkList(Cst.getNode());
6173
6174       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6175     }
6176   }
6177
6178   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6179   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6180     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6181     if (CombineLD.getNode())
6182       return CombineLD;
6183   }
6184
6185   return SDValue();
6186 }
6187
6188 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6189   EVT VT = N->getValueType(0);
6190   return CombineConsecutiveLoads(N, VT);
6191 }
6192
6193 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6194 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6195 /// destination element value type.
6196 SDValue DAGCombiner::
6197 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6198   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6199
6200   // If this is already the right type, we're done.
6201   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6202
6203   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6204   unsigned DstBitSize = DstEltVT.getSizeInBits();
6205
6206   // If this is a conversion of N elements of one type to N elements of another
6207   // type, convert each element.  This handles FP<->INT cases.
6208   if (SrcBitSize == DstBitSize) {
6209     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6210                               BV->getValueType(0).getVectorNumElements());
6211
6212     // Due to the FP element handling below calling this routine recursively,
6213     // we can end up with a scalar-to-vector node here.
6214     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6215       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6216                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6217                                      DstEltVT, BV->getOperand(0)));
6218
6219     SmallVector<SDValue, 8> Ops;
6220     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6221       SDValue Op = BV->getOperand(i);
6222       // If the vector element type is not legal, the BUILD_VECTOR operands
6223       // are promoted and implicitly truncated.  Make that explicit here.
6224       if (Op.getValueType() != SrcEltVT)
6225         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6226       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6227                                 DstEltVT, Op));
6228       AddToWorkList(Ops.back().getNode());
6229     }
6230     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6231                        &Ops[0], Ops.size());
6232   }
6233
6234   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6235   // handle annoying details of growing/shrinking FP values, we convert them to
6236   // int first.
6237   if (SrcEltVT.isFloatingPoint()) {
6238     // Convert the input float vector to a int vector where the elements are the
6239     // same sizes.
6240     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6241     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6242     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6243     SrcEltVT = IntVT;
6244   }
6245
6246   // Now we know the input is an integer vector.  If the output is a FP type,
6247   // convert to integer first, then to FP of the right size.
6248   if (DstEltVT.isFloatingPoint()) {
6249     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6250     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6251     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6252
6253     // Next, convert to FP elements of the same size.
6254     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6255   }
6256
6257   // Okay, we know the src/dst types are both integers of differing types.
6258   // Handling growing first.
6259   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6260   if (SrcBitSize < DstBitSize) {
6261     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6262
6263     SmallVector<SDValue, 8> Ops;
6264     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6265          i += NumInputsPerOutput) {
6266       bool isLE = TLI.isLittleEndian();
6267       APInt NewBits = APInt(DstBitSize, 0);
6268       bool EltIsUndef = true;
6269       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6270         // Shift the previously computed bits over.
6271         NewBits <<= SrcBitSize;
6272         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6273         if (Op.getOpcode() == ISD::UNDEF) continue;
6274         EltIsUndef = false;
6275
6276         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6277                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6278       }
6279
6280       if (EltIsUndef)
6281         Ops.push_back(DAG.getUNDEF(DstEltVT));
6282       else
6283         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6284     }
6285
6286     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6287     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6288                        &Ops[0], Ops.size());
6289   }
6290
6291   // Finally, this must be the case where we are shrinking elements: each input
6292   // turns into multiple outputs.
6293   bool isS2V = ISD::isScalarToVector(BV);
6294   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6295   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6296                             NumOutputsPerInput*BV->getNumOperands());
6297   SmallVector<SDValue, 8> Ops;
6298
6299   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6300     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6301       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6302         Ops.push_back(DAG.getUNDEF(DstEltVT));
6303       continue;
6304     }
6305
6306     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6307                   getAPIntValue().zextOrTrunc(SrcBitSize);
6308
6309     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6310       APInt ThisVal = OpVal.trunc(DstBitSize);
6311       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6312       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6313         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6314         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6315                            Ops[0]);
6316       OpVal = OpVal.lshr(DstBitSize);
6317     }
6318
6319     // For big endian targets, swap the order of the pieces of each element.
6320     if (TLI.isBigEndian())
6321       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6322   }
6323
6324   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6325                      &Ops[0], Ops.size());
6326 }
6327
6328 SDValue DAGCombiner::visitFADD(SDNode *N) {
6329   SDValue N0 = N->getOperand(0);
6330   SDValue N1 = N->getOperand(1);
6331   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6332   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6333   EVT VT = N->getValueType(0);
6334
6335   // fold vector ops
6336   if (VT.isVector()) {
6337     SDValue FoldedVOp = SimplifyVBinOp(N);
6338     if (FoldedVOp.getNode()) return FoldedVOp;
6339   }
6340
6341   // fold (fadd c1, c2) -> c1 + c2
6342   if (N0CFP && N1CFP)
6343     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6344   // canonicalize constant to RHS
6345   if (N0CFP && !N1CFP)
6346     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6347   // fold (fadd A, 0) -> A
6348   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6349       N1CFP->getValueAPF().isZero())
6350     return N0;
6351   // fold (fadd A, (fneg B)) -> (fsub A, B)
6352   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6353     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6354     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6355                        GetNegatedExpression(N1, DAG, LegalOperations));
6356   // fold (fadd (fneg A), B) -> (fsub B, A)
6357   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6358     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6359     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6360                        GetNegatedExpression(N0, DAG, LegalOperations));
6361
6362   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6363   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6364       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6365       isa<ConstantFPSDNode>(N0.getOperand(1)))
6366     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6367                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6368                                    N0.getOperand(1), N1));
6369
6370   // No FP constant should be created after legalization as Instruction
6371   // Selection pass has hard time in dealing with FP constant.
6372   //
6373   // We don't need test this condition for transformation like following, as
6374   // the DAG being transformed implies it is legal to take FP constant as
6375   // operand.
6376   //
6377   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6378   //
6379   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6380
6381   // If allow, fold (fadd (fneg x), x) -> 0.0
6382   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6383       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6384     return DAG.getConstantFP(0.0, VT);
6385
6386     // If allow, fold (fadd x, (fneg x)) -> 0.0
6387   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6388       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6389     return DAG.getConstantFP(0.0, VT);
6390
6391   // In unsafe math mode, we can fold chains of FADD's of the same value
6392   // into multiplications.  This transform is not safe in general because
6393   // we are reducing the number of rounding steps.
6394   if (DAG.getTarget().Options.UnsafeFPMath &&
6395       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6396       !N0CFP && !N1CFP) {
6397     if (N0.getOpcode() == ISD::FMUL) {
6398       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6399       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6400
6401       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6402       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6403         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6404                                      SDValue(CFP00, 0),
6405                                      DAG.getConstantFP(1.0, VT));
6406         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6407                            N1, NewCFP);
6408       }
6409
6410       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6411       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6412         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6413                                      SDValue(CFP01, 0),
6414                                      DAG.getConstantFP(1.0, VT));
6415         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6416                            N1, NewCFP);
6417       }
6418
6419       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6420       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6421           N1.getOperand(0) == N1.getOperand(1) &&
6422           N0.getOperand(1) == N1.getOperand(0)) {
6423         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6424                                      SDValue(CFP00, 0),
6425                                      DAG.getConstantFP(2.0, VT));
6426         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6427                            N0.getOperand(1), NewCFP);
6428       }
6429
6430       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6431       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6432           N1.getOperand(0) == N1.getOperand(1) &&
6433           N0.getOperand(0) == N1.getOperand(0)) {
6434         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6435                                      SDValue(CFP01, 0),
6436                                      DAG.getConstantFP(2.0, VT));
6437         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6438                            N0.getOperand(0), NewCFP);
6439       }
6440     }
6441
6442     if (N1.getOpcode() == ISD::FMUL) {
6443       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6444       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6445
6446       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6447       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6448         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6449                                      SDValue(CFP10, 0),
6450                                      DAG.getConstantFP(1.0, VT));
6451         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6452                            N0, NewCFP);
6453       }
6454
6455       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6456       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6457         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6458                                      SDValue(CFP11, 0),
6459                                      DAG.getConstantFP(1.0, VT));
6460         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6461                            N0, NewCFP);
6462       }
6463
6464
6465       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6466       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6467           N0.getOperand(0) == N0.getOperand(1) &&
6468           N1.getOperand(1) == N0.getOperand(0)) {
6469         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6470                                      SDValue(CFP10, 0),
6471                                      DAG.getConstantFP(2.0, VT));
6472         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6473                            N1.getOperand(1), NewCFP);
6474       }
6475
6476       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6477       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6478           N0.getOperand(0) == N0.getOperand(1) &&
6479           N1.getOperand(0) == N0.getOperand(0)) {
6480         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6481                                      SDValue(CFP11, 0),
6482                                      DAG.getConstantFP(2.0, VT));
6483         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6484                            N1.getOperand(0), NewCFP);
6485       }
6486     }
6487
6488     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6489       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6490       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6491       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6492           (N0.getOperand(0) == N1))
6493         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6494                            N1, DAG.getConstantFP(3.0, VT));
6495     }
6496
6497     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6498       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6499       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6500       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6501           N1.getOperand(0) == N0)
6502         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6503                            N0, DAG.getConstantFP(3.0, VT));
6504     }
6505
6506     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6507     if (AllowNewFpConst &&
6508         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6509         N0.getOperand(0) == N0.getOperand(1) &&
6510         N1.getOperand(0) == N1.getOperand(1) &&
6511         N0.getOperand(0) == N1.getOperand(0))
6512       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6513                          N0.getOperand(0),
6514                          DAG.getConstantFP(4.0, VT));
6515   }
6516
6517   // FADD -> FMA combines:
6518   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6519        DAG.getTarget().Options.UnsafeFPMath) &&
6520       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6521       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6522
6523     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6524     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6525       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6526                          N0.getOperand(0), N0.getOperand(1), N1);
6527
6528     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6529     // Note: Commutes FADD operands.
6530     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6531       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6532                          N1.getOperand(0), N1.getOperand(1), N0);
6533   }
6534
6535   return SDValue();
6536 }
6537
6538 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6539   SDValue N0 = N->getOperand(0);
6540   SDValue N1 = N->getOperand(1);
6541   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6542   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6543   EVT VT = N->getValueType(0);
6544   SDLoc dl(N);
6545
6546   // fold vector ops
6547   if (VT.isVector()) {
6548     SDValue FoldedVOp = SimplifyVBinOp(N);
6549     if (FoldedVOp.getNode()) return FoldedVOp;
6550   }
6551
6552   // fold (fsub c1, c2) -> c1-c2
6553   if (N0CFP && N1CFP)
6554     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6555   // fold (fsub A, 0) -> A
6556   if (DAG.getTarget().Options.UnsafeFPMath &&
6557       N1CFP && N1CFP->getValueAPF().isZero())
6558     return N0;
6559   // fold (fsub 0, B) -> -B
6560   if (DAG.getTarget().Options.UnsafeFPMath &&
6561       N0CFP && N0CFP->getValueAPF().isZero()) {
6562     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6563       return GetNegatedExpression(N1, DAG, LegalOperations);
6564     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6565       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6566   }
6567   // fold (fsub A, (fneg B)) -> (fadd A, B)
6568   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6569     return DAG.getNode(ISD::FADD, dl, VT, N0,
6570                        GetNegatedExpression(N1, DAG, LegalOperations));
6571
6572   // If 'unsafe math' is enabled, fold
6573   //    (fsub x, x) -> 0.0 &
6574   //    (fsub x, (fadd x, y)) -> (fneg y) &
6575   //    (fsub x, (fadd y, x)) -> (fneg y)
6576   if (DAG.getTarget().Options.UnsafeFPMath) {
6577     if (N0 == N1)
6578       return DAG.getConstantFP(0.0f, VT);
6579
6580     if (N1.getOpcode() == ISD::FADD) {
6581       SDValue N10 = N1->getOperand(0);
6582       SDValue N11 = N1->getOperand(1);
6583
6584       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6585                                           &DAG.getTarget().Options))
6586         return GetNegatedExpression(N11, DAG, LegalOperations);
6587
6588       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6589                                           &DAG.getTarget().Options))
6590         return GetNegatedExpression(N10, DAG, LegalOperations);
6591     }
6592   }
6593
6594   // FSUB -> FMA combines:
6595   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6596        DAG.getTarget().Options.UnsafeFPMath) &&
6597       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6598       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6599
6600     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6601     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6602       return DAG.getNode(ISD::FMA, dl, VT,
6603                          N0.getOperand(0), N0.getOperand(1),
6604                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6605
6606     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6607     // Note: Commutes FSUB operands.
6608     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6609       return DAG.getNode(ISD::FMA, dl, VT,
6610                          DAG.getNode(ISD::FNEG, dl, VT,
6611                          N1.getOperand(0)),
6612                          N1.getOperand(1), N0);
6613
6614     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6615     if (N0.getOpcode() == ISD::FNEG &&
6616         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6617         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6618       SDValue N00 = N0.getOperand(0).getOperand(0);
6619       SDValue N01 = N0.getOperand(0).getOperand(1);
6620       return DAG.getNode(ISD::FMA, dl, VT,
6621                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6622                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6623     }
6624   }
6625
6626   return SDValue();
6627 }
6628
6629 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6630   SDValue N0 = N->getOperand(0);
6631   SDValue N1 = N->getOperand(1);
6632   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6633   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6634   EVT VT = N->getValueType(0);
6635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6636
6637   // fold vector ops
6638   if (VT.isVector()) {
6639     SDValue FoldedVOp = SimplifyVBinOp(N);
6640     if (FoldedVOp.getNode()) return FoldedVOp;
6641   }
6642
6643   // fold (fmul c1, c2) -> c1*c2
6644   if (N0CFP && N1CFP)
6645     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6646   // canonicalize constant to RHS
6647   if (N0CFP && !N1CFP)
6648     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6649   // fold (fmul A, 0) -> 0
6650   if (DAG.getTarget().Options.UnsafeFPMath &&
6651       N1CFP && N1CFP->getValueAPF().isZero())
6652     return N1;
6653   // fold (fmul A, 0) -> 0, vector edition.
6654   if (DAG.getTarget().Options.UnsafeFPMath &&
6655       ISD::isBuildVectorAllZeros(N1.getNode()))
6656     return N1;
6657   // fold (fmul A, 1.0) -> A
6658   if (N1CFP && N1CFP->isExactlyValue(1.0))
6659     return N0;
6660   // fold (fmul X, 2.0) -> (fadd X, X)
6661   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6662     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6663   // fold (fmul X, -1.0) -> (fneg X)
6664   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6665     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6666       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6667
6668   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6669   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6670                                        &DAG.getTarget().Options)) {
6671     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6672                                          &DAG.getTarget().Options)) {
6673       // Both can be negated for free, check to see if at least one is cheaper
6674       // negated.
6675       if (LHSNeg == 2 || RHSNeg == 2)
6676         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6677                            GetNegatedExpression(N0, DAG, LegalOperations),
6678                            GetNegatedExpression(N1, DAG, LegalOperations));
6679     }
6680   }
6681
6682   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6683   if (DAG.getTarget().Options.UnsafeFPMath &&
6684       N1CFP && N0.getOpcode() == ISD::FMUL &&
6685       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6686     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6687                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6688                                    N0.getOperand(1), N1));
6689
6690   return SDValue();
6691 }
6692
6693 SDValue DAGCombiner::visitFMA(SDNode *N) {
6694   SDValue N0 = N->getOperand(0);
6695   SDValue N1 = N->getOperand(1);
6696   SDValue N2 = N->getOperand(2);
6697   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6698   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6699   EVT VT = N->getValueType(0);
6700   SDLoc dl(N);
6701
6702   if (DAG.getTarget().Options.UnsafeFPMath) {
6703     if (N0CFP && N0CFP->isZero())
6704       return N2;
6705     if (N1CFP && N1CFP->isZero())
6706       return N2;
6707   }
6708   if (N0CFP && N0CFP->isExactlyValue(1.0))
6709     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6710   if (N1CFP && N1CFP->isExactlyValue(1.0))
6711     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6712
6713   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6714   if (N0CFP && !N1CFP)
6715     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6716
6717   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6718   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6719       N2.getOpcode() == ISD::FMUL &&
6720       N0 == N2.getOperand(0) &&
6721       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6722     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6723                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6724   }
6725
6726
6727   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6728   if (DAG.getTarget().Options.UnsafeFPMath &&
6729       N0.getOpcode() == ISD::FMUL && N1CFP &&
6730       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6731     return DAG.getNode(ISD::FMA, dl, VT,
6732                        N0.getOperand(0),
6733                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6734                        N2);
6735   }
6736
6737   // (fma x, 1, y) -> (fadd x, y)
6738   // (fma x, -1, y) -> (fadd (fneg x), y)
6739   if (N1CFP) {
6740     if (N1CFP->isExactlyValue(1.0))
6741       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6742
6743     if (N1CFP->isExactlyValue(-1.0) &&
6744         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6745       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6746       AddToWorkList(RHSNeg.getNode());
6747       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6748     }
6749   }
6750
6751   // (fma x, c, x) -> (fmul x, (c+1))
6752   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6753     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6754                        DAG.getNode(ISD::FADD, dl, VT,
6755                                    N1, DAG.getConstantFP(1.0, VT)));
6756
6757   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6758   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6759       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6760     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6761                        DAG.getNode(ISD::FADD, dl, VT,
6762                                    N1, DAG.getConstantFP(-1.0, VT)));
6763
6764
6765   return SDValue();
6766 }
6767
6768 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6769   SDValue N0 = N->getOperand(0);
6770   SDValue N1 = N->getOperand(1);
6771   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6772   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6773   EVT VT = N->getValueType(0);
6774   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6775
6776   // fold vector ops
6777   if (VT.isVector()) {
6778     SDValue FoldedVOp = SimplifyVBinOp(N);
6779     if (FoldedVOp.getNode()) return FoldedVOp;
6780   }
6781
6782   // fold (fdiv c1, c2) -> c1/c2
6783   if (N0CFP && N1CFP)
6784     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6785
6786   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6787   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6788     // Compute the reciprocal 1.0 / c2.
6789     APFloat N1APF = N1CFP->getValueAPF();
6790     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6791     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6792     // Only do the transform if the reciprocal is a legal fp immediate that
6793     // isn't too nasty (eg NaN, denormal, ...).
6794     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6795         (!LegalOperations ||
6796          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6797          // backend)... we should handle this gracefully after Legalize.
6798          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6799          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6800          TLI.isFPImmLegal(Recip, VT)))
6801       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6802                          DAG.getConstantFP(Recip, VT));
6803   }
6804
6805   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6806   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6807                                        &DAG.getTarget().Options)) {
6808     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6809                                          &DAG.getTarget().Options)) {
6810       // Both can be negated for free, check to see if at least one is cheaper
6811       // negated.
6812       if (LHSNeg == 2 || RHSNeg == 2)
6813         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6814                            GetNegatedExpression(N0, DAG, LegalOperations),
6815                            GetNegatedExpression(N1, DAG, LegalOperations));
6816     }
6817   }
6818
6819   return SDValue();
6820 }
6821
6822 SDValue DAGCombiner::visitFREM(SDNode *N) {
6823   SDValue N0 = N->getOperand(0);
6824   SDValue N1 = N->getOperand(1);
6825   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6826   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6827   EVT VT = N->getValueType(0);
6828
6829   // fold (frem c1, c2) -> fmod(c1,c2)
6830   if (N0CFP && N1CFP)
6831     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6832
6833   return SDValue();
6834 }
6835
6836 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6837   SDValue N0 = N->getOperand(0);
6838   SDValue N1 = N->getOperand(1);
6839   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6840   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6841   EVT VT = N->getValueType(0);
6842
6843   if (N0CFP && N1CFP)  // Constant fold
6844     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6845
6846   if (N1CFP) {
6847     const APFloat& V = N1CFP->getValueAPF();
6848     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6849     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6850     if (!V.isNegative()) {
6851       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6852         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6853     } else {
6854       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6855         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6856                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6857     }
6858   }
6859
6860   // copysign(fabs(x), y) -> copysign(x, y)
6861   // copysign(fneg(x), y) -> copysign(x, y)
6862   // copysign(copysign(x,z), y) -> copysign(x, y)
6863   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6864       N0.getOpcode() == ISD::FCOPYSIGN)
6865     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6866                        N0.getOperand(0), N1);
6867
6868   // copysign(x, abs(y)) -> abs(x)
6869   if (N1.getOpcode() == ISD::FABS)
6870     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6871
6872   // copysign(x, copysign(y,z)) -> copysign(x, z)
6873   if (N1.getOpcode() == ISD::FCOPYSIGN)
6874     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6875                        N0, N1.getOperand(1));
6876
6877   // copysign(x, fp_extend(y)) -> copysign(x, y)
6878   // copysign(x, fp_round(y)) -> copysign(x, y)
6879   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6880     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6881                        N0, N1.getOperand(0));
6882
6883   return SDValue();
6884 }
6885
6886 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6887   SDValue N0 = N->getOperand(0);
6888   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6889   EVT VT = N->getValueType(0);
6890   EVT OpVT = N0.getValueType();
6891
6892   // fold (sint_to_fp c1) -> c1fp
6893   if (N0C &&
6894       // ...but only if the target supports immediate floating-point values
6895       (!LegalOperations ||
6896        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6897     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6898
6899   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6900   // but UINT_TO_FP is legal on this target, try to convert.
6901   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6902       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6903     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6904     if (DAG.SignBitIsZero(N0))
6905       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6906   }
6907
6908   // The next optimizations are desirable only if SELECT_CC can be lowered.
6909   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6910   // having to say they don't support SELECT_CC on every type the DAG knows
6911   // about, since there is no way to mark an opcode illegal at all value types
6912   // (See also visitSELECT)
6913   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6914     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6915     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6916         !VT.isVector() &&
6917         (!LegalOperations ||
6918          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6919       SDValue Ops[] =
6920         { N0.getOperand(0), N0.getOperand(1),
6921           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6922           N0.getOperand(2) };
6923       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6924     }
6925
6926     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6927     //      (select_cc x, y, 1.0, 0.0,, cc)
6928     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6929         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6930         (!LegalOperations ||
6931          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6932       SDValue Ops[] =
6933         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6934           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6935           N0.getOperand(0).getOperand(2) };
6936       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6937     }
6938   }
6939
6940   return SDValue();
6941 }
6942
6943 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6944   SDValue N0 = N->getOperand(0);
6945   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6946   EVT VT = N->getValueType(0);
6947   EVT OpVT = N0.getValueType();
6948
6949   // fold (uint_to_fp c1) -> c1fp
6950   if (N0C &&
6951       // ...but only if the target supports immediate floating-point values
6952       (!LegalOperations ||
6953        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6954     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6955
6956   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6957   // but SINT_TO_FP is legal on this target, try to convert.
6958   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6959       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6960     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6961     if (DAG.SignBitIsZero(N0))
6962       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6963   }
6964
6965   // The next optimizations are desirable only if SELECT_CC can be lowered.
6966   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6967   // having to say they don't support SELECT_CC on every type the DAG knows
6968   // about, since there is no way to mark an opcode illegal at all value types
6969   // (See also visitSELECT)
6970   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6971     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6972
6973     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6974         (!LegalOperations ||
6975          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976       SDValue Ops[] =
6977         { N0.getOperand(0), N0.getOperand(1),
6978           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6979           N0.getOperand(2) };
6980       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6981     }
6982   }
6983
6984   return SDValue();
6985 }
6986
6987 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6988   SDValue N0 = N->getOperand(0);
6989   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6990   EVT VT = N->getValueType(0);
6991
6992   // fold (fp_to_sint c1fp) -> c1
6993   if (N0CFP)
6994     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6995
6996   return SDValue();
6997 }
6998
6999 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7000   SDValue N0 = N->getOperand(0);
7001   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7002   EVT VT = N->getValueType(0);
7003
7004   // fold (fp_to_uint c1fp) -> c1
7005   if (N0CFP)
7006     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7007
7008   return SDValue();
7009 }
7010
7011 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7012   SDValue N0 = N->getOperand(0);
7013   SDValue N1 = N->getOperand(1);
7014   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7015   EVT VT = N->getValueType(0);
7016
7017   // fold (fp_round c1fp) -> c1fp
7018   if (N0CFP)
7019     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7020
7021   // fold (fp_round (fp_extend x)) -> x
7022   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7023     return N0.getOperand(0);
7024
7025   // fold (fp_round (fp_round x)) -> (fp_round x)
7026   if (N0.getOpcode() == ISD::FP_ROUND) {
7027     // This is a value preserving truncation if both round's are.
7028     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7029                    N0.getNode()->getConstantOperandVal(1) == 1;
7030     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7031                        DAG.getIntPtrConstant(IsTrunc));
7032   }
7033
7034   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7035   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7036     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7037                               N0.getOperand(0), N1);
7038     AddToWorkList(Tmp.getNode());
7039     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7040                        Tmp, N0.getOperand(1));
7041   }
7042
7043   return SDValue();
7044 }
7045
7046 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7047   SDValue N0 = N->getOperand(0);
7048   EVT VT = N->getValueType(0);
7049   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7050   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7051
7052   // fold (fp_round_inreg c1fp) -> c1fp
7053   if (N0CFP && isTypeLegal(EVT)) {
7054     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7055     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7056   }
7057
7058   return SDValue();
7059 }
7060
7061 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7062   SDValue N0 = N->getOperand(0);
7063   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7064   EVT VT = N->getValueType(0);
7065
7066   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7067   if (N->hasOneUse() &&
7068       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7069     return SDValue();
7070
7071   // fold (fp_extend c1fp) -> c1fp
7072   if (N0CFP)
7073     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7074
7075   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7076   // value of X.
7077   if (N0.getOpcode() == ISD::FP_ROUND
7078       && N0.getNode()->getConstantOperandVal(1) == 1) {
7079     SDValue In = N0.getOperand(0);
7080     if (In.getValueType() == VT) return In;
7081     if (VT.bitsLT(In.getValueType()))
7082       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7083                          In, N0.getOperand(1));
7084     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7085   }
7086
7087   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7088   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7089       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7090        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7091     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7092     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7093                                      LN0->getChain(),
7094                                      LN0->getBasePtr(), N0.getValueType(),
7095                                      LN0->getMemOperand());
7096     CombineTo(N, ExtLoad);
7097     CombineTo(N0.getNode(),
7098               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7099                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7100               ExtLoad.getValue(1));
7101     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7102   }
7103
7104   return SDValue();
7105 }
7106
7107 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7108   SDValue N0 = N->getOperand(0);
7109   EVT VT = N->getValueType(0);
7110
7111   if (VT.isVector()) {
7112     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7113     if (FoldedVOp.getNode()) return FoldedVOp;
7114   }
7115
7116   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7117                          &DAG.getTarget().Options))
7118     return GetNegatedExpression(N0, DAG, LegalOperations);
7119
7120   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7121   // constant pool values.
7122   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7123       !VT.isVector() &&
7124       N0.getNode()->hasOneUse() &&
7125       N0.getOperand(0).getValueType().isInteger()) {
7126     SDValue Int = N0.getOperand(0);
7127     EVT IntVT = Int.getValueType();
7128     if (IntVT.isInteger() && !IntVT.isVector()) {
7129       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7130               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7131       AddToWorkList(Int.getNode());
7132       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7133                          VT, Int);
7134     }
7135   }
7136
7137   // (fneg (fmul c, x)) -> (fmul -c, x)
7138   if (N0.getOpcode() == ISD::FMUL) {
7139     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7140     if (CFP1)
7141       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7142                          N0.getOperand(0),
7143                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7144                                      N0.getOperand(1)));
7145   }
7146
7147   return SDValue();
7148 }
7149
7150 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7151   SDValue N0 = N->getOperand(0);
7152   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7153   EVT VT = N->getValueType(0);
7154
7155   // fold (fceil c1) -> fceil(c1)
7156   if (N0CFP)
7157     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7158
7159   return SDValue();
7160 }
7161
7162 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7163   SDValue N0 = N->getOperand(0);
7164   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7165   EVT VT = N->getValueType(0);
7166
7167   // fold (ftrunc c1) -> ftrunc(c1)
7168   if (N0CFP)
7169     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7170
7171   return SDValue();
7172 }
7173
7174 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7175   SDValue N0 = N->getOperand(0);
7176   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7177   EVT VT = N->getValueType(0);
7178
7179   // fold (ffloor c1) -> ffloor(c1)
7180   if (N0CFP)
7181     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7182
7183   return SDValue();
7184 }
7185
7186 SDValue DAGCombiner::visitFABS(SDNode *N) {
7187   SDValue N0 = N->getOperand(0);
7188   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7189   EVT VT = N->getValueType(0);
7190
7191   if (VT.isVector()) {
7192     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7193     if (FoldedVOp.getNode()) return FoldedVOp;
7194   }
7195
7196   // fold (fabs c1) -> fabs(c1)
7197   if (N0CFP)
7198     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7199   // fold (fabs (fabs x)) -> (fabs x)
7200   if (N0.getOpcode() == ISD::FABS)
7201     return N->getOperand(0);
7202   // fold (fabs (fneg x)) -> (fabs x)
7203   // fold (fabs (fcopysign x, y)) -> (fabs x)
7204   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7205     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7206
7207   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7208   // constant pool values.
7209   if (!TLI.isFAbsFree(VT) &&
7210       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7211       N0.getOperand(0).getValueType().isInteger() &&
7212       !N0.getOperand(0).getValueType().isVector()) {
7213     SDValue Int = N0.getOperand(0);
7214     EVT IntVT = Int.getValueType();
7215     if (IntVT.isInteger() && !IntVT.isVector()) {
7216       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7217              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7218       AddToWorkList(Int.getNode());
7219       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7220                          N->getValueType(0), Int);
7221     }
7222   }
7223
7224   return SDValue();
7225 }
7226
7227 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7228   SDValue Chain = N->getOperand(0);
7229   SDValue N1 = N->getOperand(1);
7230   SDValue N2 = N->getOperand(2);
7231
7232   // If N is a constant we could fold this into a fallthrough or unconditional
7233   // branch. However that doesn't happen very often in normal code, because
7234   // Instcombine/SimplifyCFG should have handled the available opportunities.
7235   // If we did this folding here, it would be necessary to update the
7236   // MachineBasicBlock CFG, which is awkward.
7237
7238   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7239   // on the target.
7240   if (N1.getOpcode() == ISD::SETCC &&
7241       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7242                                    N1.getOperand(0).getValueType())) {
7243     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7244                        Chain, N1.getOperand(2),
7245                        N1.getOperand(0), N1.getOperand(1), N2);
7246   }
7247
7248   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7249       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7250        (N1.getOperand(0).hasOneUse() &&
7251         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7252     SDNode *Trunc = 0;
7253     if (N1.getOpcode() == ISD::TRUNCATE) {
7254       // Look pass the truncate.
7255       Trunc = N1.getNode();
7256       N1 = N1.getOperand(0);
7257     }
7258
7259     // Match this pattern so that we can generate simpler code:
7260     //
7261     //   %a = ...
7262     //   %b = and i32 %a, 2
7263     //   %c = srl i32 %b, 1
7264     //   brcond i32 %c ...
7265     //
7266     // into
7267     //
7268     //   %a = ...
7269     //   %b = and i32 %a, 2
7270     //   %c = setcc eq %b, 0
7271     //   brcond %c ...
7272     //
7273     // This applies only when the AND constant value has one bit set and the
7274     // SRL constant is equal to the log2 of the AND constant. The back-end is
7275     // smart enough to convert the result into a TEST/JMP sequence.
7276     SDValue Op0 = N1.getOperand(0);
7277     SDValue Op1 = N1.getOperand(1);
7278
7279     if (Op0.getOpcode() == ISD::AND &&
7280         Op1.getOpcode() == ISD::Constant) {
7281       SDValue AndOp1 = Op0.getOperand(1);
7282
7283       if (AndOp1.getOpcode() == ISD::Constant) {
7284         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7285
7286         if (AndConst.isPowerOf2() &&
7287             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7288           SDValue SetCC =
7289             DAG.getSetCC(SDLoc(N),
7290                          getSetCCResultType(Op0.getValueType()),
7291                          Op0, DAG.getConstant(0, Op0.getValueType()),
7292                          ISD::SETNE);
7293
7294           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7295                                           MVT::Other, Chain, SetCC, N2);
7296           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7297           // will convert it back to (X & C1) >> C2.
7298           CombineTo(N, NewBRCond, false);
7299           // Truncate is dead.
7300           if (Trunc) {
7301             removeFromWorkList(Trunc);
7302             DAG.DeleteNode(Trunc);
7303           }
7304           // Replace the uses of SRL with SETCC
7305           WorkListRemover DeadNodes(*this);
7306           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7307           removeFromWorkList(N1.getNode());
7308           DAG.DeleteNode(N1.getNode());
7309           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7310         }
7311       }
7312     }
7313
7314     if (Trunc)
7315       // Restore N1 if the above transformation doesn't match.
7316       N1 = N->getOperand(1);
7317   }
7318
7319   // Transform br(xor(x, y)) -> br(x != y)
7320   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7321   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7322     SDNode *TheXor = N1.getNode();
7323     SDValue Op0 = TheXor->getOperand(0);
7324     SDValue Op1 = TheXor->getOperand(1);
7325     if (Op0.getOpcode() == Op1.getOpcode()) {
7326       // Avoid missing important xor optimizations.
7327       SDValue Tmp = visitXOR(TheXor);
7328       if (Tmp.getNode()) {
7329         if (Tmp.getNode() != TheXor) {
7330           DEBUG(dbgs() << "\nReplacing.8 ";
7331                 TheXor->dump(&DAG);
7332                 dbgs() << "\nWith: ";
7333                 Tmp.getNode()->dump(&DAG);
7334                 dbgs() << '\n');
7335           WorkListRemover DeadNodes(*this);
7336           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7337           removeFromWorkList(TheXor);
7338           DAG.DeleteNode(TheXor);
7339           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7340                              MVT::Other, Chain, Tmp, N2);
7341         }
7342
7343         // visitXOR has changed XOR's operands or replaced the XOR completely,
7344         // bail out.
7345         return SDValue(N, 0);
7346       }
7347     }
7348
7349     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7350       bool Equal = false;
7351       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7352         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7353             Op0.getOpcode() == ISD::XOR) {
7354           TheXor = Op0.getNode();
7355           Equal = true;
7356         }
7357
7358       EVT SetCCVT = N1.getValueType();
7359       if (LegalTypes)
7360         SetCCVT = getSetCCResultType(SetCCVT);
7361       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7362                                    SetCCVT,
7363                                    Op0, Op1,
7364                                    Equal ? ISD::SETEQ : ISD::SETNE);
7365       // Replace the uses of XOR with SETCC
7366       WorkListRemover DeadNodes(*this);
7367       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7368       removeFromWorkList(N1.getNode());
7369       DAG.DeleteNode(N1.getNode());
7370       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7371                          MVT::Other, Chain, SetCC, N2);
7372     }
7373   }
7374
7375   return SDValue();
7376 }
7377
7378 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7379 //
7380 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7381   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7382   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7383
7384   // If N is a constant we could fold this into a fallthrough or unconditional
7385   // branch. However that doesn't happen very often in normal code, because
7386   // Instcombine/SimplifyCFG should have handled the available opportunities.
7387   // If we did this folding here, it would be necessary to update the
7388   // MachineBasicBlock CFG, which is awkward.
7389
7390   // Use SimplifySetCC to simplify SETCC's.
7391   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7392                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7393                                false);
7394   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7395
7396   // fold to a simpler setcc
7397   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7398     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7399                        N->getOperand(0), Simp.getOperand(2),
7400                        Simp.getOperand(0), Simp.getOperand(1),
7401                        N->getOperand(4));
7402
7403   return SDValue();
7404 }
7405
7406 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7407 /// uses N as its base pointer and that N may be folded in the load / store
7408 /// addressing mode.
7409 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7410                                     SelectionDAG &DAG,
7411                                     const TargetLowering &TLI) {
7412   EVT VT;
7413   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7414     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7415       return false;
7416     VT = Use->getValueType(0);
7417   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7418     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7419       return false;
7420     VT = ST->getValue().getValueType();
7421   } else
7422     return false;
7423
7424   TargetLowering::AddrMode AM;
7425   if (N->getOpcode() == ISD::ADD) {
7426     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7427     if (Offset)
7428       // [reg +/- imm]
7429       AM.BaseOffs = Offset->getSExtValue();
7430     else
7431       // [reg +/- reg]
7432       AM.Scale = 1;
7433   } else if (N->getOpcode() == ISD::SUB) {
7434     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7435     if (Offset)
7436       // [reg +/- imm]
7437       AM.BaseOffs = -Offset->getSExtValue();
7438     else
7439       // [reg +/- reg]
7440       AM.Scale = 1;
7441   } else
7442     return false;
7443
7444   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7445 }
7446
7447 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7448 /// pre-indexed load / store when the base pointer is an add or subtract
7449 /// and it has other uses besides the load / store. After the
7450 /// transformation, the new indexed load / store has effectively folded
7451 /// the add / subtract in and all of its other uses are redirected to the
7452 /// new load / store.
7453 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7454   if (Level < AfterLegalizeDAG)
7455     return false;
7456
7457   bool isLoad = true;
7458   SDValue Ptr;
7459   EVT VT;
7460   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7461     if (LD->isIndexed())
7462       return false;
7463     VT = LD->getMemoryVT();
7464     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7465         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7466       return false;
7467     Ptr = LD->getBasePtr();
7468   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7469     if (ST->isIndexed())
7470       return false;
7471     VT = ST->getMemoryVT();
7472     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7473         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7474       return false;
7475     Ptr = ST->getBasePtr();
7476     isLoad = false;
7477   } else {
7478     return false;
7479   }
7480
7481   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7482   // out.  There is no reason to make this a preinc/predec.
7483   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7484       Ptr.getNode()->hasOneUse())
7485     return false;
7486
7487   // Ask the target to do addressing mode selection.
7488   SDValue BasePtr;
7489   SDValue Offset;
7490   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7491   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7492     return false;
7493
7494   // Backends without true r+i pre-indexed forms may need to pass a
7495   // constant base with a variable offset so that constant coercion
7496   // will work with the patterns in canonical form.
7497   bool Swapped = false;
7498   if (isa<ConstantSDNode>(BasePtr)) {
7499     std::swap(BasePtr, Offset);
7500     Swapped = true;
7501   }
7502
7503   // Don't create a indexed load / store with zero offset.
7504   if (isa<ConstantSDNode>(Offset) &&
7505       cast<ConstantSDNode>(Offset)->isNullValue())
7506     return false;
7507
7508   // Try turning it into a pre-indexed load / store except when:
7509   // 1) The new base ptr is a frame index.
7510   // 2) If N is a store and the new base ptr is either the same as or is a
7511   //    predecessor of the value being stored.
7512   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7513   //    that would create a cycle.
7514   // 4) All uses are load / store ops that use it as old base ptr.
7515
7516   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7517   // (plus the implicit offset) to a register to preinc anyway.
7518   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7519     return false;
7520
7521   // Check #2.
7522   if (!isLoad) {
7523     SDValue Val = cast<StoreSDNode>(N)->getValue();
7524     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7525       return false;
7526   }
7527
7528   // If the offset is a constant, there may be other adds of constants that
7529   // can be folded with this one. We should do this to avoid having to keep
7530   // a copy of the original base pointer.
7531   SmallVector<SDNode *, 16> OtherUses;
7532   if (isa<ConstantSDNode>(Offset))
7533     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7534          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7535       SDNode *Use = *I;
7536       if (Use == Ptr.getNode())
7537         continue;
7538
7539       if (Use->isPredecessorOf(N))
7540         continue;
7541
7542       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7543         OtherUses.clear();
7544         break;
7545       }
7546
7547       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7548       if (Op1.getNode() == BasePtr.getNode())
7549         std::swap(Op0, Op1);
7550       assert(Op0.getNode() == BasePtr.getNode() &&
7551              "Use of ADD/SUB but not an operand");
7552
7553       if (!isa<ConstantSDNode>(Op1)) {
7554         OtherUses.clear();
7555         break;
7556       }
7557
7558       // FIXME: In some cases, we can be smarter about this.
7559       if (Op1.getValueType() != Offset.getValueType()) {
7560         OtherUses.clear();
7561         break;
7562       }
7563
7564       OtherUses.push_back(Use);
7565     }
7566
7567   if (Swapped)
7568     std::swap(BasePtr, Offset);
7569
7570   // Now check for #3 and #4.
7571   bool RealUse = false;
7572
7573   // Caches for hasPredecessorHelper
7574   SmallPtrSet<const SDNode *, 32> Visited;
7575   SmallVector<const SDNode *, 16> Worklist;
7576
7577   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7578          E = Ptr.getNode()->use_end(); I != E; ++I) {
7579     SDNode *Use = *I;
7580     if (Use == N)
7581       continue;
7582     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7583       return false;
7584
7585     // If Ptr may be folded in addressing mode of other use, then it's
7586     // not profitable to do this transformation.
7587     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7588       RealUse = true;
7589   }
7590
7591   if (!RealUse)
7592     return false;
7593
7594   SDValue Result;
7595   if (isLoad)
7596     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7597                                 BasePtr, Offset, AM);
7598   else
7599     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7600                                  BasePtr, Offset, AM);
7601   ++PreIndexedNodes;
7602   ++NodesCombined;
7603   DEBUG(dbgs() << "\nReplacing.4 ";
7604         N->dump(&DAG);
7605         dbgs() << "\nWith: ";
7606         Result.getNode()->dump(&DAG);
7607         dbgs() << '\n');
7608   WorkListRemover DeadNodes(*this);
7609   if (isLoad) {
7610     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7611     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7612   } else {
7613     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7614   }
7615
7616   // Finally, since the node is now dead, remove it from the graph.
7617   DAG.DeleteNode(N);
7618
7619   if (Swapped)
7620     std::swap(BasePtr, Offset);
7621
7622   // Replace other uses of BasePtr that can be updated to use Ptr
7623   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7624     unsigned OffsetIdx = 1;
7625     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7626       OffsetIdx = 0;
7627     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7628            BasePtr.getNode() && "Expected BasePtr operand");
7629
7630     // We need to replace ptr0 in the following expression:
7631     //   x0 * offset0 + y0 * ptr0 = t0
7632     // knowing that
7633     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7634     //
7635     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7636     // indexed load/store and the expresion that needs to be re-written.
7637     //
7638     // Therefore, we have:
7639     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7640
7641     ConstantSDNode *CN =
7642       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7643     int X0, X1, Y0, Y1;
7644     APInt Offset0 = CN->getAPIntValue();
7645     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7646
7647     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7648     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7649     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7650     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7651
7652     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7653
7654     APInt CNV = Offset0;
7655     if (X0 < 0) CNV = -CNV;
7656     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7657     else CNV = CNV - Offset1;
7658
7659     // We can now generate the new expression.
7660     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7661     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7662
7663     SDValue NewUse = DAG.getNode(Opcode,
7664                                  SDLoc(OtherUses[i]),
7665                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7666     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7667     removeFromWorkList(OtherUses[i]);
7668     DAG.DeleteNode(OtherUses[i]);
7669   }
7670
7671   // Replace the uses of Ptr with uses of the updated base value.
7672   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7673   removeFromWorkList(Ptr.getNode());
7674   DAG.DeleteNode(Ptr.getNode());
7675
7676   return true;
7677 }
7678
7679 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7680 /// add / sub of the base pointer node into a post-indexed load / store.
7681 /// The transformation folded the add / subtract into the new indexed
7682 /// load / store effectively and all of its uses are redirected to the
7683 /// new load / store.
7684 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7685   if (Level < AfterLegalizeDAG)
7686     return false;
7687
7688   bool isLoad = true;
7689   SDValue Ptr;
7690   EVT VT;
7691   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7692     if (LD->isIndexed())
7693       return false;
7694     VT = LD->getMemoryVT();
7695     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7696         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7697       return false;
7698     Ptr = LD->getBasePtr();
7699   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7700     if (ST->isIndexed())
7701       return false;
7702     VT = ST->getMemoryVT();
7703     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7704         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7705       return false;
7706     Ptr = ST->getBasePtr();
7707     isLoad = false;
7708   } else {
7709     return false;
7710   }
7711
7712   if (Ptr.getNode()->hasOneUse())
7713     return false;
7714
7715   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7716          E = Ptr.getNode()->use_end(); I != E; ++I) {
7717     SDNode *Op = *I;
7718     if (Op == N ||
7719         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7720       continue;
7721
7722     SDValue BasePtr;
7723     SDValue Offset;
7724     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7725     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7726       // Don't create a indexed load / store with zero offset.
7727       if (isa<ConstantSDNode>(Offset) &&
7728           cast<ConstantSDNode>(Offset)->isNullValue())
7729         continue;
7730
7731       // Try turning it into a post-indexed load / store except when
7732       // 1) All uses are load / store ops that use it as base ptr (and
7733       //    it may be folded as addressing mmode).
7734       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7735       //    nor a successor of N. Otherwise, if Op is folded that would
7736       //    create a cycle.
7737
7738       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7739         continue;
7740
7741       // Check for #1.
7742       bool TryNext = false;
7743       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7744              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7745         SDNode *Use = *II;
7746         if (Use == Ptr.getNode())
7747           continue;
7748
7749         // If all the uses are load / store addresses, then don't do the
7750         // transformation.
7751         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7752           bool RealUse = false;
7753           for (SDNode::use_iterator III = Use->use_begin(),
7754                  EEE = Use->use_end(); III != EEE; ++III) {
7755             SDNode *UseUse = *III;
7756             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7757               RealUse = true;
7758           }
7759
7760           if (!RealUse) {
7761             TryNext = true;
7762             break;
7763           }
7764         }
7765       }
7766
7767       if (TryNext)
7768         continue;
7769
7770       // Check for #2
7771       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7772         SDValue Result = isLoad
7773           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7774                                BasePtr, Offset, AM)
7775           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7776                                 BasePtr, Offset, AM);
7777         ++PostIndexedNodes;
7778         ++NodesCombined;
7779         DEBUG(dbgs() << "\nReplacing.5 ";
7780               N->dump(&DAG);
7781               dbgs() << "\nWith: ";
7782               Result.getNode()->dump(&DAG);
7783               dbgs() << '\n');
7784         WorkListRemover DeadNodes(*this);
7785         if (isLoad) {
7786           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7787           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7788         } else {
7789           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7790         }
7791
7792         // Finally, since the node is now dead, remove it from the graph.
7793         DAG.DeleteNode(N);
7794
7795         // Replace the uses of Use with uses of the updated base value.
7796         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7797                                       Result.getValue(isLoad ? 1 : 0));
7798         removeFromWorkList(Op);
7799         DAG.DeleteNode(Op);
7800         return true;
7801       }
7802     }
7803   }
7804
7805   return false;
7806 }
7807
7808 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7809   LoadSDNode *LD  = cast<LoadSDNode>(N);
7810   SDValue Chain = LD->getChain();
7811   SDValue Ptr   = LD->getBasePtr();
7812
7813   // If load is not volatile and there are no uses of the loaded value (and
7814   // the updated indexed value in case of indexed loads), change uses of the
7815   // chain value into uses of the chain input (i.e. delete the dead load).
7816   if (!LD->isVolatile()) {
7817     if (N->getValueType(1) == MVT::Other) {
7818       // Unindexed loads.
7819       if (!N->hasAnyUseOfValue(0)) {
7820         // It's not safe to use the two value CombineTo variant here. e.g.
7821         // v1, chain2 = load chain1, loc
7822         // v2, chain3 = load chain2, loc
7823         // v3         = add v2, c
7824         // Now we replace use of chain2 with chain1.  This makes the second load
7825         // isomorphic to the one we are deleting, and thus makes this load live.
7826         DEBUG(dbgs() << "\nReplacing.6 ";
7827               N->dump(&DAG);
7828               dbgs() << "\nWith chain: ";
7829               Chain.getNode()->dump(&DAG);
7830               dbgs() << "\n");
7831         WorkListRemover DeadNodes(*this);
7832         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7833
7834         if (N->use_empty()) {
7835           removeFromWorkList(N);
7836           DAG.DeleteNode(N);
7837         }
7838
7839         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7840       }
7841     } else {
7842       // Indexed loads.
7843       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7844       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7845         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7846         DEBUG(dbgs() << "\nReplacing.7 ";
7847               N->dump(&DAG);
7848               dbgs() << "\nWith: ";
7849               Undef.getNode()->dump(&DAG);
7850               dbgs() << " and 2 other values\n");
7851         WorkListRemover DeadNodes(*this);
7852         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7853         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7854                                       DAG.getUNDEF(N->getValueType(1)));
7855         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7856         removeFromWorkList(N);
7857         DAG.DeleteNode(N);
7858         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7859       }
7860     }
7861   }
7862
7863   // If this load is directly stored, replace the load value with the stored
7864   // value.
7865   // TODO: Handle store large -> read small portion.
7866   // TODO: Handle TRUNCSTORE/LOADEXT
7867   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7868     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7869       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7870       if (PrevST->getBasePtr() == Ptr &&
7871           PrevST->getValue().getValueType() == N->getValueType(0))
7872       return CombineTo(N, Chain.getOperand(1), Chain);
7873     }
7874   }
7875
7876   // Try to infer better alignment information than the load already has.
7877   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7878     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7879       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7880         SDValue NewLoad =
7881                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7882                               LD->getValueType(0),
7883                               Chain, Ptr, LD->getPointerInfo(),
7884                               LD->getMemoryVT(),
7885                               LD->isVolatile(), LD->isNonTemporal(), Align,
7886                               LD->getTBAAInfo());
7887         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7888       }
7889     }
7890   }
7891
7892   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7893     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7894 #ifndef NDEBUG
7895   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7896       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7897     UseAA = false;
7898 #endif
7899   if (UseAA && LD->isUnindexed()) {
7900     // Walk up chain skipping non-aliasing memory nodes.
7901     SDValue BetterChain = FindBetterChain(N, Chain);
7902
7903     // If there is a better chain.
7904     if (Chain != BetterChain) {
7905       SDValue ReplLoad;
7906
7907       // Replace the chain to void dependency.
7908       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7909         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7910                                BetterChain, Ptr, LD->getMemOperand());
7911       } else {
7912         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7913                                   LD->getValueType(0),
7914                                   BetterChain, Ptr, LD->getMemoryVT(),
7915                                   LD->getMemOperand());
7916       }
7917
7918       // Create token factor to keep old chain connected.
7919       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7920                                   MVT::Other, Chain, ReplLoad.getValue(1));
7921
7922       // Make sure the new and old chains are cleaned up.
7923       AddToWorkList(Token.getNode());
7924
7925       // Replace uses with load result and token factor. Don't add users
7926       // to work list.
7927       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7928     }
7929   }
7930
7931   // Try transforming N to an indexed load.
7932   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7933     return SDValue(N, 0);
7934
7935   // Try to slice up N to more direct loads if the slices are mapped to
7936   // different register banks or pairing can take place.
7937   if (SliceUpLoad(N))
7938     return SDValue(N, 0);
7939
7940   return SDValue();
7941 }
7942
7943 namespace {
7944 /// \brief Helper structure used to slice a load in smaller loads.
7945 /// Basically a slice is obtained from the following sequence:
7946 /// Origin = load Ty1, Base
7947 /// Shift = srl Ty1 Origin, CstTy Amount
7948 /// Inst = trunc Shift to Ty2
7949 ///
7950 /// Then, it will be rewriten into:
7951 /// Slice = load SliceTy, Base + SliceOffset
7952 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7953 ///
7954 /// SliceTy is deduced from the number of bits that are actually used to
7955 /// build Inst.
7956 struct LoadedSlice {
7957   /// \brief Helper structure used to compute the cost of a slice.
7958   struct Cost {
7959     /// Are we optimizing for code size.
7960     bool ForCodeSize;
7961     /// Various cost.
7962     unsigned Loads;
7963     unsigned Truncates;
7964     unsigned CrossRegisterBanksCopies;
7965     unsigned ZExts;
7966     unsigned Shift;
7967
7968     Cost(bool ForCodeSize = false)
7969         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7970           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7971
7972     /// \brief Get the cost of one isolated slice.
7973     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7974         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7975           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7976       EVT TruncType = LS.Inst->getValueType(0);
7977       EVT LoadedType = LS.getLoadedType();
7978       if (TruncType != LoadedType &&
7979           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7980         ZExts = 1;
7981     }
7982
7983     /// \brief Account for slicing gain in the current cost.
7984     /// Slicing provide a few gains like removing a shift or a
7985     /// truncate. This method allows to grow the cost of the original
7986     /// load with the gain from this slice.
7987     void addSliceGain(const LoadedSlice &LS) {
7988       // Each slice saves a truncate.
7989       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7990       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7991                               LS.Inst->getOperand(0).getValueType()))
7992         ++Truncates;
7993       // If there is a shift amount, this slice gets rid of it.
7994       if (LS.Shift)
7995         ++Shift;
7996       // If this slice can merge a cross register bank copy, account for it.
7997       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7998         ++CrossRegisterBanksCopies;
7999     }
8000
8001     Cost &operator+=(const Cost &RHS) {
8002       Loads += RHS.Loads;
8003       Truncates += RHS.Truncates;
8004       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8005       ZExts += RHS.ZExts;
8006       Shift += RHS.Shift;
8007       return *this;
8008     }
8009
8010     bool operator==(const Cost &RHS) const {
8011       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8012              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8013              ZExts == RHS.ZExts && Shift == RHS.Shift;
8014     }
8015
8016     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8017
8018     bool operator<(const Cost &RHS) const {
8019       // Assume cross register banks copies are as expensive as loads.
8020       // FIXME: Do we want some more target hooks?
8021       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8022       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8023       // Unless we are optimizing for code size, consider the
8024       // expensive operation first.
8025       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8026         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8027       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8028              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8029     }
8030
8031     bool operator>(const Cost &RHS) const { return RHS < *this; }
8032
8033     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8034
8035     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8036   };
8037   // The last instruction that represent the slice. This should be a
8038   // truncate instruction.
8039   SDNode *Inst;
8040   // The original load instruction.
8041   LoadSDNode *Origin;
8042   // The right shift amount in bits from the original load.
8043   unsigned Shift;
8044   // The DAG from which Origin came from.
8045   // This is used to get some contextual information about legal types, etc.
8046   SelectionDAG *DAG;
8047
8048   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8049               unsigned Shift = 0, SelectionDAG *DAG = NULL)
8050       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8051
8052   LoadedSlice(const LoadedSlice &LS)
8053       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8054
8055   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8056   /// \return Result is \p BitWidth and has used bits set to 1 and
8057   ///         not used bits set to 0.
8058   APInt getUsedBits() const {
8059     // Reproduce the trunc(lshr) sequence:
8060     // - Start from the truncated value.
8061     // - Zero extend to the desired bit width.
8062     // - Shift left.
8063     assert(Origin && "No original load to compare against.");
8064     unsigned BitWidth = Origin->getValueSizeInBits(0);
8065     assert(Inst && "This slice is not bound to an instruction");
8066     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8067            "Extracted slice is bigger than the whole type!");
8068     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8069     UsedBits.setAllBits();
8070     UsedBits = UsedBits.zext(BitWidth);
8071     UsedBits <<= Shift;
8072     return UsedBits;
8073   }
8074
8075   /// \brief Get the size of the slice to be loaded in bytes.
8076   unsigned getLoadedSize() const {
8077     unsigned SliceSize = getUsedBits().countPopulation();
8078     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8079     return SliceSize / 8;
8080   }
8081
8082   /// \brief Get the type that will be loaded for this slice.
8083   /// Note: This may not be the final type for the slice.
8084   EVT getLoadedType() const {
8085     assert(DAG && "Missing context");
8086     LLVMContext &Ctxt = *DAG->getContext();
8087     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8088   }
8089
8090   /// \brief Get the alignment of the load used for this slice.
8091   unsigned getAlignment() const {
8092     unsigned Alignment = Origin->getAlignment();
8093     unsigned Offset = getOffsetFromBase();
8094     if (Offset != 0)
8095       Alignment = MinAlign(Alignment, Alignment + Offset);
8096     return Alignment;
8097   }
8098
8099   /// \brief Check if this slice can be rewritten with legal operations.
8100   bool isLegal() const {
8101     // An invalid slice is not legal.
8102     if (!Origin || !Inst || !DAG)
8103       return false;
8104
8105     // Offsets are for indexed load only, we do not handle that.
8106     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8107       return false;
8108
8109     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8110
8111     // Check that the type is legal.
8112     EVT SliceType = getLoadedType();
8113     if (!TLI.isTypeLegal(SliceType))
8114       return false;
8115
8116     // Check that the load is legal for this type.
8117     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8118       return false;
8119
8120     // Check that the offset can be computed.
8121     // 1. Check its type.
8122     EVT PtrType = Origin->getBasePtr().getValueType();
8123     if (PtrType == MVT::Untyped || PtrType.isExtended())
8124       return false;
8125
8126     // 2. Check that it fits in the immediate.
8127     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8128       return false;
8129
8130     // 3. Check that the computation is legal.
8131     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8132       return false;
8133
8134     // Check that the zext is legal if it needs one.
8135     EVT TruncateType = Inst->getValueType(0);
8136     if (TruncateType != SliceType &&
8137         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8138       return false;
8139
8140     return true;
8141   }
8142
8143   /// \brief Get the offset in bytes of this slice in the original chunk of
8144   /// bits.
8145   /// \pre DAG != NULL.
8146   uint64_t getOffsetFromBase() const {
8147     assert(DAG && "Missing context.");
8148     bool IsBigEndian =
8149         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8150     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8151     uint64_t Offset = Shift / 8;
8152     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8153     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8154            "The size of the original loaded type is not a multiple of a"
8155            " byte.");
8156     // If Offset is bigger than TySizeInBytes, it means we are loading all
8157     // zeros. This should have been optimized before in the process.
8158     assert(TySizeInBytes > Offset &&
8159            "Invalid shift amount for given loaded size");
8160     if (IsBigEndian)
8161       Offset = TySizeInBytes - Offset - getLoadedSize();
8162     return Offset;
8163   }
8164
8165   /// \brief Generate the sequence of instructions to load the slice
8166   /// represented by this object and redirect the uses of this slice to
8167   /// this new sequence of instructions.
8168   /// \pre this->Inst && this->Origin are valid Instructions and this
8169   /// object passed the legal check: LoadedSlice::isLegal returned true.
8170   /// \return The last instruction of the sequence used to load the slice.
8171   SDValue loadSlice() const {
8172     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8173     const SDValue &OldBaseAddr = Origin->getBasePtr();
8174     SDValue BaseAddr = OldBaseAddr;
8175     // Get the offset in that chunk of bytes w.r.t. the endianess.
8176     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8177     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8178     if (Offset) {
8179       // BaseAddr = BaseAddr + Offset.
8180       EVT ArithType = BaseAddr.getValueType();
8181       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8182                               DAG->getConstant(Offset, ArithType));
8183     }
8184
8185     // Create the type of the loaded slice according to its size.
8186     EVT SliceType = getLoadedType();
8187
8188     // Create the load for the slice.
8189     SDValue LastInst = DAG->getLoad(
8190         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8191         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8192         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8193     // If the final type is not the same as the loaded type, this means that
8194     // we have to pad with zero. Create a zero extend for that.
8195     EVT FinalType = Inst->getValueType(0);
8196     if (SliceType != FinalType)
8197       LastInst =
8198           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8199     return LastInst;
8200   }
8201
8202   /// \brief Check if this slice can be merged with an expensive cross register
8203   /// bank copy. E.g.,
8204   /// i = load i32
8205   /// f = bitcast i32 i to float
8206   bool canMergeExpensiveCrossRegisterBankCopy() const {
8207     if (!Inst || !Inst->hasOneUse())
8208       return false;
8209     SDNode *Use = *Inst->use_begin();
8210     if (Use->getOpcode() != ISD::BITCAST)
8211       return false;
8212     assert(DAG && "Missing context");
8213     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8214     EVT ResVT = Use->getValueType(0);
8215     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8216     const TargetRegisterClass *ArgRC =
8217         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8218     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8219       return false;
8220
8221     // At this point, we know that we perform a cross-register-bank copy.
8222     // Check if it is expensive.
8223     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8224     // Assume bitcasts are cheap, unless both register classes do not
8225     // explicitly share a common sub class.
8226     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8227       return false;
8228
8229     // Check if it will be merged with the load.
8230     // 1. Check the alignment constraint.
8231     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8232         ResVT.getTypeForEVT(*DAG->getContext()));
8233
8234     if (RequiredAlignment > getAlignment())
8235       return false;
8236
8237     // 2. Check that the load is a legal operation for that type.
8238     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8239       return false;
8240
8241     // 3. Check that we do not have a zext in the way.
8242     if (Inst->getValueType(0) != getLoadedType())
8243       return false;
8244
8245     return true;
8246   }
8247 };
8248 }
8249
8250 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8251 /// \p UsedBits looks like 0..0 1..1 0..0.
8252 static bool areUsedBitsDense(const APInt &UsedBits) {
8253   // If all the bits are one, this is dense!
8254   if (UsedBits.isAllOnesValue())
8255     return true;
8256
8257   // Get rid of the unused bits on the right.
8258   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8259   // Get rid of the unused bits on the left.
8260   if (NarrowedUsedBits.countLeadingZeros())
8261     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8262   // Check that the chunk of bits is completely used.
8263   return NarrowedUsedBits.isAllOnesValue();
8264 }
8265
8266 /// \brief Check whether or not \p First and \p Second are next to each other
8267 /// in memory. This means that there is no hole between the bits loaded
8268 /// by \p First and the bits loaded by \p Second.
8269 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8270                                      const LoadedSlice &Second) {
8271   assert(First.Origin == Second.Origin && First.Origin &&
8272          "Unable to match different memory origins.");
8273   APInt UsedBits = First.getUsedBits();
8274   assert((UsedBits & Second.getUsedBits()) == 0 &&
8275          "Slices are not supposed to overlap.");
8276   UsedBits |= Second.getUsedBits();
8277   return areUsedBitsDense(UsedBits);
8278 }
8279
8280 /// \brief Adjust the \p GlobalLSCost according to the target
8281 /// paring capabilities and the layout of the slices.
8282 /// \pre \p GlobalLSCost should account for at least as many loads as
8283 /// there is in the slices in \p LoadedSlices.
8284 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8285                                  LoadedSlice::Cost &GlobalLSCost) {
8286   unsigned NumberOfSlices = LoadedSlices.size();
8287   // If there is less than 2 elements, no pairing is possible.
8288   if (NumberOfSlices < 2)
8289     return;
8290
8291   // Sort the slices so that elements that are likely to be next to each
8292   // other in memory are next to each other in the list.
8293   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8294             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8295     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8296     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8297   });
8298   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8299   // First (resp. Second) is the first (resp. Second) potentially candidate
8300   // to be placed in a paired load.
8301   const LoadedSlice *First = NULL;
8302   const LoadedSlice *Second = NULL;
8303   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8304                 // Set the beginning of the pair.
8305                                                            First = Second) {
8306
8307     Second = &LoadedSlices[CurrSlice];
8308
8309     // If First is NULL, it means we start a new pair.
8310     // Get to the next slice.
8311     if (!First)
8312       continue;
8313
8314     EVT LoadedType = First->getLoadedType();
8315
8316     // If the types of the slices are different, we cannot pair them.
8317     if (LoadedType != Second->getLoadedType())
8318       continue;
8319
8320     // Check if the target supplies paired loads for this type.
8321     unsigned RequiredAlignment = 0;
8322     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8323       // move to the next pair, this type is hopeless.
8324       Second = NULL;
8325       continue;
8326     }
8327     // Check if we meet the alignment requirement.
8328     if (RequiredAlignment > First->getAlignment())
8329       continue;
8330
8331     // Check that both loads are next to each other in memory.
8332     if (!areSlicesNextToEachOther(*First, *Second))
8333       continue;
8334
8335     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8336     --GlobalLSCost.Loads;
8337     // Move to the next pair.
8338     Second = NULL;
8339   }
8340 }
8341
8342 /// \brief Check the profitability of all involved LoadedSlice.
8343 /// Currently, it is considered profitable if there is exactly two
8344 /// involved slices (1) which are (2) next to each other in memory, and
8345 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8346 ///
8347 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8348 /// the elements themselves.
8349 ///
8350 /// FIXME: When the cost model will be mature enough, we can relax
8351 /// constraints (1) and (2).
8352 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8353                                 const APInt &UsedBits, bool ForCodeSize) {
8354   unsigned NumberOfSlices = LoadedSlices.size();
8355   if (StressLoadSlicing)
8356     return NumberOfSlices > 1;
8357
8358   // Check (1).
8359   if (NumberOfSlices != 2)
8360     return false;
8361
8362   // Check (2).
8363   if (!areUsedBitsDense(UsedBits))
8364     return false;
8365
8366   // Check (3).
8367   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8368   // The original code has one big load.
8369   OrigCost.Loads = 1;
8370   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8371     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8372     // Accumulate the cost of all the slices.
8373     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8374     GlobalSlicingCost += SliceCost;
8375
8376     // Account as cost in the original configuration the gain obtained
8377     // with the current slices.
8378     OrigCost.addSliceGain(LS);
8379   }
8380
8381   // If the target supports paired load, adjust the cost accordingly.
8382   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8383   return OrigCost > GlobalSlicingCost;
8384 }
8385
8386 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8387 /// operations, split it in the various pieces being extracted.
8388 ///
8389 /// This sort of thing is introduced by SROA.
8390 /// This slicing takes care not to insert overlapping loads.
8391 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8392 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8393   if (Level < AfterLegalizeDAG)
8394     return false;
8395
8396   LoadSDNode *LD = cast<LoadSDNode>(N);
8397   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8398       !LD->getValueType(0).isInteger())
8399     return false;
8400
8401   // Keep track of already used bits to detect overlapping values.
8402   // In that case, we will just abort the transformation.
8403   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8404
8405   SmallVector<LoadedSlice, 4> LoadedSlices;
8406
8407   // Check if this load is used as several smaller chunks of bits.
8408   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8409   // of computation for each trunc.
8410   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8411        UI != UIEnd; ++UI) {
8412     // Skip the uses of the chain.
8413     if (UI.getUse().getResNo() != 0)
8414       continue;
8415
8416     SDNode *User = *UI;
8417     unsigned Shift = 0;
8418
8419     // Check if this is a trunc(lshr).
8420     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8421         isa<ConstantSDNode>(User->getOperand(1))) {
8422       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8423       User = *User->use_begin();
8424     }
8425
8426     // At this point, User is a Truncate, iff we encountered, trunc or
8427     // trunc(lshr).
8428     if (User->getOpcode() != ISD::TRUNCATE)
8429       return false;
8430
8431     // The width of the type must be a power of 2 and greater than 8-bits.
8432     // Otherwise the load cannot be represented in LLVM IR.
8433     // Moreover, if we shifted with a non-8-bits multiple, the slice
8434     // will be across several bytes. We do not support that.
8435     unsigned Width = User->getValueSizeInBits(0);
8436     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8437       return 0;
8438
8439     // Build the slice for this chain of computations.
8440     LoadedSlice LS(User, LD, Shift, &DAG);
8441     APInt CurrentUsedBits = LS.getUsedBits();
8442
8443     // Check if this slice overlaps with another.
8444     if ((CurrentUsedBits & UsedBits) != 0)
8445       return false;
8446     // Update the bits used globally.
8447     UsedBits |= CurrentUsedBits;
8448
8449     // Check if the new slice would be legal.
8450     if (!LS.isLegal())
8451       return false;
8452
8453     // Record the slice.
8454     LoadedSlices.push_back(LS);
8455   }
8456
8457   // Abort slicing if it does not seem to be profitable.
8458   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8459     return false;
8460
8461   ++SlicedLoads;
8462
8463   // Rewrite each chain to use an independent load.
8464   // By construction, each chain can be represented by a unique load.
8465
8466   // Prepare the argument for the new token factor for all the slices.
8467   SmallVector<SDValue, 8> ArgChains;
8468   for (SmallVectorImpl<LoadedSlice>::const_iterator
8469            LSIt = LoadedSlices.begin(),
8470            LSItEnd = LoadedSlices.end();
8471        LSIt != LSItEnd; ++LSIt) {
8472     SDValue SliceInst = LSIt->loadSlice();
8473     CombineTo(LSIt->Inst, SliceInst, true);
8474     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8475       SliceInst = SliceInst.getOperand(0);
8476     assert(SliceInst->getOpcode() == ISD::LOAD &&
8477            "It takes more than a zext to get to the loaded slice!!");
8478     ArgChains.push_back(SliceInst.getValue(1));
8479   }
8480
8481   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8482                               &ArgChains[0], ArgChains.size());
8483   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8484   return true;
8485 }
8486
8487 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8488 /// load is having specific bytes cleared out.  If so, return the byte size
8489 /// being masked out and the shift amount.
8490 static std::pair<unsigned, unsigned>
8491 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8492   std::pair<unsigned, unsigned> Result(0, 0);
8493
8494   // Check for the structure we're looking for.
8495   if (V->getOpcode() != ISD::AND ||
8496       !isa<ConstantSDNode>(V->getOperand(1)) ||
8497       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8498     return Result;
8499
8500   // Check the chain and pointer.
8501   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8502   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8503
8504   // The store should be chained directly to the load or be an operand of a
8505   // tokenfactor.
8506   if (LD == Chain.getNode())
8507     ; // ok.
8508   else if (Chain->getOpcode() != ISD::TokenFactor)
8509     return Result; // Fail.
8510   else {
8511     bool isOk = false;
8512     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8513       if (Chain->getOperand(i).getNode() == LD) {
8514         isOk = true;
8515         break;
8516       }
8517     if (!isOk) return Result;
8518   }
8519
8520   // This only handles simple types.
8521   if (V.getValueType() != MVT::i16 &&
8522       V.getValueType() != MVT::i32 &&
8523       V.getValueType() != MVT::i64)
8524     return Result;
8525
8526   // Check the constant mask.  Invert it so that the bits being masked out are
8527   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8528   // follow the sign bit for uniformity.
8529   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8530   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8531   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8532   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8533   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8534   if (NotMaskLZ == 64) return Result;  // All zero mask.
8535
8536   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8537   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8538     return Result;
8539
8540   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8541   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8542     NotMaskLZ -= 64-V.getValueSizeInBits();
8543
8544   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8545   switch (MaskedBytes) {
8546   case 1:
8547   case 2:
8548   case 4: break;
8549   default: return Result; // All one mask, or 5-byte mask.
8550   }
8551
8552   // Verify that the first bit starts at a multiple of mask so that the access
8553   // is aligned the same as the access width.
8554   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8555
8556   Result.first = MaskedBytes;
8557   Result.second = NotMaskTZ/8;
8558   return Result;
8559 }
8560
8561
8562 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8563 /// provides a value as specified by MaskInfo.  If so, replace the specified
8564 /// store with a narrower store of truncated IVal.
8565 static SDNode *
8566 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8567                                 SDValue IVal, StoreSDNode *St,
8568                                 DAGCombiner *DC) {
8569   unsigned NumBytes = MaskInfo.first;
8570   unsigned ByteShift = MaskInfo.second;
8571   SelectionDAG &DAG = DC->getDAG();
8572
8573   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8574   // that uses this.  If not, this is not a replacement.
8575   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8576                                   ByteShift*8, (ByteShift+NumBytes)*8);
8577   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8578
8579   // Check that it is legal on the target to do this.  It is legal if the new
8580   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8581   // legalization.
8582   MVT VT = MVT::getIntegerVT(NumBytes*8);
8583   if (!DC->isTypeLegal(VT))
8584     return 0;
8585
8586   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8587   // shifted by ByteShift and truncated down to NumBytes.
8588   if (ByteShift)
8589     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8590                        DAG.getConstant(ByteShift*8,
8591                                     DC->getShiftAmountTy(IVal.getValueType())));
8592
8593   // Figure out the offset for the store and the alignment of the access.
8594   unsigned StOffset;
8595   unsigned NewAlign = St->getAlignment();
8596
8597   if (DAG.getTargetLoweringInfo().isLittleEndian())
8598     StOffset = ByteShift;
8599   else
8600     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8601
8602   SDValue Ptr = St->getBasePtr();
8603   if (StOffset) {
8604     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8605                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8606     NewAlign = MinAlign(NewAlign, StOffset);
8607   }
8608
8609   // Truncate down to the new size.
8610   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8611
8612   ++OpsNarrowed;
8613   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8614                       St->getPointerInfo().getWithOffset(StOffset),
8615                       false, false, NewAlign).getNode();
8616 }
8617
8618
8619 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8620 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8621 /// of the loaded bits, try narrowing the load and store if it would end up
8622 /// being a win for performance or code size.
8623 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8624   StoreSDNode *ST  = cast<StoreSDNode>(N);
8625   if (ST->isVolatile())
8626     return SDValue();
8627
8628   SDValue Chain = ST->getChain();
8629   SDValue Value = ST->getValue();
8630   SDValue Ptr   = ST->getBasePtr();
8631   EVT VT = Value.getValueType();
8632
8633   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8634     return SDValue();
8635
8636   unsigned Opc = Value.getOpcode();
8637
8638   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8639   // is a byte mask indicating a consecutive number of bytes, check to see if
8640   // Y is known to provide just those bytes.  If so, we try to replace the
8641   // load + replace + store sequence with a single (narrower) store, which makes
8642   // the load dead.
8643   if (Opc == ISD::OR) {
8644     std::pair<unsigned, unsigned> MaskedLoad;
8645     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8646     if (MaskedLoad.first)
8647       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8648                                                   Value.getOperand(1), ST,this))
8649         return SDValue(NewST, 0);
8650
8651     // Or is commutative, so try swapping X and Y.
8652     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8653     if (MaskedLoad.first)
8654       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8655                                                   Value.getOperand(0), ST,this))
8656         return SDValue(NewST, 0);
8657   }
8658
8659   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8660       Value.getOperand(1).getOpcode() != ISD::Constant)
8661     return SDValue();
8662
8663   SDValue N0 = Value.getOperand(0);
8664   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8665       Chain == SDValue(N0.getNode(), 1)) {
8666     LoadSDNode *LD = cast<LoadSDNode>(N0);
8667     if (LD->getBasePtr() != Ptr ||
8668         LD->getPointerInfo().getAddrSpace() !=
8669         ST->getPointerInfo().getAddrSpace())
8670       return SDValue();
8671
8672     // Find the type to narrow it the load / op / store to.
8673     SDValue N1 = Value.getOperand(1);
8674     unsigned BitWidth = N1.getValueSizeInBits();
8675     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8676     if (Opc == ISD::AND)
8677       Imm ^= APInt::getAllOnesValue(BitWidth);
8678     if (Imm == 0 || Imm.isAllOnesValue())
8679       return SDValue();
8680     unsigned ShAmt = Imm.countTrailingZeros();
8681     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8682     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8683     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8684     while (NewBW < BitWidth &&
8685            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8686              TLI.isNarrowingProfitable(VT, NewVT))) {
8687       NewBW = NextPowerOf2(NewBW);
8688       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8689     }
8690     if (NewBW >= BitWidth)
8691       return SDValue();
8692
8693     // If the lsb changed does not start at the type bitwidth boundary,
8694     // start at the previous one.
8695     if (ShAmt % NewBW)
8696       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8697     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8698                                    std::min(BitWidth, ShAmt + NewBW));
8699     if ((Imm & Mask) == Imm) {
8700       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8701       if (Opc == ISD::AND)
8702         NewImm ^= APInt::getAllOnesValue(NewBW);
8703       uint64_t PtrOff = ShAmt / 8;
8704       // For big endian targets, we need to adjust the offset to the pointer to
8705       // load the correct bytes.
8706       if (TLI.isBigEndian())
8707         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8708
8709       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8710       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8711       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8712         return SDValue();
8713
8714       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8715                                    Ptr.getValueType(), Ptr,
8716                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8717       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8718                                   LD->getChain(), NewPtr,
8719                                   LD->getPointerInfo().getWithOffset(PtrOff),
8720                                   LD->isVolatile(), LD->isNonTemporal(),
8721                                   LD->isInvariant(), NewAlign,
8722                                   LD->getTBAAInfo());
8723       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8724                                    DAG.getConstant(NewImm, NewVT));
8725       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8726                                    NewVal, NewPtr,
8727                                    ST->getPointerInfo().getWithOffset(PtrOff),
8728                                    false, false, NewAlign);
8729
8730       AddToWorkList(NewPtr.getNode());
8731       AddToWorkList(NewLD.getNode());
8732       AddToWorkList(NewVal.getNode());
8733       WorkListRemover DeadNodes(*this);
8734       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8735       ++OpsNarrowed;
8736       return NewST;
8737     }
8738   }
8739
8740   return SDValue();
8741 }
8742
8743 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8744 /// if the load value isn't used by any other operations, then consider
8745 /// transforming the pair to integer load / store operations if the target
8746 /// deems the transformation profitable.
8747 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8748   StoreSDNode *ST  = cast<StoreSDNode>(N);
8749   SDValue Chain = ST->getChain();
8750   SDValue Value = ST->getValue();
8751   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8752       Value.hasOneUse() &&
8753       Chain == SDValue(Value.getNode(), 1)) {
8754     LoadSDNode *LD = cast<LoadSDNode>(Value);
8755     EVT VT = LD->getMemoryVT();
8756     if (!VT.isFloatingPoint() ||
8757         VT != ST->getMemoryVT() ||
8758         LD->isNonTemporal() ||
8759         ST->isNonTemporal() ||
8760         LD->getPointerInfo().getAddrSpace() != 0 ||
8761         ST->getPointerInfo().getAddrSpace() != 0)
8762       return SDValue();
8763
8764     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8765     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8766         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8767         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8768         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8769       return SDValue();
8770
8771     unsigned LDAlign = LD->getAlignment();
8772     unsigned STAlign = ST->getAlignment();
8773     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8774     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8775     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8776       return SDValue();
8777
8778     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8779                                 LD->getChain(), LD->getBasePtr(),
8780                                 LD->getPointerInfo(),
8781                                 false, false, false, LDAlign);
8782
8783     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8784                                  NewLD, ST->getBasePtr(),
8785                                  ST->getPointerInfo(),
8786                                  false, false, STAlign);
8787
8788     AddToWorkList(NewLD.getNode());
8789     AddToWorkList(NewST.getNode());
8790     WorkListRemover DeadNodes(*this);
8791     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8792     ++LdStFP2Int;
8793     return NewST;
8794   }
8795
8796   return SDValue();
8797 }
8798
8799 /// Helper struct to parse and store a memory address as base + index + offset.
8800 /// We ignore sign extensions when it is safe to do so.
8801 /// The following two expressions are not equivalent. To differentiate we need
8802 /// to store whether there was a sign extension involved in the index
8803 /// computation.
8804 ///  (load (i64 add (i64 copyfromreg %c)
8805 ///                 (i64 signextend (add (i8 load %index)
8806 ///                                      (i8 1))))
8807 /// vs
8808 ///
8809 /// (load (i64 add (i64 copyfromreg %c)
8810 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8811 ///                                         (i32 1)))))
8812 struct BaseIndexOffset {
8813   SDValue Base;
8814   SDValue Index;
8815   int64_t Offset;
8816   bool IsIndexSignExt;
8817
8818   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8819
8820   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8821                   bool IsIndexSignExt) :
8822     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8823
8824   bool equalBaseIndex(const BaseIndexOffset &Other) {
8825     return Other.Base == Base && Other.Index == Index &&
8826       Other.IsIndexSignExt == IsIndexSignExt;
8827   }
8828
8829   /// Parses tree in Ptr for base, index, offset addresses.
8830   static BaseIndexOffset match(SDValue Ptr) {
8831     bool IsIndexSignExt = false;
8832
8833     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8834     // instruction, then it could be just the BASE or everything else we don't
8835     // know how to handle. Just use Ptr as BASE and give up.
8836     if (Ptr->getOpcode() != ISD::ADD)
8837       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8838
8839     // We know that we have at least an ADD instruction. Try to pattern match
8840     // the simple case of BASE + OFFSET.
8841     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8842       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8843       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8844                               IsIndexSignExt);
8845     }
8846
8847     // Inside a loop the current BASE pointer is calculated using an ADD and a
8848     // MUL instruction. In this case Ptr is the actual BASE pointer.
8849     // (i64 add (i64 %array_ptr)
8850     //          (i64 mul (i64 %induction_var)
8851     //                   (i64 %element_size)))
8852     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8853       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8854
8855     // Look at Base + Index + Offset cases.
8856     SDValue Base = Ptr->getOperand(0);
8857     SDValue IndexOffset = Ptr->getOperand(1);
8858
8859     // Skip signextends.
8860     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8861       IndexOffset = IndexOffset->getOperand(0);
8862       IsIndexSignExt = true;
8863     }
8864
8865     // Either the case of Base + Index (no offset) or something else.
8866     if (IndexOffset->getOpcode() != ISD::ADD)
8867       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8868
8869     // Now we have the case of Base + Index + offset.
8870     SDValue Index = IndexOffset->getOperand(0);
8871     SDValue Offset = IndexOffset->getOperand(1);
8872
8873     if (!isa<ConstantSDNode>(Offset))
8874       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8875
8876     // Ignore signextends.
8877     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8878       Index = Index->getOperand(0);
8879       IsIndexSignExt = true;
8880     } else IsIndexSignExt = false;
8881
8882     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8883     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8884   }
8885 };
8886
8887 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8888 /// is located in a sequence of memory operations connected by a chain.
8889 struct MemOpLink {
8890   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8891     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8892   // Ptr to the mem node.
8893   LSBaseSDNode *MemNode;
8894   // Offset from the base ptr.
8895   int64_t OffsetFromBase;
8896   // What is the sequence number of this mem node.
8897   // Lowest mem operand in the DAG starts at zero.
8898   unsigned SequenceNum;
8899 };
8900
8901 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8902   EVT MemVT = St->getMemoryVT();
8903   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8904   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8905     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8906
8907   // Don't merge vectors into wider inputs.
8908   if (MemVT.isVector() || !MemVT.isSimple())
8909     return false;
8910
8911   // Perform an early exit check. Do not bother looking at stored values that
8912   // are not constants or loads.
8913   SDValue StoredVal = St->getValue();
8914   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8915   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8916       !IsLoadSrc)
8917     return false;
8918
8919   // Only look at ends of store sequences.
8920   SDValue Chain = SDValue(St, 1);
8921   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8922     return false;
8923
8924   // This holds the base pointer, index, and the offset in bytes from the base
8925   // pointer.
8926   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8927
8928   // We must have a base and an offset.
8929   if (!BasePtr.Base.getNode())
8930     return false;
8931
8932   // Do not handle stores to undef base pointers.
8933   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8934     return false;
8935
8936   // Save the LoadSDNodes that we find in the chain.
8937   // We need to make sure that these nodes do not interfere with
8938   // any of the store nodes.
8939   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8940
8941   // Save the StoreSDNodes that we find in the chain.
8942   SmallVector<MemOpLink, 8> StoreNodes;
8943
8944   // Walk up the chain and look for nodes with offsets from the same
8945   // base pointer. Stop when reaching an instruction with a different kind
8946   // or instruction which has a different base pointer.
8947   unsigned Seq = 0;
8948   StoreSDNode *Index = St;
8949   while (Index) {
8950     // If the chain has more than one use, then we can't reorder the mem ops.
8951     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8952       break;
8953
8954     // Find the base pointer and offset for this memory node.
8955     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8956
8957     // Check that the base pointer is the same as the original one.
8958     if (!Ptr.equalBaseIndex(BasePtr))
8959       break;
8960
8961     // Check that the alignment is the same.
8962     if (Index->getAlignment() != St->getAlignment())
8963       break;
8964
8965     // The memory operands must not be volatile.
8966     if (Index->isVolatile() || Index->isIndexed())
8967       break;
8968
8969     // No truncation.
8970     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8971       if (St->isTruncatingStore())
8972         break;
8973
8974     // The stored memory type must be the same.
8975     if (Index->getMemoryVT() != MemVT)
8976       break;
8977
8978     // We do not allow unaligned stores because we want to prevent overriding
8979     // stores.
8980     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8981       break;
8982
8983     // We found a potential memory operand to merge.
8984     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8985
8986     // Find the next memory operand in the chain. If the next operand in the
8987     // chain is a store then move up and continue the scan with the next
8988     // memory operand. If the next operand is a load save it and use alias
8989     // information to check if it interferes with anything.
8990     SDNode *NextInChain = Index->getChain().getNode();
8991     while (1) {
8992       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8993         // We found a store node. Use it for the next iteration.
8994         Index = STn;
8995         break;
8996       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8997         if (Ldn->isVolatile()) {
8998           Index = NULL;
8999           break;
9000         }
9001
9002         // Save the load node for later. Continue the scan.
9003         AliasLoadNodes.push_back(Ldn);
9004         NextInChain = Ldn->getChain().getNode();
9005         continue;
9006       } else {
9007         Index = NULL;
9008         break;
9009       }
9010     }
9011   }
9012
9013   // Check if there is anything to merge.
9014   if (StoreNodes.size() < 2)
9015     return false;
9016
9017   // Sort the memory operands according to their distance from the base pointer.
9018   std::sort(StoreNodes.begin(), StoreNodes.end(),
9019             [](MemOpLink LHS, MemOpLink RHS) {
9020     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9021            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9022             LHS.SequenceNum > RHS.SequenceNum);
9023   });
9024
9025   // Scan the memory operations on the chain and find the first non-consecutive
9026   // store memory address.
9027   unsigned LastConsecutiveStore = 0;
9028   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9029   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9030
9031     // Check that the addresses are consecutive starting from the second
9032     // element in the list of stores.
9033     if (i > 0) {
9034       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9035       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9036         break;
9037     }
9038
9039     bool Alias = false;
9040     // Check if this store interferes with any of the loads that we found.
9041     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9042       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9043         Alias = true;
9044         break;
9045       }
9046     // We found a load that alias with this store. Stop the sequence.
9047     if (Alias)
9048       break;
9049
9050     // Mark this node as useful.
9051     LastConsecutiveStore = i;
9052   }
9053
9054   // The node with the lowest store address.
9055   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9056
9057   // Store the constants into memory as one consecutive store.
9058   if (!IsLoadSrc) {
9059     unsigned LastLegalType = 0;
9060     unsigned LastLegalVectorType = 0;
9061     bool NonZero = false;
9062     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9063       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9064       SDValue StoredVal = St->getValue();
9065
9066       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9067         NonZero |= !C->isNullValue();
9068       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9069         NonZero |= !C->getConstantFPValue()->isNullValue();
9070       } else {
9071         // Non-constant.
9072         break;
9073       }
9074
9075       // Find a legal type for the constant store.
9076       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9077       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9078       if (TLI.isTypeLegal(StoreTy))
9079         LastLegalType = i+1;
9080       // Or check whether a truncstore is legal.
9081       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9082                TargetLowering::TypePromoteInteger) {
9083         EVT LegalizedStoredValueTy =
9084           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9085         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9086           LastLegalType = i+1;
9087       }
9088
9089       // Find a legal type for the vector store.
9090       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9091       if (TLI.isTypeLegal(Ty))
9092         LastLegalVectorType = i + 1;
9093     }
9094
9095     // We only use vectors if the constant is known to be zero and the
9096     // function is not marked with the noimplicitfloat attribute.
9097     if (NonZero || NoVectors)
9098       LastLegalVectorType = 0;
9099
9100     // Check if we found a legal integer type to store.
9101     if (LastLegalType == 0 && LastLegalVectorType == 0)
9102       return false;
9103
9104     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9105     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9106
9107     // Make sure we have something to merge.
9108     if (NumElem < 2)
9109       return false;
9110
9111     unsigned EarliestNodeUsed = 0;
9112     for (unsigned i=0; i < NumElem; ++i) {
9113       // Find a chain for the new wide-store operand. Notice that some
9114       // of the store nodes that we found may not be selected for inclusion
9115       // in the wide store. The chain we use needs to be the chain of the
9116       // earliest store node which is *used* and replaced by the wide store.
9117       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9118         EarliestNodeUsed = i;
9119     }
9120
9121     // The earliest Node in the DAG.
9122     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9123     SDLoc DL(StoreNodes[0].MemNode);
9124
9125     SDValue StoredVal;
9126     if (UseVector) {
9127       // Find a legal type for the vector store.
9128       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9129       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9130       StoredVal = DAG.getConstant(0, Ty);
9131     } else {
9132       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9133       APInt StoreInt(StoreBW, 0);
9134
9135       // Construct a single integer constant which is made of the smaller
9136       // constant inputs.
9137       bool IsLE = TLI.isLittleEndian();
9138       for (unsigned i = 0; i < NumElem ; ++i) {
9139         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9140         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9141         SDValue Val = St->getValue();
9142         StoreInt<<=ElementSizeBytes*8;
9143         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9144           StoreInt|=C->getAPIntValue().zext(StoreBW);
9145         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9146           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9147         } else {
9148           assert(false && "Invalid constant element type");
9149         }
9150       }
9151
9152       // Create the new Load and Store operations.
9153       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9154       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9155     }
9156
9157     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9158                                     FirstInChain->getBasePtr(),
9159                                     FirstInChain->getPointerInfo(),
9160                                     false, false,
9161                                     FirstInChain->getAlignment());
9162
9163     // Replace the first store with the new store
9164     CombineTo(EarliestOp, NewStore);
9165     // Erase all other stores.
9166     for (unsigned i = 0; i < NumElem ; ++i) {
9167       if (StoreNodes[i].MemNode == EarliestOp)
9168         continue;
9169       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9170       // ReplaceAllUsesWith will replace all uses that existed when it was
9171       // called, but graph optimizations may cause new ones to appear. For
9172       // example, the case in pr14333 looks like
9173       //
9174       //  St's chain -> St -> another store -> X
9175       //
9176       // And the only difference from St to the other store is the chain.
9177       // When we change it's chain to be St's chain they become identical,
9178       // get CSEed and the net result is that X is now a use of St.
9179       // Since we know that St is redundant, just iterate.
9180       while (!St->use_empty())
9181         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9182       removeFromWorkList(St);
9183       DAG.DeleteNode(St);
9184     }
9185
9186     return true;
9187   }
9188
9189   // Below we handle the case of multiple consecutive stores that
9190   // come from multiple consecutive loads. We merge them into a single
9191   // wide load and a single wide store.
9192
9193   // Look for load nodes which are used by the stored values.
9194   SmallVector<MemOpLink, 8> LoadNodes;
9195
9196   // Find acceptable loads. Loads need to have the same chain (token factor),
9197   // must not be zext, volatile, indexed, and they must be consecutive.
9198   BaseIndexOffset LdBasePtr;
9199   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9200     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9201     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9202     if (!Ld) break;
9203
9204     // Loads must only have one use.
9205     if (!Ld->hasNUsesOfValue(1, 0))
9206       break;
9207
9208     // Check that the alignment is the same as the stores.
9209     if (Ld->getAlignment() != St->getAlignment())
9210       break;
9211
9212     // The memory operands must not be volatile.
9213     if (Ld->isVolatile() || Ld->isIndexed())
9214       break;
9215
9216     // We do not accept ext loads.
9217     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9218       break;
9219
9220     // The stored memory type must be the same.
9221     if (Ld->getMemoryVT() != MemVT)
9222       break;
9223
9224     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9225     // If this is not the first ptr that we check.
9226     if (LdBasePtr.Base.getNode()) {
9227       // The base ptr must be the same.
9228       if (!LdPtr.equalBaseIndex(LdBasePtr))
9229         break;
9230     } else {
9231       // Check that all other base pointers are the same as this one.
9232       LdBasePtr = LdPtr;
9233     }
9234
9235     // We found a potential memory operand to merge.
9236     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9237   }
9238
9239   if (LoadNodes.size() < 2)
9240     return false;
9241
9242   // Scan the memory operations on the chain and find the first non-consecutive
9243   // load memory address. These variables hold the index in the store node
9244   // array.
9245   unsigned LastConsecutiveLoad = 0;
9246   // This variable refers to the size and not index in the array.
9247   unsigned LastLegalVectorType = 0;
9248   unsigned LastLegalIntegerType = 0;
9249   StartAddress = LoadNodes[0].OffsetFromBase;
9250   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9251   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9252     // All loads much share the same chain.
9253     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9254       break;
9255
9256     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9257     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9258       break;
9259     LastConsecutiveLoad = i;
9260
9261     // Find a legal type for the vector store.
9262     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9263     if (TLI.isTypeLegal(StoreTy))
9264       LastLegalVectorType = i + 1;
9265
9266     // Find a legal type for the integer store.
9267     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9268     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9269     if (TLI.isTypeLegal(StoreTy))
9270       LastLegalIntegerType = i + 1;
9271     // Or check whether a truncstore and extload is legal.
9272     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9273              TargetLowering::TypePromoteInteger) {
9274       EVT LegalizedStoredValueTy =
9275         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9276       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9277           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9278           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9279           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9280         LastLegalIntegerType = i+1;
9281     }
9282   }
9283
9284   // Only use vector types if the vector type is larger than the integer type.
9285   // If they are the same, use integers.
9286   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9287   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9288
9289   // We add +1 here because the LastXXX variables refer to location while
9290   // the NumElem refers to array/index size.
9291   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9292   NumElem = std::min(LastLegalType, NumElem);
9293
9294   if (NumElem < 2)
9295     return false;
9296
9297   // The earliest Node in the DAG.
9298   unsigned EarliestNodeUsed = 0;
9299   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9300   for (unsigned i=1; i<NumElem; ++i) {
9301     // Find a chain for the new wide-store operand. Notice that some
9302     // of the store nodes that we found may not be selected for inclusion
9303     // in the wide store. The chain we use needs to be the chain of the
9304     // earliest store node which is *used* and replaced by the wide store.
9305     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9306       EarliestNodeUsed = i;
9307   }
9308
9309   // Find if it is better to use vectors or integers to load and store
9310   // to memory.
9311   EVT JointMemOpVT;
9312   if (UseVectorTy) {
9313     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9314   } else {
9315     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9316     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9317   }
9318
9319   SDLoc LoadDL(LoadNodes[0].MemNode);
9320   SDLoc StoreDL(StoreNodes[0].MemNode);
9321
9322   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9323   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9324                                 FirstLoad->getChain(),
9325                                 FirstLoad->getBasePtr(),
9326                                 FirstLoad->getPointerInfo(),
9327                                 false, false, false,
9328                                 FirstLoad->getAlignment());
9329
9330   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9331                                   FirstInChain->getBasePtr(),
9332                                   FirstInChain->getPointerInfo(), false, false,
9333                                   FirstInChain->getAlignment());
9334
9335   // Replace one of the loads with the new load.
9336   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9337   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9338                                 SDValue(NewLoad.getNode(), 1));
9339
9340   // Remove the rest of the load chains.
9341   for (unsigned i = 1; i < NumElem ; ++i) {
9342     // Replace all chain users of the old load nodes with the chain of the new
9343     // load node.
9344     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9345     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9346   }
9347
9348   // Replace the first store with the new store.
9349   CombineTo(EarliestOp, NewStore);
9350   // Erase all other stores.
9351   for (unsigned i = 0; i < NumElem ; ++i) {
9352     // Remove all Store nodes.
9353     if (StoreNodes[i].MemNode == EarliestOp)
9354       continue;
9355     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9356     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9357     removeFromWorkList(St);
9358     DAG.DeleteNode(St);
9359   }
9360
9361   return true;
9362 }
9363
9364 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9365   StoreSDNode *ST  = cast<StoreSDNode>(N);
9366   SDValue Chain = ST->getChain();
9367   SDValue Value = ST->getValue();
9368   SDValue Ptr   = ST->getBasePtr();
9369
9370   // If this is a store of a bit convert, store the input value if the
9371   // resultant store does not need a higher alignment than the original.
9372   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9373       ST->isUnindexed()) {
9374     unsigned OrigAlign = ST->getAlignment();
9375     EVT SVT = Value.getOperand(0).getValueType();
9376     unsigned Align = TLI.getDataLayout()->
9377       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9378     if (Align <= OrigAlign &&
9379         ((!LegalOperations && !ST->isVolatile()) ||
9380          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9381       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9382                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9383                           ST->isNonTemporal(), OrigAlign,
9384                           ST->getTBAAInfo());
9385   }
9386
9387   // Turn 'store undef, Ptr' -> nothing.
9388   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9389     return Chain;
9390
9391   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9392   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9393     // NOTE: If the original store is volatile, this transform must not increase
9394     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9395     // processor operation but an i64 (which is not legal) requires two.  So the
9396     // transform should not be done in this case.
9397     if (Value.getOpcode() != ISD::TargetConstantFP) {
9398       SDValue Tmp;
9399       switch (CFP->getSimpleValueType(0).SimpleTy) {
9400       default: llvm_unreachable("Unknown FP type");
9401       case MVT::f16:    // We don't do this for these yet.
9402       case MVT::f80:
9403       case MVT::f128:
9404       case MVT::ppcf128:
9405         break;
9406       case MVT::f32:
9407         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9408             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9409           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9410                               bitcastToAPInt().getZExtValue(), MVT::i32);
9411           return DAG.getStore(Chain, SDLoc(N), Tmp,
9412                               Ptr, ST->getMemOperand());
9413         }
9414         break;
9415       case MVT::f64:
9416         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9417              !ST->isVolatile()) ||
9418             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9419           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9420                                 getZExtValue(), MVT::i64);
9421           return DAG.getStore(Chain, SDLoc(N), Tmp,
9422                               Ptr, ST->getMemOperand());
9423         }
9424
9425         if (!ST->isVolatile() &&
9426             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9427           // Many FP stores are not made apparent until after legalize, e.g. for
9428           // argument passing.  Since this is so common, custom legalize the
9429           // 64-bit integer store into two 32-bit stores.
9430           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9431           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9432           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9433           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9434
9435           unsigned Alignment = ST->getAlignment();
9436           bool isVolatile = ST->isVolatile();
9437           bool isNonTemporal = ST->isNonTemporal();
9438           const MDNode *TBAAInfo = ST->getTBAAInfo();
9439
9440           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9441                                      Ptr, ST->getPointerInfo(),
9442                                      isVolatile, isNonTemporal,
9443                                      ST->getAlignment(), TBAAInfo);
9444           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9445                             DAG.getConstant(4, Ptr.getValueType()));
9446           Alignment = MinAlign(Alignment, 4U);
9447           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9448                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9449                                      isVolatile, isNonTemporal,
9450                                      Alignment, TBAAInfo);
9451           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9452                              St0, St1);
9453         }
9454
9455         break;
9456       }
9457     }
9458   }
9459
9460   // Try to infer better alignment information than the store already has.
9461   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9462     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9463       if (Align > ST->getAlignment())
9464         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9465                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9466                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9467                                  ST->getTBAAInfo());
9468     }
9469   }
9470
9471   // Try transforming a pair floating point load / store ops to integer
9472   // load / store ops.
9473   SDValue NewST = TransformFPLoadStorePair(N);
9474   if (NewST.getNode())
9475     return NewST;
9476
9477   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9478     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9479 #ifndef NDEBUG
9480   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9481       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9482     UseAA = false;
9483 #endif
9484   if (UseAA && ST->isUnindexed()) {
9485     // Walk up chain skipping non-aliasing memory nodes.
9486     SDValue BetterChain = FindBetterChain(N, Chain);
9487
9488     // If there is a better chain.
9489     if (Chain != BetterChain) {
9490       SDValue ReplStore;
9491
9492       // Replace the chain to avoid dependency.
9493       if (ST->isTruncatingStore()) {
9494         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9495                                       ST->getMemoryVT(), ST->getMemOperand());
9496       } else {
9497         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9498                                  ST->getMemOperand());
9499       }
9500
9501       // Create token to keep both nodes around.
9502       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9503                                   MVT::Other, Chain, ReplStore);
9504
9505       // Make sure the new and old chains are cleaned up.
9506       AddToWorkList(Token.getNode());
9507
9508       // Don't add users to work list.
9509       return CombineTo(N, Token, false);
9510     }
9511   }
9512
9513   // Try transforming N to an indexed store.
9514   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9515     return SDValue(N, 0);
9516
9517   // FIXME: is there such a thing as a truncating indexed store?
9518   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9519       Value.getValueType().isInteger()) {
9520     // See if we can simplify the input to this truncstore with knowledge that
9521     // only the low bits are being used.  For example:
9522     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9523     SDValue Shorter =
9524       GetDemandedBits(Value,
9525                       APInt::getLowBitsSet(
9526                         Value.getValueType().getScalarType().getSizeInBits(),
9527                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9528     AddToWorkList(Value.getNode());
9529     if (Shorter.getNode())
9530       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9531                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9532
9533     // Otherwise, see if we can simplify the operation with
9534     // SimplifyDemandedBits, which only works if the value has a single use.
9535     if (SimplifyDemandedBits(Value,
9536                         APInt::getLowBitsSet(
9537                           Value.getValueType().getScalarType().getSizeInBits(),
9538                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9539       return SDValue(N, 0);
9540   }
9541
9542   // If this is a load followed by a store to the same location, then the store
9543   // is dead/noop.
9544   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9545     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9546         ST->isUnindexed() && !ST->isVolatile() &&
9547         // There can't be any side effects between the load and store, such as
9548         // a call or store.
9549         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9550       // The store is dead, remove it.
9551       return Chain;
9552     }
9553   }
9554
9555   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9556   // truncating store.  We can do this even if this is already a truncstore.
9557   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9558       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9559       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9560                             ST->getMemoryVT())) {
9561     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9562                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9563   }
9564
9565   // Only perform this optimization before the types are legal, because we
9566   // don't want to perform this optimization on every DAGCombine invocation.
9567   if (!LegalTypes) {
9568     bool EverChanged = false;
9569
9570     do {
9571       // There can be multiple store sequences on the same chain.
9572       // Keep trying to merge store sequences until we are unable to do so
9573       // or until we merge the last store on the chain.
9574       bool Changed = MergeConsecutiveStores(ST);
9575       EverChanged |= Changed;
9576       if (!Changed) break;
9577     } while (ST->getOpcode() != ISD::DELETED_NODE);
9578
9579     if (EverChanged)
9580       return SDValue(N, 0);
9581   }
9582
9583   return ReduceLoadOpStoreWidth(N);
9584 }
9585
9586 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9587   SDValue InVec = N->getOperand(0);
9588   SDValue InVal = N->getOperand(1);
9589   SDValue EltNo = N->getOperand(2);
9590   SDLoc dl(N);
9591
9592   // If the inserted element is an UNDEF, just use the input vector.
9593   if (InVal.getOpcode() == ISD::UNDEF)
9594     return InVec;
9595
9596   EVT VT = InVec.getValueType();
9597
9598   // If we can't generate a legal BUILD_VECTOR, exit
9599   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9600     return SDValue();
9601
9602   // Check that we know which element is being inserted
9603   if (!isa<ConstantSDNode>(EltNo))
9604     return SDValue();
9605   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9606
9607   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9608   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9609   // vector elements.
9610   SmallVector<SDValue, 8> Ops;
9611   // Do not combine these two vectors if the output vector will not replace
9612   // the input vector.
9613   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9614     Ops.append(InVec.getNode()->op_begin(),
9615                InVec.getNode()->op_end());
9616   } else if (InVec.getOpcode() == ISD::UNDEF) {
9617     unsigned NElts = VT.getVectorNumElements();
9618     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9619   } else {
9620     return SDValue();
9621   }
9622
9623   // Insert the element
9624   if (Elt < Ops.size()) {
9625     // All the operands of BUILD_VECTOR must have the same type;
9626     // we enforce that here.
9627     EVT OpVT = Ops[0].getValueType();
9628     if (InVal.getValueType() != OpVT)
9629       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9630                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9631                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9632     Ops[Elt] = InVal;
9633   }
9634
9635   // Return the new vector
9636   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9637                      VT, &Ops[0], Ops.size());
9638 }
9639
9640 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9641   // (vextract (scalar_to_vector val, 0) -> val
9642   SDValue InVec = N->getOperand(0);
9643   EVT VT = InVec.getValueType();
9644   EVT NVT = N->getValueType(0);
9645
9646   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9647     // Check if the result type doesn't match the inserted element type. A
9648     // SCALAR_TO_VECTOR may truncate the inserted element and the
9649     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9650     SDValue InOp = InVec.getOperand(0);
9651     if (InOp.getValueType() != NVT) {
9652       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9653       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9654     }
9655     return InOp;
9656   }
9657
9658   SDValue EltNo = N->getOperand(1);
9659   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9660
9661   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9662   // We only perform this optimization before the op legalization phase because
9663   // we may introduce new vector instructions which are not backed by TD
9664   // patterns. For example on AVX, extracting elements from a wide vector
9665   // without using extract_subvector.
9666   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9667       && ConstEltNo && !LegalOperations) {
9668     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9669     int NumElem = VT.getVectorNumElements();
9670     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9671     // Find the new index to extract from.
9672     int OrigElt = SVOp->getMaskElt(Elt);
9673
9674     // Extracting an undef index is undef.
9675     if (OrigElt == -1)
9676       return DAG.getUNDEF(NVT);
9677
9678     // Select the right vector half to extract from.
9679     if (OrigElt < NumElem) {
9680       InVec = InVec->getOperand(0);
9681     } else {
9682       InVec = InVec->getOperand(1);
9683       OrigElt -= NumElem;
9684     }
9685
9686     EVT IndexTy = TLI.getVectorIdxTy();
9687     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9688                        InVec, DAG.getConstant(OrigElt, IndexTy));
9689   }
9690
9691   // Perform only after legalization to ensure build_vector / vector_shuffle
9692   // optimizations have already been done.
9693   if (!LegalOperations) return SDValue();
9694
9695   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9696   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9697   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9698
9699   if (ConstEltNo) {
9700     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9701     bool NewLoad = false;
9702     bool BCNumEltsChanged = false;
9703     EVT ExtVT = VT.getVectorElementType();
9704     EVT LVT = ExtVT;
9705
9706     // If the result of load has to be truncated, then it's not necessarily
9707     // profitable.
9708     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9709       return SDValue();
9710
9711     if (InVec.getOpcode() == ISD::BITCAST) {
9712       // Don't duplicate a load with other uses.
9713       if (!InVec.hasOneUse())
9714         return SDValue();
9715
9716       EVT BCVT = InVec.getOperand(0).getValueType();
9717       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9718         return SDValue();
9719       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9720         BCNumEltsChanged = true;
9721       InVec = InVec.getOperand(0);
9722       ExtVT = BCVT.getVectorElementType();
9723       NewLoad = true;
9724     }
9725
9726     LoadSDNode *LN0 = NULL;
9727     const ShuffleVectorSDNode *SVN = NULL;
9728     if (ISD::isNormalLoad(InVec.getNode())) {
9729       LN0 = cast<LoadSDNode>(InVec);
9730     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9731                InVec.getOperand(0).getValueType() == ExtVT &&
9732                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9733       // Don't duplicate a load with other uses.
9734       if (!InVec.hasOneUse())
9735         return SDValue();
9736
9737       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9738     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9739       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9740       // =>
9741       // (load $addr+1*size)
9742
9743       // Don't duplicate a load with other uses.
9744       if (!InVec.hasOneUse())
9745         return SDValue();
9746
9747       // If the bit convert changed the number of elements, it is unsafe
9748       // to examine the mask.
9749       if (BCNumEltsChanged)
9750         return SDValue();
9751
9752       // Select the input vector, guarding against out of range extract vector.
9753       unsigned NumElems = VT.getVectorNumElements();
9754       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9755       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9756
9757       if (InVec.getOpcode() == ISD::BITCAST) {
9758         // Don't duplicate a load with other uses.
9759         if (!InVec.hasOneUse())
9760           return SDValue();
9761
9762         InVec = InVec.getOperand(0);
9763       }
9764       if (ISD::isNormalLoad(InVec.getNode())) {
9765         LN0 = cast<LoadSDNode>(InVec);
9766         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9767       }
9768     }
9769
9770     // Make sure we found a non-volatile load and the extractelement is
9771     // the only use.
9772     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9773       return SDValue();
9774
9775     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9776     if (Elt == -1)
9777       return DAG.getUNDEF(LVT);
9778
9779     unsigned Align = LN0->getAlignment();
9780     if (NewLoad) {
9781       // Check the resultant load doesn't need a higher alignment than the
9782       // original load.
9783       unsigned NewAlign =
9784         TLI.getDataLayout()
9785             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9786
9787       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9788         return SDValue();
9789
9790       Align = NewAlign;
9791     }
9792
9793     SDValue NewPtr = LN0->getBasePtr();
9794     unsigned PtrOff = 0;
9795
9796     if (Elt) {
9797       PtrOff = LVT.getSizeInBits() * Elt / 8;
9798       EVT PtrType = NewPtr.getValueType();
9799       if (TLI.isBigEndian())
9800         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9801       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9802                            DAG.getConstant(PtrOff, PtrType));
9803     }
9804
9805     // The replacement we need to do here is a little tricky: we need to
9806     // replace an extractelement of a load with a load.
9807     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9808     // Note that this replacement assumes that the extractvalue is the only
9809     // use of the load; that's okay because we don't want to perform this
9810     // transformation in other cases anyway.
9811     SDValue Load;
9812     SDValue Chain;
9813     if (NVT.bitsGT(LVT)) {
9814       // If the result type of vextract is wider than the load, then issue an
9815       // extending load instead.
9816       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9817         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9818       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9819                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9820                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9821                             Align, LN0->getTBAAInfo());
9822       Chain = Load.getValue(1);
9823     } else {
9824       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9825                          LN0->getPointerInfo().getWithOffset(PtrOff),
9826                          LN0->isVolatile(), LN0->isNonTemporal(),
9827                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9828       Chain = Load.getValue(1);
9829       if (NVT.bitsLT(LVT))
9830         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9831       else
9832         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9833     }
9834     WorkListRemover DeadNodes(*this);
9835     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9836     SDValue To[] = { Load, Chain };
9837     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9838     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9839     // worklist explicitly as well.
9840     AddToWorkList(Load.getNode());
9841     AddUsersToWorkList(Load.getNode()); // Add users too
9842     // Make sure to revisit this node to clean it up; it will usually be dead.
9843     AddToWorkList(N);
9844     return SDValue(N, 0);
9845   }
9846
9847   return SDValue();
9848 }
9849
9850 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9851 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9852   // We perform this optimization post type-legalization because
9853   // the type-legalizer often scalarizes integer-promoted vectors.
9854   // Performing this optimization before may create bit-casts which
9855   // will be type-legalized to complex code sequences.
9856   // We perform this optimization only before the operation legalizer because we
9857   // may introduce illegal operations.
9858   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9859     return SDValue();
9860
9861   unsigned NumInScalars = N->getNumOperands();
9862   SDLoc dl(N);
9863   EVT VT = N->getValueType(0);
9864
9865   // Check to see if this is a BUILD_VECTOR of a bunch of values
9866   // which come from any_extend or zero_extend nodes. If so, we can create
9867   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9868   // optimizations. We do not handle sign-extend because we can't fill the sign
9869   // using shuffles.
9870   EVT SourceType = MVT::Other;
9871   bool AllAnyExt = true;
9872
9873   for (unsigned i = 0; i != NumInScalars; ++i) {
9874     SDValue In = N->getOperand(i);
9875     // Ignore undef inputs.
9876     if (In.getOpcode() == ISD::UNDEF) continue;
9877
9878     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9879     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9880
9881     // Abort if the element is not an extension.
9882     if (!ZeroExt && !AnyExt) {
9883       SourceType = MVT::Other;
9884       break;
9885     }
9886
9887     // The input is a ZeroExt or AnyExt. Check the original type.
9888     EVT InTy = In.getOperand(0).getValueType();
9889
9890     // Check that all of the widened source types are the same.
9891     if (SourceType == MVT::Other)
9892       // First time.
9893       SourceType = InTy;
9894     else if (InTy != SourceType) {
9895       // Multiple income types. Abort.
9896       SourceType = MVT::Other;
9897       break;
9898     }
9899
9900     // Check if all of the extends are ANY_EXTENDs.
9901     AllAnyExt &= AnyExt;
9902   }
9903
9904   // In order to have valid types, all of the inputs must be extended from the
9905   // same source type and all of the inputs must be any or zero extend.
9906   // Scalar sizes must be a power of two.
9907   EVT OutScalarTy = VT.getScalarType();
9908   bool ValidTypes = SourceType != MVT::Other &&
9909                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9910                  isPowerOf2_32(SourceType.getSizeInBits());
9911
9912   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9913   // turn into a single shuffle instruction.
9914   if (!ValidTypes)
9915     return SDValue();
9916
9917   bool isLE = TLI.isLittleEndian();
9918   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9919   assert(ElemRatio > 1 && "Invalid element size ratio");
9920   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9921                                DAG.getConstant(0, SourceType);
9922
9923   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9924   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9925
9926   // Populate the new build_vector
9927   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9928     SDValue Cast = N->getOperand(i);
9929     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9930             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9931             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9932     SDValue In;
9933     if (Cast.getOpcode() == ISD::UNDEF)
9934       In = DAG.getUNDEF(SourceType);
9935     else
9936       In = Cast->getOperand(0);
9937     unsigned Index = isLE ? (i * ElemRatio) :
9938                             (i * ElemRatio + (ElemRatio - 1));
9939
9940     assert(Index < Ops.size() && "Invalid index");
9941     Ops[Index] = In;
9942   }
9943
9944   // The type of the new BUILD_VECTOR node.
9945   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9946   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9947          "Invalid vector size");
9948   // Check if the new vector type is legal.
9949   if (!isTypeLegal(VecVT)) return SDValue();
9950
9951   // Make the new BUILD_VECTOR.
9952   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9953
9954   // The new BUILD_VECTOR node has the potential to be further optimized.
9955   AddToWorkList(BV.getNode());
9956   // Bitcast to the desired type.
9957   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9958 }
9959
9960 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9961   EVT VT = N->getValueType(0);
9962
9963   unsigned NumInScalars = N->getNumOperands();
9964   SDLoc dl(N);
9965
9966   EVT SrcVT = MVT::Other;
9967   unsigned Opcode = ISD::DELETED_NODE;
9968   unsigned NumDefs = 0;
9969
9970   for (unsigned i = 0; i != NumInScalars; ++i) {
9971     SDValue In = N->getOperand(i);
9972     unsigned Opc = In.getOpcode();
9973
9974     if (Opc == ISD::UNDEF)
9975       continue;
9976
9977     // If all scalar values are floats and converted from integers.
9978     if (Opcode == ISD::DELETED_NODE &&
9979         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9980       Opcode = Opc;
9981     }
9982
9983     if (Opc != Opcode)
9984       return SDValue();
9985
9986     EVT InVT = In.getOperand(0).getValueType();
9987
9988     // If all scalar values are typed differently, bail out. It's chosen to
9989     // simplify BUILD_VECTOR of integer types.
9990     if (SrcVT == MVT::Other)
9991       SrcVT = InVT;
9992     if (SrcVT != InVT)
9993       return SDValue();
9994     NumDefs++;
9995   }
9996
9997   // If the vector has just one element defined, it's not worth to fold it into
9998   // a vectorized one.
9999   if (NumDefs < 2)
10000     return SDValue();
10001
10002   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10003          && "Should only handle conversion from integer to float.");
10004   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10005
10006   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10007
10008   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10009     return SDValue();
10010
10011   SmallVector<SDValue, 8> Opnds;
10012   for (unsigned i = 0; i != NumInScalars; ++i) {
10013     SDValue In = N->getOperand(i);
10014
10015     if (In.getOpcode() == ISD::UNDEF)
10016       Opnds.push_back(DAG.getUNDEF(SrcVT));
10017     else
10018       Opnds.push_back(In.getOperand(0));
10019   }
10020   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10021                            &Opnds[0], Opnds.size());
10022   AddToWorkList(BV.getNode());
10023
10024   return DAG.getNode(Opcode, dl, VT, BV);
10025 }
10026
10027 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10028   unsigned NumInScalars = N->getNumOperands();
10029   SDLoc dl(N);
10030   EVT VT = N->getValueType(0);
10031
10032   // A vector built entirely of undefs is undef.
10033   if (ISD::allOperandsUndef(N))
10034     return DAG.getUNDEF(VT);
10035
10036   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10037   if (V.getNode())
10038     return V;
10039
10040   V = reduceBuildVecConvertToConvertBuildVec(N);
10041   if (V.getNode())
10042     return V;
10043
10044   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10045   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10046   // at most two distinct vectors, turn this into a shuffle node.
10047
10048   // May only combine to shuffle after legalize if shuffle is legal.
10049   if (LegalOperations &&
10050       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10051     return SDValue();
10052
10053   SDValue VecIn1, VecIn2;
10054   for (unsigned i = 0; i != NumInScalars; ++i) {
10055     // Ignore undef inputs.
10056     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10057
10058     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10059     // constant index, bail out.
10060     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10061         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10062       VecIn1 = VecIn2 = SDValue(0, 0);
10063       break;
10064     }
10065
10066     // We allow up to two distinct input vectors.
10067     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10068     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10069       continue;
10070
10071     if (VecIn1.getNode() == 0) {
10072       VecIn1 = ExtractedFromVec;
10073     } else if (VecIn2.getNode() == 0) {
10074       VecIn2 = ExtractedFromVec;
10075     } else {
10076       // Too many inputs.
10077       VecIn1 = VecIn2 = SDValue(0, 0);
10078       break;
10079     }
10080   }
10081
10082     // If everything is good, we can make a shuffle operation.
10083   if (VecIn1.getNode()) {
10084     SmallVector<int, 8> Mask;
10085     for (unsigned i = 0; i != NumInScalars; ++i) {
10086       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10087         Mask.push_back(-1);
10088         continue;
10089       }
10090
10091       // If extracting from the first vector, just use the index directly.
10092       SDValue Extract = N->getOperand(i);
10093       SDValue ExtVal = Extract.getOperand(1);
10094       if (Extract.getOperand(0) == VecIn1) {
10095         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10096         if (ExtIndex > VT.getVectorNumElements())
10097           return SDValue();
10098
10099         Mask.push_back(ExtIndex);
10100         continue;
10101       }
10102
10103       // Otherwise, use InIdx + VecSize
10104       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10105       Mask.push_back(Idx+NumInScalars);
10106     }
10107
10108     // We can't generate a shuffle node with mismatched input and output types.
10109     // Attempt to transform a single input vector to the correct type.
10110     if ((VT != VecIn1.getValueType())) {
10111       // We don't support shuffeling between TWO values of different types.
10112       if (VecIn2.getNode() != 0)
10113         return SDValue();
10114
10115       // We only support widening of vectors which are half the size of the
10116       // output registers. For example XMM->YMM widening on X86 with AVX.
10117       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10118         return SDValue();
10119
10120       // If the input vector type has a different base type to the output
10121       // vector type, bail out.
10122       if (VecIn1.getValueType().getVectorElementType() !=
10123           VT.getVectorElementType())
10124         return SDValue();
10125
10126       // Widen the input vector by adding undef values.
10127       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10128                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10129     }
10130
10131     // If VecIn2 is unused then change it to undef.
10132     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10133
10134     // Check that we were able to transform all incoming values to the same
10135     // type.
10136     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10137         VecIn1.getValueType() != VT)
10138           return SDValue();
10139
10140     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10141     if (!isTypeLegal(VT))
10142       return SDValue();
10143
10144     // Return the new VECTOR_SHUFFLE node.
10145     SDValue Ops[2];
10146     Ops[0] = VecIn1;
10147     Ops[1] = VecIn2;
10148     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10149   }
10150
10151   return SDValue();
10152 }
10153
10154 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10155   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10156   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10157   // inputs come from at most two distinct vectors, turn this into a shuffle
10158   // node.
10159
10160   // If we only have one input vector, we don't need to do any concatenation.
10161   if (N->getNumOperands() == 1)
10162     return N->getOperand(0);
10163
10164   // Check if all of the operands are undefs.
10165   EVT VT = N->getValueType(0);
10166   if (ISD::allOperandsUndef(N))
10167     return DAG.getUNDEF(VT);
10168
10169   // Optimize concat_vectors where one of the vectors is undef.
10170   if (N->getNumOperands() == 2 &&
10171       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10172     SDValue In = N->getOperand(0);
10173     assert(In.getValueType().isVector() && "Must concat vectors");
10174
10175     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10176     if (In->getOpcode() == ISD::BITCAST &&
10177         !In->getOperand(0)->getValueType(0).isVector()) {
10178       SDValue Scalar = In->getOperand(0);
10179       EVT SclTy = Scalar->getValueType(0);
10180
10181       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10182         return SDValue();
10183
10184       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10185                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10186       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10187         return SDValue();
10188
10189       SDLoc dl = SDLoc(N);
10190       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10191       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10192     }
10193   }
10194
10195   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10196   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10197   if (N->getNumOperands() == 2 &&
10198       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10199       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10200     EVT VT = N->getValueType(0);
10201     SDValue N0 = N->getOperand(0);
10202     SDValue N1 = N->getOperand(1);
10203     SmallVector<SDValue, 8> Opnds;
10204     unsigned BuildVecNumElts =  N0.getNumOperands();
10205
10206     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10207       Opnds.push_back(N0.getOperand(i));
10208     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10209       Opnds.push_back(N1.getOperand(i));
10210
10211     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10212                        Opnds.size());
10213   }
10214
10215   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10216   // nodes often generate nop CONCAT_VECTOR nodes.
10217   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10218   // place the incoming vectors at the exact same location.
10219   SDValue SingleSource = SDValue();
10220   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10221
10222   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10223     SDValue Op = N->getOperand(i);
10224
10225     if (Op.getOpcode() == ISD::UNDEF)
10226       continue;
10227
10228     // Check if this is the identity extract:
10229     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10230       return SDValue();
10231
10232     // Find the single incoming vector for the extract_subvector.
10233     if (SingleSource.getNode()) {
10234       if (Op.getOperand(0) != SingleSource)
10235         return SDValue();
10236     } else {
10237       SingleSource = Op.getOperand(0);
10238
10239       // Check the source type is the same as the type of the result.
10240       // If not, this concat may extend the vector, so we can not
10241       // optimize it away.
10242       if (SingleSource.getValueType() != N->getValueType(0))
10243         return SDValue();
10244     }
10245
10246     unsigned IdentityIndex = i * PartNumElem;
10247     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10248     // The extract index must be constant.
10249     if (!CS)
10250       return SDValue();
10251
10252     // Check that we are reading from the identity index.
10253     if (CS->getZExtValue() != IdentityIndex)
10254       return SDValue();
10255   }
10256
10257   if (SingleSource.getNode())
10258     return SingleSource;
10259
10260   return SDValue();
10261 }
10262
10263 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10264   EVT NVT = N->getValueType(0);
10265   SDValue V = N->getOperand(0);
10266
10267   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10268     // Combine:
10269     //    (extract_subvec (concat V1, V2, ...), i)
10270     // Into:
10271     //    Vi if possible
10272     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10273     // type.
10274     if (V->getOperand(0).getValueType() != NVT)
10275       return SDValue();
10276     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10277     unsigned NumElems = NVT.getVectorNumElements();
10278     assert((Idx % NumElems) == 0 &&
10279            "IDX in concat is not a multiple of the result vector length.");
10280     return V->getOperand(Idx / NumElems);
10281   }
10282
10283   // Skip bitcasting
10284   if (V->getOpcode() == ISD::BITCAST)
10285     V = V.getOperand(0);
10286
10287   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10288     SDLoc dl(N);
10289     // Handle only simple case where vector being inserted and vector
10290     // being extracted are of same type, and are half size of larger vectors.
10291     EVT BigVT = V->getOperand(0).getValueType();
10292     EVT SmallVT = V->getOperand(1).getValueType();
10293     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10294       return SDValue();
10295
10296     // Only handle cases where both indexes are constants with the same type.
10297     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10298     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10299
10300     if (InsIdx && ExtIdx &&
10301         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10302         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10303       // Combine:
10304       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10305       // Into:
10306       //    indices are equal or bit offsets are equal => V1
10307       //    otherwise => (extract_subvec V1, ExtIdx)
10308       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10309           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10310         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10311       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10312                          DAG.getNode(ISD::BITCAST, dl,
10313                                      N->getOperand(0).getValueType(),
10314                                      V->getOperand(0)), N->getOperand(1));
10315     }
10316   }
10317
10318   return SDValue();
10319 }
10320
10321 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10322 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10323   EVT VT = N->getValueType(0);
10324   unsigned NumElts = VT.getVectorNumElements();
10325
10326   SDValue N0 = N->getOperand(0);
10327   SDValue N1 = N->getOperand(1);
10328   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10329
10330   SmallVector<SDValue, 4> Ops;
10331   EVT ConcatVT = N0.getOperand(0).getValueType();
10332   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10333   unsigned NumConcats = NumElts / NumElemsPerConcat;
10334
10335   // Look at every vector that's inserted. We're looking for exact
10336   // subvector-sized copies from a concatenated vector
10337   for (unsigned I = 0; I != NumConcats; ++I) {
10338     // Make sure we're dealing with a copy.
10339     unsigned Begin = I * NumElemsPerConcat;
10340     bool AllUndef = true, NoUndef = true;
10341     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10342       if (SVN->getMaskElt(J) >= 0)
10343         AllUndef = false;
10344       else
10345         NoUndef = false;
10346     }
10347
10348     if (NoUndef) {
10349       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10350         return SDValue();
10351
10352       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10353         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10354           return SDValue();
10355
10356       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10357       if (FirstElt < N0.getNumOperands())
10358         Ops.push_back(N0.getOperand(FirstElt));
10359       else
10360         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10361
10362     } else if (AllUndef) {
10363       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10364     } else { // Mixed with general masks and undefs, can't do optimization.
10365       return SDValue();
10366     }
10367   }
10368
10369   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10370                      Ops.size());
10371 }
10372
10373 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10374   EVT VT = N->getValueType(0);
10375   unsigned NumElts = VT.getVectorNumElements();
10376
10377   SDValue N0 = N->getOperand(0);
10378   SDValue N1 = N->getOperand(1);
10379
10380   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10381
10382   // Canonicalize shuffle undef, undef -> undef
10383   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10384     return DAG.getUNDEF(VT);
10385
10386   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10387
10388   // Canonicalize shuffle v, v -> v, undef
10389   if (N0 == N1) {
10390     SmallVector<int, 8> NewMask;
10391     for (unsigned i = 0; i != NumElts; ++i) {
10392       int Idx = SVN->getMaskElt(i);
10393       if (Idx >= (int)NumElts) Idx -= NumElts;
10394       NewMask.push_back(Idx);
10395     }
10396     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10397                                 &NewMask[0]);
10398   }
10399
10400   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10401   if (N0.getOpcode() == ISD::UNDEF) {
10402     SmallVector<int, 8> NewMask;
10403     for (unsigned i = 0; i != NumElts; ++i) {
10404       int Idx = SVN->getMaskElt(i);
10405       if (Idx >= 0) {
10406         if (Idx >= (int)NumElts)
10407           Idx -= NumElts;
10408         else
10409           Idx = -1; // remove reference to lhs
10410       }
10411       NewMask.push_back(Idx);
10412     }
10413     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10414                                 &NewMask[0]);
10415   }
10416
10417   // Remove references to rhs if it is undef
10418   if (N1.getOpcode() == ISD::UNDEF) {
10419     bool Changed = false;
10420     SmallVector<int, 8> NewMask;
10421     for (unsigned i = 0; i != NumElts; ++i) {
10422       int Idx = SVN->getMaskElt(i);
10423       if (Idx >= (int)NumElts) {
10424         Idx = -1;
10425         Changed = true;
10426       }
10427       NewMask.push_back(Idx);
10428     }
10429     if (Changed)
10430       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10431   }
10432
10433   // If it is a splat, check if the argument vector is another splat or a
10434   // build_vector with all scalar elements the same.
10435   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10436     SDNode *V = N0.getNode();
10437
10438     // If this is a bit convert that changes the element type of the vector but
10439     // not the number of vector elements, look through it.  Be careful not to
10440     // look though conversions that change things like v4f32 to v2f64.
10441     if (V->getOpcode() == ISD::BITCAST) {
10442       SDValue ConvInput = V->getOperand(0);
10443       if (ConvInput.getValueType().isVector() &&
10444           ConvInput.getValueType().getVectorNumElements() == NumElts)
10445         V = ConvInput.getNode();
10446     }
10447
10448     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10449       assert(V->getNumOperands() == NumElts &&
10450              "BUILD_VECTOR has wrong number of operands");
10451       SDValue Base;
10452       bool AllSame = true;
10453       for (unsigned i = 0; i != NumElts; ++i) {
10454         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10455           Base = V->getOperand(i);
10456           break;
10457         }
10458       }
10459       // Splat of <u, u, u, u>, return <u, u, u, u>
10460       if (!Base.getNode())
10461         return N0;
10462       for (unsigned i = 0; i != NumElts; ++i) {
10463         if (V->getOperand(i) != Base) {
10464           AllSame = false;
10465           break;
10466         }
10467       }
10468       // Splat of <x, x, x, x>, return <x, x, x, x>
10469       if (AllSame)
10470         return N0;
10471     }
10472   }
10473
10474   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10475       Level < AfterLegalizeVectorOps &&
10476       (N1.getOpcode() == ISD::UNDEF ||
10477       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10478        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10479     SDValue V = partitionShuffleOfConcats(N, DAG);
10480
10481     if (V.getNode())
10482       return V;
10483   }
10484
10485   // If this shuffle node is simply a swizzle of another shuffle node,
10486   // and it reverses the swizzle of the previous shuffle then we can
10487   // optimize shuffle(shuffle(x, undef), undef) -> x.
10488   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10489       N1.getOpcode() == ISD::UNDEF) {
10490
10491     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10492
10493     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10494     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10495       return SDValue();
10496
10497     // The incoming shuffle must be of the same type as the result of the
10498     // current shuffle.
10499     assert(OtherSV->getOperand(0).getValueType() == VT &&
10500            "Shuffle types don't match");
10501
10502     for (unsigned i = 0; i != NumElts; ++i) {
10503       int Idx = SVN->getMaskElt(i);
10504       assert(Idx < (int)NumElts && "Index references undef operand");
10505       // Next, this index comes from the first value, which is the incoming
10506       // shuffle. Adopt the incoming index.
10507       if (Idx >= 0)
10508         Idx = OtherSV->getMaskElt(Idx);
10509
10510       // The combined shuffle must map each index to itself.
10511       if (Idx >= 0 && (unsigned)Idx != i)
10512         return SDValue();
10513     }
10514
10515     return OtherSV->getOperand(0);
10516   }
10517
10518   return SDValue();
10519 }
10520
10521 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10522   SDValue N0 = N->getOperand(0);
10523   SDValue N2 = N->getOperand(2);
10524
10525   // If the input vector is a concatenation, and the insert replaces
10526   // one of the halves, we can optimize into a single concat_vectors.
10527   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10528       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10529     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10530     EVT VT = N->getValueType(0);
10531
10532     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10533     // (concat_vectors Z, Y)
10534     if (InsIdx == 0)
10535       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10536                          N->getOperand(1), N0.getOperand(1));
10537
10538     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10539     // (concat_vectors X, Z)
10540     if (InsIdx == VT.getVectorNumElements()/2)
10541       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10542                          N0.getOperand(0), N->getOperand(1));
10543   }
10544
10545   return SDValue();
10546 }
10547
10548 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10549 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10550 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10551 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10552 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10553   EVT VT = N->getValueType(0);
10554   SDLoc dl(N);
10555   SDValue LHS = N->getOperand(0);
10556   SDValue RHS = N->getOperand(1);
10557   if (N->getOpcode() == ISD::AND) {
10558     if (RHS.getOpcode() == ISD::BITCAST)
10559       RHS = RHS.getOperand(0);
10560     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10561       SmallVector<int, 8> Indices;
10562       unsigned NumElts = RHS.getNumOperands();
10563       for (unsigned i = 0; i != NumElts; ++i) {
10564         SDValue Elt = RHS.getOperand(i);
10565         if (!isa<ConstantSDNode>(Elt))
10566           return SDValue();
10567
10568         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10569           Indices.push_back(i);
10570         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10571           Indices.push_back(NumElts);
10572         else
10573           return SDValue();
10574       }
10575
10576       // Let's see if the target supports this vector_shuffle.
10577       EVT RVT = RHS.getValueType();
10578       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10579         return SDValue();
10580
10581       // Return the new VECTOR_SHUFFLE node.
10582       EVT EltVT = RVT.getVectorElementType();
10583       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10584                                      DAG.getConstant(0, EltVT));
10585       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10586                                  RVT, &ZeroOps[0], ZeroOps.size());
10587       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10588       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10589       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10590     }
10591   }
10592
10593   return SDValue();
10594 }
10595
10596 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10597 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10598   assert(N->getValueType(0).isVector() &&
10599          "SimplifyVBinOp only works on vectors!");
10600
10601   SDValue LHS = N->getOperand(0);
10602   SDValue RHS = N->getOperand(1);
10603   SDValue Shuffle = XformToShuffleWithZero(N);
10604   if (Shuffle.getNode()) return Shuffle;
10605
10606   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10607   // this operation.
10608   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10609       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10610     // Check if both vectors are constants. If not bail out.
10611     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10612           cast<BuildVectorSDNode>(RHS)->isConstant()))
10613       return SDValue();
10614
10615     SmallVector<SDValue, 8> Ops;
10616     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10617       SDValue LHSOp = LHS.getOperand(i);
10618       SDValue RHSOp = RHS.getOperand(i);
10619
10620       // Can't fold divide by zero.
10621       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10622           N->getOpcode() == ISD::FDIV) {
10623         if ((RHSOp.getOpcode() == ISD::Constant &&
10624              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10625             (RHSOp.getOpcode() == ISD::ConstantFP &&
10626              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10627           break;
10628       }
10629
10630       EVT VT = LHSOp.getValueType();
10631       EVT RVT = RHSOp.getValueType();
10632       if (RVT != VT) {
10633         // Integer BUILD_VECTOR operands may have types larger than the element
10634         // size (e.g., when the element type is not legal).  Prior to type
10635         // legalization, the types may not match between the two BUILD_VECTORS.
10636         // Truncate one of the operands to make them match.
10637         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10638           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10639         } else {
10640           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10641           VT = RVT;
10642         }
10643       }
10644       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10645                                    LHSOp, RHSOp);
10646       if (FoldOp.getOpcode() != ISD::UNDEF &&
10647           FoldOp.getOpcode() != ISD::Constant &&
10648           FoldOp.getOpcode() != ISD::ConstantFP)
10649         break;
10650       Ops.push_back(FoldOp);
10651       AddToWorkList(FoldOp.getNode());
10652     }
10653
10654     if (Ops.size() == LHS.getNumOperands())
10655       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10656                          LHS.getValueType(), &Ops[0], Ops.size());
10657   }
10658
10659   return SDValue();
10660 }
10661
10662 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10663 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10664   assert(N->getValueType(0).isVector() &&
10665          "SimplifyVUnaryOp only works on vectors!");
10666
10667   SDValue N0 = N->getOperand(0);
10668
10669   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10670     return SDValue();
10671
10672   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10673   SmallVector<SDValue, 8> Ops;
10674   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10675     SDValue Op = N0.getOperand(i);
10676     if (Op.getOpcode() != ISD::UNDEF &&
10677         Op.getOpcode() != ISD::ConstantFP)
10678       break;
10679     EVT EltVT = Op.getValueType();
10680     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10681     if (FoldOp.getOpcode() != ISD::UNDEF &&
10682         FoldOp.getOpcode() != ISD::ConstantFP)
10683       break;
10684     Ops.push_back(FoldOp);
10685     AddToWorkList(FoldOp.getNode());
10686   }
10687
10688   if (Ops.size() != N0.getNumOperands())
10689     return SDValue();
10690
10691   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10692                      N0.getValueType(), &Ops[0], Ops.size());
10693 }
10694
10695 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10696                                     SDValue N1, SDValue N2){
10697   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10698
10699   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10700                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10701
10702   // If we got a simplified select_cc node back from SimplifySelectCC, then
10703   // break it down into a new SETCC node, and a new SELECT node, and then return
10704   // the SELECT node, since we were called with a SELECT node.
10705   if (SCC.getNode()) {
10706     // Check to see if we got a select_cc back (to turn into setcc/select).
10707     // Otherwise, just return whatever node we got back, like fabs.
10708     if (SCC.getOpcode() == ISD::SELECT_CC) {
10709       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10710                                   N0.getValueType(),
10711                                   SCC.getOperand(0), SCC.getOperand(1),
10712                                   SCC.getOperand(4));
10713       AddToWorkList(SETCC.getNode());
10714       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10715                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10716     }
10717
10718     return SCC;
10719   }
10720   return SDValue();
10721 }
10722
10723 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10724 /// are the two values being selected between, see if we can simplify the
10725 /// select.  Callers of this should assume that TheSelect is deleted if this
10726 /// returns true.  As such, they should return the appropriate thing (e.g. the
10727 /// node) back to the top-level of the DAG combiner loop to avoid it being
10728 /// looked at.
10729 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10730                                     SDValue RHS) {
10731
10732   // Cannot simplify select with vector condition
10733   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10734
10735   // If this is a select from two identical things, try to pull the operation
10736   // through the select.
10737   if (LHS.getOpcode() != RHS.getOpcode() ||
10738       !LHS.hasOneUse() || !RHS.hasOneUse())
10739     return false;
10740
10741   // If this is a load and the token chain is identical, replace the select
10742   // of two loads with a load through a select of the address to load from.
10743   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10744   // constants have been dropped into the constant pool.
10745   if (LHS.getOpcode() == ISD::LOAD) {
10746     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10747     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10748
10749     // Token chains must be identical.
10750     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10751         // Do not let this transformation reduce the number of volatile loads.
10752         LLD->isVolatile() || RLD->isVolatile() ||
10753         // If this is an EXTLOAD, the VT's must match.
10754         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10755         // If this is an EXTLOAD, the kind of extension must match.
10756         (LLD->getExtensionType() != RLD->getExtensionType() &&
10757          // The only exception is if one of the extensions is anyext.
10758          LLD->getExtensionType() != ISD::EXTLOAD &&
10759          RLD->getExtensionType() != ISD::EXTLOAD) ||
10760         // FIXME: this discards src value information.  This is
10761         // over-conservative. It would be beneficial to be able to remember
10762         // both potential memory locations.  Since we are discarding
10763         // src value info, don't do the transformation if the memory
10764         // locations are not in the default address space.
10765         LLD->getPointerInfo().getAddrSpace() != 0 ||
10766         RLD->getPointerInfo().getAddrSpace() != 0 ||
10767         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10768                                       LLD->getBasePtr().getValueType()))
10769       return false;
10770
10771     // Check that the select condition doesn't reach either load.  If so,
10772     // folding this will induce a cycle into the DAG.  If not, this is safe to
10773     // xform, so create a select of the addresses.
10774     SDValue Addr;
10775     if (TheSelect->getOpcode() == ISD::SELECT) {
10776       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10777       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10778           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10779         return false;
10780       // The loads must not depend on one another.
10781       if (LLD->isPredecessorOf(RLD) ||
10782           RLD->isPredecessorOf(LLD))
10783         return false;
10784       Addr = DAG.getSelect(SDLoc(TheSelect),
10785                            LLD->getBasePtr().getValueType(),
10786                            TheSelect->getOperand(0), LLD->getBasePtr(),
10787                            RLD->getBasePtr());
10788     } else {  // Otherwise SELECT_CC
10789       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10790       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10791
10792       if ((LLD->hasAnyUseOfValue(1) &&
10793            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10794           (RLD->hasAnyUseOfValue(1) &&
10795            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10796         return false;
10797
10798       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10799                          LLD->getBasePtr().getValueType(),
10800                          TheSelect->getOperand(0),
10801                          TheSelect->getOperand(1),
10802                          LLD->getBasePtr(), RLD->getBasePtr(),
10803                          TheSelect->getOperand(4));
10804     }
10805
10806     SDValue Load;
10807     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10808       Load = DAG.getLoad(TheSelect->getValueType(0),
10809                          SDLoc(TheSelect),
10810                          // FIXME: Discards pointer and TBAA info.
10811                          LLD->getChain(), Addr, MachinePointerInfo(),
10812                          LLD->isVolatile(), LLD->isNonTemporal(),
10813                          LLD->isInvariant(), LLD->getAlignment());
10814     } else {
10815       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10816                             RLD->getExtensionType() : LLD->getExtensionType(),
10817                             SDLoc(TheSelect),
10818                             TheSelect->getValueType(0),
10819                             // FIXME: Discards pointer and TBAA info.
10820                             LLD->getChain(), Addr, MachinePointerInfo(),
10821                             LLD->getMemoryVT(), LLD->isVolatile(),
10822                             LLD->isNonTemporal(), LLD->getAlignment());
10823     }
10824
10825     // Users of the select now use the result of the load.
10826     CombineTo(TheSelect, Load);
10827
10828     // Users of the old loads now use the new load's chain.  We know the
10829     // old-load value is dead now.
10830     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10831     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10832     return true;
10833   }
10834
10835   return false;
10836 }
10837
10838 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10839 /// where 'cond' is the comparison specified by CC.
10840 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10841                                       SDValue N2, SDValue N3,
10842                                       ISD::CondCode CC, bool NotExtCompare) {
10843   // (x ? y : y) -> y.
10844   if (N2 == N3) return N2;
10845
10846   EVT VT = N2.getValueType();
10847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10848   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10849   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10850
10851   // Determine if the condition we're dealing with is constant
10852   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10853                               N0, N1, CC, DL, false);
10854   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10855   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10856
10857   // fold select_cc true, x, y -> x
10858   if (SCCC && !SCCC->isNullValue())
10859     return N2;
10860   // fold select_cc false, x, y -> y
10861   if (SCCC && SCCC->isNullValue())
10862     return N3;
10863
10864   // Check to see if we can simplify the select into an fabs node
10865   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10866     // Allow either -0.0 or 0.0
10867     if (CFP->getValueAPF().isZero()) {
10868       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10869       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10870           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10871           N2 == N3.getOperand(0))
10872         return DAG.getNode(ISD::FABS, DL, VT, N0);
10873
10874       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10875       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10876           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10877           N2.getOperand(0) == N3)
10878         return DAG.getNode(ISD::FABS, DL, VT, N3);
10879     }
10880   }
10881
10882   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10883   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10884   // in it.  This is a win when the constant is not otherwise available because
10885   // it replaces two constant pool loads with one.  We only do this if the FP
10886   // type is known to be legal, because if it isn't, then we are before legalize
10887   // types an we want the other legalization to happen first (e.g. to avoid
10888   // messing with soft float) and if the ConstantFP is not legal, because if
10889   // it is legal, we may not need to store the FP constant in a constant pool.
10890   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10891     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10892       if (TLI.isTypeLegal(N2.getValueType()) &&
10893           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10894            TargetLowering::Legal) &&
10895           // If both constants have multiple uses, then we won't need to do an
10896           // extra load, they are likely around in registers for other users.
10897           (TV->hasOneUse() || FV->hasOneUse())) {
10898         Constant *Elts[] = {
10899           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10900           const_cast<ConstantFP*>(TV->getConstantFPValue())
10901         };
10902         Type *FPTy = Elts[0]->getType();
10903         const DataLayout &TD = *TLI.getDataLayout();
10904
10905         // Create a ConstantArray of the two constants.
10906         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10907         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10908                                             TD.getPrefTypeAlignment(FPTy));
10909         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10910
10911         // Get the offsets to the 0 and 1 element of the array so that we can
10912         // select between them.
10913         SDValue Zero = DAG.getIntPtrConstant(0);
10914         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10915         SDValue One = DAG.getIntPtrConstant(EltSize);
10916
10917         SDValue Cond = DAG.getSetCC(DL,
10918                                     getSetCCResultType(N0.getValueType()),
10919                                     N0, N1, CC);
10920         AddToWorkList(Cond.getNode());
10921         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10922                                           Cond, One, Zero);
10923         AddToWorkList(CstOffset.getNode());
10924         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10925                             CstOffset);
10926         AddToWorkList(CPIdx.getNode());
10927         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10928                            MachinePointerInfo::getConstantPool(), false,
10929                            false, false, Alignment);
10930
10931       }
10932     }
10933
10934   // Check to see if we can perform the "gzip trick", transforming
10935   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10936   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10937       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10938        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10939     EVT XType = N0.getValueType();
10940     EVT AType = N2.getValueType();
10941     if (XType.bitsGE(AType)) {
10942       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10943       // single-bit constant.
10944       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10945         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10946         ShCtV = XType.getSizeInBits()-ShCtV-1;
10947         SDValue ShCt = DAG.getConstant(ShCtV,
10948                                        getShiftAmountTy(N0.getValueType()));
10949         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10950                                     XType, N0, ShCt);
10951         AddToWorkList(Shift.getNode());
10952
10953         if (XType.bitsGT(AType)) {
10954           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10955           AddToWorkList(Shift.getNode());
10956         }
10957
10958         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10959       }
10960
10961       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10962                                   XType, N0,
10963                                   DAG.getConstant(XType.getSizeInBits()-1,
10964                                          getShiftAmountTy(N0.getValueType())));
10965       AddToWorkList(Shift.getNode());
10966
10967       if (XType.bitsGT(AType)) {
10968         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10969         AddToWorkList(Shift.getNode());
10970       }
10971
10972       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10973     }
10974   }
10975
10976   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10977   // where y is has a single bit set.
10978   // A plaintext description would be, we can turn the SELECT_CC into an AND
10979   // when the condition can be materialized as an all-ones register.  Any
10980   // single bit-test can be materialized as an all-ones register with
10981   // shift-left and shift-right-arith.
10982   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10983       N0->getValueType(0) == VT &&
10984       N1C && N1C->isNullValue() &&
10985       N2C && N2C->isNullValue()) {
10986     SDValue AndLHS = N0->getOperand(0);
10987     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10988     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10989       // Shift the tested bit over the sign bit.
10990       APInt AndMask = ConstAndRHS->getAPIntValue();
10991       SDValue ShlAmt =
10992         DAG.getConstant(AndMask.countLeadingZeros(),
10993                         getShiftAmountTy(AndLHS.getValueType()));
10994       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10995
10996       // Now arithmetic right shift it all the way over, so the result is either
10997       // all-ones, or zero.
10998       SDValue ShrAmt =
10999         DAG.getConstant(AndMask.getBitWidth()-1,
11000                         getShiftAmountTy(Shl.getValueType()));
11001       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11002
11003       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11004     }
11005   }
11006
11007   // fold select C, 16, 0 -> shl C, 4
11008   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11009     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11010       TargetLowering::ZeroOrOneBooleanContent) {
11011
11012     // If the caller doesn't want us to simplify this into a zext of a compare,
11013     // don't do it.
11014     if (NotExtCompare && N2C->getAPIntValue() == 1)
11015       return SDValue();
11016
11017     // Get a SetCC of the condition
11018     // NOTE: Don't create a SETCC if it's not legal on this target.
11019     if (!LegalOperations ||
11020         TLI.isOperationLegal(ISD::SETCC,
11021           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11022       SDValue Temp, SCC;
11023       // cast from setcc result type to select result type
11024       if (LegalTypes) {
11025         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11026                             N0, N1, CC);
11027         if (N2.getValueType().bitsLT(SCC.getValueType()))
11028           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11029                                         N2.getValueType());
11030         else
11031           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11032                              N2.getValueType(), SCC);
11033       } else {
11034         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11035         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11036                            N2.getValueType(), SCC);
11037       }
11038
11039       AddToWorkList(SCC.getNode());
11040       AddToWorkList(Temp.getNode());
11041
11042       if (N2C->getAPIntValue() == 1)
11043         return Temp;
11044
11045       // shl setcc result by log2 n2c
11046       return DAG.getNode(
11047           ISD::SHL, DL, N2.getValueType(), Temp,
11048           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11049                           getShiftAmountTy(Temp.getValueType())));
11050     }
11051   }
11052
11053   // Check to see if this is the equivalent of setcc
11054   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11055   // otherwise, go ahead with the folds.
11056   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11057     EVT XType = N0.getValueType();
11058     if (!LegalOperations ||
11059         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11060       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11061       if (Res.getValueType() != VT)
11062         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11063       return Res;
11064     }
11065
11066     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11067     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11068         (!LegalOperations ||
11069          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11070       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11071       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11072                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11073                                        getShiftAmountTy(Ctlz.getValueType())));
11074     }
11075     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11076     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11077       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11078                                   XType, DAG.getConstant(0, XType), N0);
11079       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11080       return DAG.getNode(ISD::SRL, DL, XType,
11081                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11082                          DAG.getConstant(XType.getSizeInBits()-1,
11083                                          getShiftAmountTy(XType)));
11084     }
11085     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11086     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11087       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11088                                  DAG.getConstant(XType.getSizeInBits()-1,
11089                                          getShiftAmountTy(N0.getValueType())));
11090       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11091     }
11092   }
11093
11094   // Check to see if this is an integer abs.
11095   // select_cc setg[te] X,  0,  X, -X ->
11096   // select_cc setgt    X, -1,  X, -X ->
11097   // select_cc setl[te] X,  0, -X,  X ->
11098   // select_cc setlt    X,  1, -X,  X ->
11099   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11100   if (N1C) {
11101     ConstantSDNode *SubC = NULL;
11102     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11103          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11104         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11105       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11106     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11107               (N1C->isOne() && CC == ISD::SETLT)) &&
11108              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11109       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11110
11111     EVT XType = N0.getValueType();
11112     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11113       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11114                                   N0,
11115                                   DAG.getConstant(XType.getSizeInBits()-1,
11116                                          getShiftAmountTy(N0.getValueType())));
11117       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11118                                 XType, N0, Shift);
11119       AddToWorkList(Shift.getNode());
11120       AddToWorkList(Add.getNode());
11121       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11122     }
11123   }
11124
11125   return SDValue();
11126 }
11127
11128 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11129 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11130                                    SDValue N1, ISD::CondCode Cond,
11131                                    SDLoc DL, bool foldBooleans) {
11132   TargetLowering::DAGCombinerInfo
11133     DagCombineInfo(DAG, Level, false, this);
11134   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11135 }
11136
11137 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11138 /// return a DAG expression to select that will generate the same value by
11139 /// multiplying by a magic number.  See:
11140 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11141 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11142   std::vector<SDNode*> Built;
11143   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11144
11145   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11146        ii != ee; ++ii)
11147     AddToWorkList(*ii);
11148   return S;
11149 }
11150
11151 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11152 /// return a DAG expression to select that will generate the same value by
11153 /// multiplying by a magic number.  See:
11154 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11155 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11156   std::vector<SDNode*> Built;
11157   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11158
11159   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11160        ii != ee; ++ii)
11161     AddToWorkList(*ii);
11162   return S;
11163 }
11164
11165 /// FindBaseOffset - Return true if base is a frame index, which is known not
11166 // to alias with anything but itself.  Provides base object and offset as
11167 // results.
11168 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11169                            const GlobalValue *&GV, const void *&CV) {
11170   // Assume it is a primitive operation.
11171   Base = Ptr; Offset = 0; GV = 0; CV = 0;
11172
11173   // If it's an adding a simple constant then integrate the offset.
11174   if (Base.getOpcode() == ISD::ADD) {
11175     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11176       Base = Base.getOperand(0);
11177       Offset += C->getZExtValue();
11178     }
11179   }
11180
11181   // Return the underlying GlobalValue, and update the Offset.  Return false
11182   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11183   // by multiple nodes with different offsets.
11184   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11185     GV = G->getGlobal();
11186     Offset += G->getOffset();
11187     return false;
11188   }
11189
11190   // Return the underlying Constant value, and update the Offset.  Return false
11191   // for ConstantSDNodes since the same constant pool entry may be represented
11192   // by multiple nodes with different offsets.
11193   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11194     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11195                                          : (const void *)C->getConstVal();
11196     Offset += C->getOffset();
11197     return false;
11198   }
11199   // If it's any of the following then it can't alias with anything but itself.
11200   return isa<FrameIndexSDNode>(Base);
11201 }
11202
11203 /// isAlias - Return true if there is any possibility that the two addresses
11204 /// overlap.
11205 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11206                           const Value *SrcValue1, int SrcValueOffset1,
11207                           unsigned SrcValueAlign1,
11208                           const MDNode *TBAAInfo1,
11209                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11210                           const Value *SrcValue2, int SrcValueOffset2,
11211                           unsigned SrcValueAlign2,
11212                           const MDNode *TBAAInfo2) const {
11213   // If they are the same then they must be aliases.
11214   if (Ptr1 == Ptr2) return true;
11215
11216   // If they are both volatile then they cannot be reordered.
11217   if (IsVolatile1 && IsVolatile2) return true;
11218
11219   // Gather base node and offset information.
11220   SDValue Base1, Base2;
11221   int64_t Offset1, Offset2;
11222   const GlobalValue *GV1, *GV2;
11223   const void *CV1, *CV2;
11224   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11225   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11226
11227   // If they have a same base address then check to see if they overlap.
11228   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11229     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11230
11231   // It is possible for different frame indices to alias each other, mostly
11232   // when tail call optimization reuses return address slots for arguments.
11233   // To catch this case, look up the actual index of frame indices to compute
11234   // the real alias relationship.
11235   if (isFrameIndex1 && isFrameIndex2) {
11236     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11237     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11238     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11239     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11240   }
11241
11242   // Otherwise, if we know what the bases are, and they aren't identical, then
11243   // we know they cannot alias.
11244   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11245     return false;
11246
11247   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11248   // compared to the size and offset of the access, we may be able to prove they
11249   // do not alias.  This check is conservative for now to catch cases created by
11250   // splitting vector types.
11251   if ((SrcValueAlign1 == SrcValueAlign2) &&
11252       (SrcValueOffset1 != SrcValueOffset2) &&
11253       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11254     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11255     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11256
11257     // There is no overlap between these relatively aligned accesses of similar
11258     // size, return no alias.
11259     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11260       return false;
11261   }
11262
11263   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11264     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11265 #ifndef NDEBUG
11266   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11267       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11268     UseAA = false;
11269 #endif
11270   if (UseAA && SrcValue1 && SrcValue2) {
11271     // Use alias analysis information.
11272     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11273     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11274     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11275     AliasAnalysis::AliasResult AAResult =
11276       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11277                                        UseTBAA ? TBAAInfo1 : 0),
11278                AliasAnalysis::Location(SrcValue2, Overlap2,
11279                                        UseTBAA ? TBAAInfo2 : 0));
11280     if (AAResult == AliasAnalysis::NoAlias)
11281       return false;
11282   }
11283
11284   // Otherwise we have to assume they alias.
11285   return true;
11286 }
11287
11288 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11289   SDValue Ptr0, Ptr1;
11290   int64_t Size0, Size1;
11291   bool IsVolatile0, IsVolatile1;
11292   const Value *SrcValue0, *SrcValue1;
11293   int SrcValueOffset0, SrcValueOffset1;
11294   unsigned SrcValueAlign0, SrcValueAlign1;
11295   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11296   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11297                 SrcValueAlign0, SrcTBAAInfo0);
11298   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11299                 SrcValueAlign1, SrcTBAAInfo1);
11300   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11301                  SrcValueAlign0, SrcTBAAInfo0,
11302                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11303                  SrcValueAlign1, SrcTBAAInfo1);
11304 }
11305
11306 /// FindAliasInfo - Extracts the relevant alias information from the memory
11307 /// node.  Returns true if the operand was a nonvolatile load.
11308 bool DAGCombiner::FindAliasInfo(SDNode *N,
11309                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11310                                 const Value *&SrcValue,
11311                                 int &SrcValueOffset,
11312                                 unsigned &SrcValueAlign,
11313                                 const MDNode *&TBAAInfo) const {
11314   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11315
11316   Ptr = LS->getBasePtr();
11317   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11318   IsVolatile = LS->isVolatile();
11319   SrcValue = LS->getSrcValue();
11320   SrcValueOffset = LS->getSrcValueOffset();
11321   SrcValueAlign = LS->getOriginalAlignment();
11322   TBAAInfo = LS->getTBAAInfo();
11323   return isa<LoadSDNode>(LS) && !IsVolatile;
11324 }
11325
11326 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11327 /// looking for aliasing nodes and adding them to the Aliases vector.
11328 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11329                                    SmallVectorImpl<SDValue> &Aliases) {
11330   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11331   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11332
11333   // Get alias information for node.
11334   SDValue Ptr;
11335   int64_t Size;
11336   bool IsVolatile;
11337   const Value *SrcValue;
11338   int SrcValueOffset;
11339   unsigned SrcValueAlign;
11340   const MDNode *SrcTBAAInfo;
11341   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11342                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11343
11344   // Starting off.
11345   Chains.push_back(OriginalChain);
11346   unsigned Depth = 0;
11347
11348   // Look at each chain and determine if it is an alias.  If so, add it to the
11349   // aliases list.  If not, then continue up the chain looking for the next
11350   // candidate.
11351   while (!Chains.empty()) {
11352     SDValue Chain = Chains.back();
11353     Chains.pop_back();
11354
11355     // For TokenFactor nodes, look at each operand and only continue up the
11356     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11357     // find more and revert to original chain since the xform is unlikely to be
11358     // profitable.
11359     //
11360     // FIXME: The depth check could be made to return the last non-aliasing
11361     // chain we found before we hit a tokenfactor rather than the original
11362     // chain.
11363     if (Depth > 6 || Aliases.size() == 2) {
11364       Aliases.clear();
11365       Aliases.push_back(OriginalChain);
11366       return;
11367     }
11368
11369     // Don't bother if we've been before.
11370     if (!Visited.insert(Chain.getNode()))
11371       continue;
11372
11373     switch (Chain.getOpcode()) {
11374     case ISD::EntryToken:
11375       // Entry token is ideal chain operand, but handled in FindBetterChain.
11376       break;
11377
11378     case ISD::LOAD:
11379     case ISD::STORE: {
11380       // Get alias information for Chain.
11381       SDValue OpPtr;
11382       int64_t OpSize;
11383       bool OpIsVolatile;
11384       const Value *OpSrcValue;
11385       int OpSrcValueOffset;
11386       unsigned OpSrcValueAlign;
11387       const MDNode *OpSrcTBAAInfo;
11388       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11389                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11390                                     OpSrcValueAlign,
11391                                     OpSrcTBAAInfo);
11392
11393       // If chain is alias then stop here.
11394       if (!(IsLoad && IsOpLoad) &&
11395           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11396                   SrcValueAlign, SrcTBAAInfo,
11397                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11398                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11399         Aliases.push_back(Chain);
11400       } else {
11401         // Look further up the chain.
11402         Chains.push_back(Chain.getOperand(0));
11403         ++Depth;
11404       }
11405       break;
11406     }
11407
11408     case ISD::TokenFactor:
11409       // We have to check each of the operands of the token factor for "small"
11410       // token factors, so we queue them up.  Adding the operands to the queue
11411       // (stack) in reverse order maintains the original order and increases the
11412       // likelihood that getNode will find a matching token factor (CSE.)
11413       if (Chain.getNumOperands() > 16) {
11414         Aliases.push_back(Chain);
11415         break;
11416       }
11417       for (unsigned n = Chain.getNumOperands(); n;)
11418         Chains.push_back(Chain.getOperand(--n));
11419       ++Depth;
11420       break;
11421
11422     default:
11423       // For all other instructions we will just have to take what we can get.
11424       Aliases.push_back(Chain);
11425       break;
11426     }
11427   }
11428
11429   // We need to be careful here to also search for aliases through the
11430   // value operand of a store, etc. Consider the following situation:
11431   //   Token1 = ...
11432   //   L1 = load Token1, %52
11433   //   S1 = store Token1, L1, %51
11434   //   L2 = load Token1, %52+8
11435   //   S2 = store Token1, L2, %51+8
11436   //   Token2 = Token(S1, S2)
11437   //   L3 = load Token2, %53
11438   //   S3 = store Token2, L3, %52
11439   //   L4 = load Token2, %53+8
11440   //   S4 = store Token2, L4, %52+8
11441   // If we search for aliases of S3 (which loads address %52), and we look
11442   // only through the chain, then we'll miss the trivial dependence on L1
11443   // (which also loads from %52). We then might change all loads and
11444   // stores to use Token1 as their chain operand, which could result in
11445   // copying %53 into %52 before copying %52 into %51 (which should
11446   // happen first).
11447   //
11448   // The problem is, however, that searching for such data dependencies
11449   // can become expensive, and the cost is not directly related to the
11450   // chain depth. Instead, we'll rule out such configurations here by
11451   // insisting that we've visited all chain users (except for users
11452   // of the original chain, which is not necessary). When doing this,
11453   // we need to look through nodes we don't care about (otherwise, things
11454   // like register copies will interfere with trivial cases).
11455
11456   SmallVector<const SDNode *, 16> Worklist;
11457   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11458        IE = Visited.end(); I != IE; ++I)
11459     if (*I != OriginalChain.getNode())
11460       Worklist.push_back(*I);
11461
11462   while (!Worklist.empty()) {
11463     const SDNode *M = Worklist.pop_back_val();
11464
11465     // We have already visited M, and want to make sure we've visited any uses
11466     // of M that we care about. For uses that we've not visisted, and don't
11467     // care about, queue them to the worklist.
11468
11469     for (SDNode::use_iterator UI = M->use_begin(),
11470          UIE = M->use_end(); UI != UIE; ++UI)
11471       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11472         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11473           // We've not visited this use, and we care about it (it could have an
11474           // ordering dependency with the original node).
11475           Aliases.clear();
11476           Aliases.push_back(OriginalChain);
11477           return;
11478         }
11479
11480         // We've not visited this use, but we don't care about it. Mark it as
11481         // visited and enqueue it to the worklist.
11482         Worklist.push_back(*UI);
11483       }
11484   }
11485 }
11486
11487 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11488 /// for a better chain (aliasing node.)
11489 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11490   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11491
11492   // Accumulate all the aliases to this node.
11493   GatherAllAliases(N, OldChain, Aliases);
11494
11495   // If no operands then chain to entry token.
11496   if (Aliases.size() == 0)
11497     return DAG.getEntryNode();
11498
11499   // If a single operand then chain to it.  We don't need to revisit it.
11500   if (Aliases.size() == 1)
11501     return Aliases[0];
11502
11503   // Construct a custom tailored token factor.
11504   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11505                      &Aliases[0], Aliases.size());
11506 }
11507
11508 // SelectionDAG::Combine - This is the entry point for the file.
11509 //
11510 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11511                            CodeGenOpt::Level OptLevel) {
11512   /// run - This is the main entry point to this class.
11513   ///
11514   DAGCombiner(*this, AA, OptLevel).Run(Level);
11515 }