Reenable use of TBAA during CodeGen
[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   static cl::opt<bool>
60     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61                cl::desc("Enable DAG combiner's use of TBAA"));
62
63 #ifndef NDEBUG
64   static cl::opt<std::string>
65     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66                cl::desc("Only use DAG-combiner alias analysis in this"
67                         " function"));
68 #endif
69
70   /// Hidden option to stress test load slicing, i.e., when this option
71   /// is enabled, load slicing bypasses most of its profitability guards.
72   static cl::opt<bool>
73   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74                     cl::desc("Bypass the profitability model of load "
75                              "slicing"),
76                     cl::init(false));
77
78 //------------------------------ DAGCombiner ---------------------------------//
79
80   class DAGCombiner {
81     SelectionDAG &DAG;
82     const TargetLowering &TLI;
83     CombineLevel Level;
84     CodeGenOpt::Level OptLevel;
85     bool LegalOperations;
86     bool LegalTypes;
87     bool ForCodeSize;
88
89     // Worklist of all of the nodes that need to be simplified.
90     //
91     // This has the semantics that when adding to the worklist,
92     // the item added must be next to be processed. It should
93     // also only appear once. The naive approach to this takes
94     // linear time.
95     //
96     // To reduce the insert/remove time to logarithmic, we use
97     // a set and a vector to maintain our worklist.
98     //
99     // The set contains the items on the worklist, but does not
100     // maintain the order they should be visited.
101     //
102     // The vector maintains the order nodes should be visited, but may
103     // contain duplicate or removed nodes. When choosing a node to
104     // visit, we pop off the order stack until we find an item that is
105     // also in the contents set. All operations are O(log N).
106     SmallPtrSet<SDNode*, 64> WorkListContents;
107     SmallVector<SDNode*, 64> WorkListOrder;
108
109     // AA - Used for DAG load/store alias analysis.
110     AliasAnalysis &AA;
111
112     /// AddUsersToWorkList - When an instruction is simplified, add all users of
113     /// the instruction to the work lists because they might get more simplified
114     /// now.
115     ///
116     void AddUsersToWorkList(SDNode *N) {
117       for (SDNode *Node : N->uses())
118         AddToWorkList(Node);
119     }
120
121     /// visit - call the node-specific routine that knows how to fold each
122     /// particular type of node.
123     SDValue visit(SDNode *N);
124
125   public:
126     /// AddToWorkList - Add to the work list making sure its instance is at the
127     /// back (next to be processed.)
128     void AddToWorkList(SDNode *N) {
129       WorkListContents.insert(N);
130       WorkListOrder.push_back(N);
131     }
132
133     /// removeFromWorkList - remove all instances of N from the worklist.
134     ///
135     void removeFromWorkList(SDNode *N) {
136       WorkListContents.erase(N);
137     }
138
139     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
140                       bool AddTo = true);
141
142     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
143       return CombineTo(N, &Res, 1, AddTo);
144     }
145
146     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
147                       bool AddTo = true) {
148       SDValue To[] = { Res0, Res1 };
149       return CombineTo(N, To, 2, AddTo);
150     }
151
152     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
153
154   private:
155
156     /// SimplifyDemandedBits - Check the specified integer node value to see if
157     /// it can be simplified or if things it uses can be simplified by bit
158     /// propagation.  If so, return true.
159     bool SimplifyDemandedBits(SDValue Op) {
160       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
161       APInt Demanded = APInt::getAllOnesValue(BitWidth);
162       return SimplifyDemandedBits(Op, Demanded);
163     }
164
165     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
166
167     bool CombineToPreIndexedLoadStore(SDNode *N);
168     bool CombineToPostIndexedLoadStore(SDNode *N);
169     bool SliceUpLoad(SDNode *N);
170
171     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
172     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
173     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
174     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
175     SDValue PromoteIntBinOp(SDValue Op);
176     SDValue PromoteIntShiftOp(SDValue Op);
177     SDValue PromoteExtend(SDValue Op);
178     bool PromoteLoad(SDValue Op);
179
180     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
181                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
182                          ISD::NodeType ExtType);
183
184     /// combine - call the node-specific routine that knows how to fold each
185     /// particular type of node. If that doesn't do anything, try the
186     /// target-specific DAG combines.
187     SDValue combine(SDNode *N);
188
189     // Visitation implementation - Implement dag node combining for different
190     // node types.  The semantics are as follows:
191     // Return Value:
192     //   SDValue.getNode() == 0 - No change was made
193     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
194     //   otherwise              - N should be replaced by the returned Operand.
195     //
196     SDValue visitTokenFactor(SDNode *N);
197     SDValue visitMERGE_VALUES(SDNode *N);
198     SDValue visitADD(SDNode *N);
199     SDValue visitSUB(SDNode *N);
200     SDValue visitADDC(SDNode *N);
201     SDValue visitSUBC(SDNode *N);
202     SDValue visitADDE(SDNode *N);
203     SDValue visitSUBE(SDNode *N);
204     SDValue visitMUL(SDNode *N);
205     SDValue visitSDIV(SDNode *N);
206     SDValue visitUDIV(SDNode *N);
207     SDValue visitSREM(SDNode *N);
208     SDValue visitUREM(SDNode *N);
209     SDValue visitMULHU(SDNode *N);
210     SDValue visitMULHS(SDNode *N);
211     SDValue visitSMUL_LOHI(SDNode *N);
212     SDValue visitUMUL_LOHI(SDNode *N);
213     SDValue visitSMULO(SDNode *N);
214     SDValue visitUMULO(SDNode *N);
215     SDValue visitSDIVREM(SDNode *N);
216     SDValue visitUDIVREM(SDNode *N);
217     SDValue visitAND(SDNode *N);
218     SDValue visitOR(SDNode *N);
219     SDValue visitXOR(SDNode *N);
220     SDValue SimplifyVBinOp(SDNode *N);
221     SDValue SimplifyVUnaryOp(SDNode *N);
222     SDValue visitSHL(SDNode *N);
223     SDValue visitSRA(SDNode *N);
224     SDValue visitSRL(SDNode *N);
225     SDValue visitRotate(SDNode *N);
226     SDValue visitCTLZ(SDNode *N);
227     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
228     SDValue visitCTTZ(SDNode *N);
229     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
230     SDValue visitCTPOP(SDNode *N);
231     SDValue visitSELECT(SDNode *N);
232     SDValue visitVSELECT(SDNode *N);
233     SDValue visitSELECT_CC(SDNode *N);
234     SDValue visitSETCC(SDNode *N);
235     SDValue visitSIGN_EXTEND(SDNode *N);
236     SDValue visitZERO_EXTEND(SDNode *N);
237     SDValue visitANY_EXTEND(SDNode *N);
238     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
239     SDValue visitTRUNCATE(SDNode *N);
240     SDValue visitBITCAST(SDNode *N);
241     SDValue visitBUILD_PAIR(SDNode *N);
242     SDValue visitFADD(SDNode *N);
243     SDValue visitFSUB(SDNode *N);
244     SDValue visitFMUL(SDNode *N);
245     SDValue visitFMA(SDNode *N);
246     SDValue visitFDIV(SDNode *N);
247     SDValue visitFREM(SDNode *N);
248     SDValue visitFCOPYSIGN(SDNode *N);
249     SDValue visitSINT_TO_FP(SDNode *N);
250     SDValue visitUINT_TO_FP(SDNode *N);
251     SDValue visitFP_TO_SINT(SDNode *N);
252     SDValue visitFP_TO_UINT(SDNode *N);
253     SDValue visitFP_ROUND(SDNode *N);
254     SDValue visitFP_ROUND_INREG(SDNode *N);
255     SDValue visitFP_EXTEND(SDNode *N);
256     SDValue visitFNEG(SDNode *N);
257     SDValue visitFABS(SDNode *N);
258     SDValue visitFCEIL(SDNode *N);
259     SDValue visitFTRUNC(SDNode *N);
260     SDValue visitFFLOOR(SDNode *N);
261     SDValue visitBRCOND(SDNode *N);
262     SDValue visitBR_CC(SDNode *N);
263     SDValue visitLOAD(SDNode *N);
264     SDValue visitSTORE(SDNode *N);
265     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
266     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
267     SDValue visitBUILD_VECTOR(SDNode *N);
268     SDValue visitCONCAT_VECTORS(SDNode *N);
269     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
270     SDValue visitVECTOR_SHUFFLE(SDNode *N);
271     SDValue visitINSERT_SUBVECTOR(SDNode *N);
272
273     SDValue XformToShuffleWithZero(SDNode *N);
274     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
275
276     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
277
278     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
279     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
280     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
281     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
282                              SDValue N3, ISD::CondCode CC,
283                              bool NotExtCompare = false);
284     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
285                           SDLoc DL, bool foldBooleans = true);
286
287     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
288                            SDValue &CC) const;
289     bool isOneUseSetCC(SDValue N) const;
290
291     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
292                                          unsigned HiOp);
293     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
294     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
295     SDValue BuildSDIV(SDNode *N);
296     SDValue BuildUDIV(SDNode *N);
297     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
298                                bool DemandHighBits = true);
299     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
300     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
301                               SDValue InnerPos, SDValue InnerNeg,
302                               unsigned PosOpcode, unsigned NegOpcode,
303                               SDLoc DL);
304     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
305     SDValue ReduceLoadWidth(SDNode *N);
306     SDValue ReduceLoadOpStoreWidth(SDNode *N);
307     SDValue TransformFPLoadStorePair(SDNode *N);
308     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
309     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
310
311     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
312
313     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
314     /// looking for aliasing nodes and adding them to the Aliases vector.
315     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
316                           SmallVectorImpl<SDValue> &Aliases);
317
318     /// isAlias - Return true if there is any possibility that the two addresses
319     /// overlap.
320     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
321                  const Value *SrcValue1, int SrcValueOffset1,
322                  unsigned SrcValueAlign1,
323                  const MDNode *TBAAInfo1,
324                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
325                  const Value *SrcValue2, int SrcValueOffset2,
326                  unsigned SrcValueAlign2,
327                  const MDNode *TBAAInfo2) const;
328
329     /// isAlias - Return true if there is any possibility that the two addresses
330     /// overlap.
331     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
332
333     /// FindAliasInfo - Extracts the relevant alias information from the memory
334     /// node.  Returns true if the operand was a load.
335     bool FindAliasInfo(SDNode *N,
336                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
337                        const Value *&SrcValue, int &SrcValueOffset,
338                        unsigned &SrcValueAlignment,
339                        const MDNode *&TBAAInfo) const;
340
341     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
342     /// looking for a better chain (aliasing node.)
343     SDValue FindBetterChain(SDNode *N, SDValue Chain);
344
345     /// Merge consecutive store operations into a wide store.
346     /// This optimization uses wide integers or vectors when possible.
347     /// \return True if some memory operations were changed.
348     bool MergeConsecutiveStores(StoreSDNode *N);
349
350     /// \brief Try to transform a truncation where C is a constant:
351     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
352     ///
353     /// \p N needs to be a truncation and its first operand an AND. Other
354     /// requirements are checked by the function (e.g. that trunc is
355     /// single-use) and if missed an empty SDValue is returned.
356     SDValue distributeTruncateThroughAnd(SDNode *N);
357
358   public:
359     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
360         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
361           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
362       AttributeSet FnAttrs =
363           DAG.getMachineFunction().getFunction()->getAttributes();
364       ForCodeSize =
365           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
366                                Attribute::OptimizeForSize) ||
367           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
368     }
369
370     /// Run - runs the dag combiner on all nodes in the work list
371     void Run(CombineLevel AtLevel);
372
373     SelectionDAG &getDAG() const { return DAG; }
374
375     /// getShiftAmountTy - Returns a type large enough to hold any valid
376     /// shift amount - before type legalization these can be huge.
377     EVT getShiftAmountTy(EVT LHSTy) {
378       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
379       if (LHSTy.isVector())
380         return LHSTy;
381       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
382                         : TLI.getPointerTy();
383     }
384
385     /// isTypeLegal - This method returns true if we are running before type
386     /// legalization or if the specified VT is legal.
387     bool isTypeLegal(const EVT &VT) {
388       if (!LegalTypes) return true;
389       return TLI.isTypeLegal(VT);
390     }
391
392     /// getSetCCResultType - Convenience wrapper around
393     /// TargetLowering::getSetCCResultType
394     EVT getSetCCResultType(EVT VT) const {
395       return TLI.getSetCCResultType(*DAG.getContext(), VT);
396     }
397   };
398 }
399
400
401 namespace {
402 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
403 /// nodes from the worklist.
404 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
405   DAGCombiner &DC;
406 public:
407   explicit WorkListRemover(DAGCombiner &dc)
408     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
409
410   void NodeDeleted(SDNode *N, SDNode *E) override {
411     DC.removeFromWorkList(N);
412   }
413 };
414 }
415
416 //===----------------------------------------------------------------------===//
417 //  TargetLowering::DAGCombinerInfo implementation
418 //===----------------------------------------------------------------------===//
419
420 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
421   ((DAGCombiner*)DC)->AddToWorkList(N);
422 }
423
424 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
425   ((DAGCombiner*)DC)->removeFromWorkList(N);
426 }
427
428 SDValue TargetLowering::DAGCombinerInfo::
429 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
430   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
431 }
432
433 SDValue TargetLowering::DAGCombinerInfo::
434 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
435   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
436 }
437
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
442 }
443
444 void TargetLowering::DAGCombinerInfo::
445 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
446   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
447 }
448
449 //===----------------------------------------------------------------------===//
450 // Helper Functions
451 //===----------------------------------------------------------------------===//
452
453 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
454 /// specified expression for the same cost as the expression itself, or 2 if we
455 /// can compute the negated form more cheaply than the expression itself.
456 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
457                                const TargetLowering &TLI,
458                                const TargetOptions *Options,
459                                unsigned Depth = 0) {
460   // fneg is removable even if it has multiple uses.
461   if (Op.getOpcode() == ISD::FNEG) return 2;
462
463   // Don't allow anything with multiple uses.
464   if (!Op.hasOneUse()) return 0;
465
466   // Don't recurse exponentially.
467   if (Depth > 6) return 0;
468
469   switch (Op.getOpcode()) {
470   default: return false;
471   case ISD::ConstantFP:
472     // Don't invert constant FP values after legalize.  The negated constant
473     // isn't necessarily legal.
474     return LegalOperations ? 0 : 1;
475   case ISD::FADD:
476     // FIXME: determine better conditions for this xform.
477     if (!Options->UnsafeFPMath) return 0;
478
479     // After operation legalization, it might not be legal to create new FSUBs.
480     if (LegalOperations &&
481         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
482       return 0;
483
484     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
485     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486                                     Options, Depth + 1))
487       return V;
488     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
489     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
490                               Depth + 1);
491   case ISD::FSUB:
492     // We can't turn -(A-B) into B-A when we honor signed zeros.
493     if (!Options->UnsafeFPMath) return 0;
494
495     // fold (fneg (fsub A, B)) -> (fsub B, A)
496     return 1;
497
498   case ISD::FMUL:
499   case ISD::FDIV:
500     if (Options->HonorSignDependentRoundingFPMath()) return 0;
501
502     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
503     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
504                                     Options, Depth + 1))
505       return V;
506
507     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
508                               Depth + 1);
509
510   case ISD::FP_EXTEND:
511   case ISD::FP_ROUND:
512   case ISD::FSIN:
513     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
514                               Depth + 1);
515   }
516 }
517
518 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
519 /// returns the newly negated expression.
520 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
521                                     bool LegalOperations, unsigned Depth = 0) {
522   // fneg is removable even if it has multiple uses.
523   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
524
525   // Don't allow anything with multiple uses.
526   assert(Op.hasOneUse() && "Unknown reuse!");
527
528   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
529   switch (Op.getOpcode()) {
530   default: llvm_unreachable("Unknown code");
531   case ISD::ConstantFP: {
532     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
533     V.changeSign();
534     return DAG.getConstantFP(V, Op.getValueType());
535   }
536   case ISD::FADD:
537     // FIXME: determine better conditions for this xform.
538     assert(DAG.getTarget().Options.UnsafeFPMath);
539
540     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
541     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
542                            DAG.getTargetLoweringInfo(),
543                            &DAG.getTarget().Options, Depth+1))
544       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
545                          GetNegatedExpression(Op.getOperand(0), DAG,
546                                               LegalOperations, Depth+1),
547                          Op.getOperand(1));
548     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
549     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
550                        GetNegatedExpression(Op.getOperand(1), DAG,
551                                             LegalOperations, Depth+1),
552                        Op.getOperand(0));
553   case ISD::FSUB:
554     // We can't turn -(A-B) into B-A when we honor signed zeros.
555     assert(DAG.getTarget().Options.UnsafeFPMath);
556
557     // fold (fneg (fsub 0, B)) -> B
558     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
559       if (N0CFP->getValueAPF().isZero())
560         return Op.getOperand(1);
561
562     // fold (fneg (fsub A, B)) -> (fsub B, A)
563     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
564                        Op.getOperand(1), Op.getOperand(0));
565
566   case ISD::FMUL:
567   case ISD::FDIV:
568     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
569
570     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
571     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
572                            DAG.getTargetLoweringInfo(),
573                            &DAG.getTarget().Options, Depth+1))
574       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
575                          GetNegatedExpression(Op.getOperand(0), DAG,
576                                               LegalOperations, Depth+1),
577                          Op.getOperand(1));
578
579     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
580     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
581                        Op.getOperand(0),
582                        GetNegatedExpression(Op.getOperand(1), DAG,
583                                             LegalOperations, Depth+1));
584
585   case ISD::FP_EXTEND:
586   case ISD::FSIN:
587     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
588                        GetNegatedExpression(Op.getOperand(0), DAG,
589                                             LegalOperations, Depth+1));
590   case ISD::FP_ROUND:
591       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
592                          GetNegatedExpression(Op.getOperand(0), DAG,
593                                               LegalOperations, Depth+1),
594                          Op.getOperand(1));
595   }
596 }
597
598 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
599 // that selects between the target values used for true and false, making it
600 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
601 // the appropriate nodes based on the type of node we are checking. This
602 // simplifies life a bit for the callers.
603 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
604                                     SDValue &CC) const {
605   if (N.getOpcode() == ISD::SETCC) {
606     LHS = N.getOperand(0);
607     RHS = N.getOperand(1);
608     CC  = N.getOperand(2);
609     return true;
610   }
611
612   if (N.getOpcode() != ISD::SELECT_CC ||
613       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
614       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
615     return false;
616
617   LHS = N.getOperand(0);
618   RHS = N.getOperand(1);
619   CC  = N.getOperand(4);
620   return true;
621 }
622
623 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
624 // one use.  If this is true, it allows the users to invert the operation for
625 // free when it is profitable to do so.
626 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
627   SDValue N0, N1, N2;
628   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
629     return true;
630   return false;
631 }
632
633 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
634 /// elements are all the same constant or undefined.
635 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
636   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
637   if (!C)
638     return false;
639
640   APInt SplatUndef;
641   unsigned SplatBitSize;
642   bool HasAnyUndefs;
643   EVT EltVT = N->getValueType(0).getVectorElementType();
644   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
645                              HasAnyUndefs) &&
646           EltVT.getSizeInBits() >= SplatBitSize);
647 }
648
649 // \brief Returns the SDNode if it is a constant BuildVector or constant.
650 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
651   if (isa<ConstantSDNode>(N))
652     return N.getNode();
653   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
654   if(BV && BV->isConstant())
655     return BV;
656   return NULL;
657 }
658
659 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
660 // int.
661 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
662   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
663     return CN;
664
665   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
666     return BV->getConstantSplatValue();
667
668   return nullptr;
669 }
670
671 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
672                                     SDValue N0, SDValue N1) {
673   EVT VT = N0.getValueType();
674   if (N0.getOpcode() == Opc) {
675     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
676       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
677         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
678         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
679         if (!OpNode.getNode())
680           return SDValue();
681         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
682       }
683       if (N0.hasOneUse()) {
684         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
685         // use
686         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
687         if (!OpNode.getNode())
688           return SDValue();
689         AddToWorkList(OpNode.getNode());
690         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
691       }
692     }
693   }
694
695   if (N1.getOpcode() == Opc) {
696     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
697       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
698         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
699         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
700         if (!OpNode.getNode())
701           return SDValue();
702         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
703       }
704       if (N1.hasOneUse()) {
705         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
706         // use
707         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
708         if (!OpNode.getNode())
709           return SDValue();
710         AddToWorkList(OpNode.getNode());
711         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
712       }
713     }
714   }
715
716   return SDValue();
717 }
718
719 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
720                                bool AddTo) {
721   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
722   ++NodesCombined;
723   DEBUG(dbgs() << "\nReplacing.1 ";
724         N->dump(&DAG);
725         dbgs() << "\nWith: ";
726         To[0].getNode()->dump(&DAG);
727         dbgs() << " and " << NumTo-1 << " other values\n";
728         for (unsigned i = 0, e = NumTo; i != e; ++i)
729           assert((!To[i].getNode() ||
730                   N->getValueType(i) == To[i].getValueType()) &&
731                  "Cannot combine value to value of different type!"));
732   WorkListRemover DeadNodes(*this);
733   DAG.ReplaceAllUsesWith(N, To);
734   if (AddTo) {
735     // Push the new nodes and any users onto the worklist
736     for (unsigned i = 0, e = NumTo; i != e; ++i) {
737       if (To[i].getNode()) {
738         AddToWorkList(To[i].getNode());
739         AddUsersToWorkList(To[i].getNode());
740       }
741     }
742   }
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 (N->use_empty()) {
748     // Nodes can be reintroduced into the worklist.  Make sure we do not
749     // process a node that has been replaced.
750     removeFromWorkList(N);
751
752     // Finally, since the node is now dead, remove it from the graph.
753     DAG.DeleteNode(N);
754   }
755   return SDValue(N, 0);
756 }
757
758 void DAGCombiner::
759 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
760   // Replace all uses.  If any nodes become isomorphic to other nodes and
761   // are deleted, make sure to remove them from our worklist.
762   WorkListRemover DeadNodes(*this);
763   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
764
765   // Push the new node and any (possibly new) users onto the worklist.
766   AddToWorkList(TLO.New.getNode());
767   AddUsersToWorkList(TLO.New.getNode());
768
769   // Finally, if the node is now dead, remove it from the graph.  The node
770   // may not be dead if the replacement process recursively simplified to
771   // something else needing this node.
772   if (TLO.Old.getNode()->use_empty()) {
773     removeFromWorkList(TLO.Old.getNode());
774
775     // If the operands of this node are only used by the node, they will now
776     // be dead.  Make sure to visit them first to delete dead nodes early.
777     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
778       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
779         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
780
781     DAG.DeleteNode(TLO.Old.getNode());
782   }
783 }
784
785 /// SimplifyDemandedBits - Check the specified integer node value to see if
786 /// it can be simplified or if things it uses can be simplified by bit
787 /// propagation.  If so, return true.
788 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
789   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
790   APInt KnownZero, KnownOne;
791   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
792     return false;
793
794   // Revisit the node.
795   AddToWorkList(Op.getNode());
796
797   // Replace the old value with the new one.
798   ++NodesCombined;
799   DEBUG(dbgs() << "\nReplacing.2 ";
800         TLO.Old.getNode()->dump(&DAG);
801         dbgs() << "\nWith: ";
802         TLO.New.getNode()->dump(&DAG);
803         dbgs() << '\n');
804
805   CommitTargetLoweringOpt(TLO);
806   return true;
807 }
808
809 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
810   SDLoc dl(Load);
811   EVT VT = Load->getValueType(0);
812   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
813
814   DEBUG(dbgs() << "\nReplacing.9 ";
815         Load->dump(&DAG);
816         dbgs() << "\nWith: ";
817         Trunc.getNode()->dump(&DAG);
818         dbgs() << '\n');
819   WorkListRemover DeadNodes(*this);
820   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
821   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
822   removeFromWorkList(Load);
823   DAG.DeleteNode(Load);
824   AddToWorkList(Trunc.getNode());
825 }
826
827 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
828   Replace = false;
829   SDLoc dl(Op);
830   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
831     EVT MemVT = LD->getMemoryVT();
832     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
833       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
834                                                   : ISD::EXTLOAD)
835       : LD->getExtensionType();
836     Replace = true;
837     return DAG.getExtLoad(ExtType, dl, PVT,
838                           LD->getChain(), LD->getBasePtr(),
839                           MemVT, LD->getMemOperand());
840   }
841
842   unsigned Opc = Op.getOpcode();
843   switch (Opc) {
844   default: break;
845   case ISD::AssertSext:
846     return DAG.getNode(ISD::AssertSext, dl, PVT,
847                        SExtPromoteOperand(Op.getOperand(0), PVT),
848                        Op.getOperand(1));
849   case ISD::AssertZext:
850     return DAG.getNode(ISD::AssertZext, dl, PVT,
851                        ZExtPromoteOperand(Op.getOperand(0), PVT),
852                        Op.getOperand(1));
853   case ISD::Constant: {
854     unsigned ExtOpc =
855       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
856     return DAG.getNode(ExtOpc, dl, PVT, Op);
857   }
858   }
859
860   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
861     return SDValue();
862   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
863 }
864
865 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
866   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
867     return SDValue();
868   EVT OldVT = Op.getValueType();
869   SDLoc dl(Op);
870   bool Replace = false;
871   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
872   if (NewOp.getNode() == 0)
873     return SDValue();
874   AddToWorkList(NewOp.getNode());
875
876   if (Replace)
877     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
878   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
879                      DAG.getValueType(OldVT));
880 }
881
882 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
883   EVT OldVT = Op.getValueType();
884   SDLoc dl(Op);
885   bool Replace = false;
886   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
887   if (NewOp.getNode() == 0)
888     return SDValue();
889   AddToWorkList(NewOp.getNode());
890
891   if (Replace)
892     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
893   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
894 }
895
896 /// PromoteIntBinOp - Promote the specified integer binary operation if the
897 /// target indicates it is beneficial. e.g. On x86, it's usually better to
898 /// promote i16 operations to i32 since i16 instructions are longer.
899 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
900   if (!LegalOperations)
901     return SDValue();
902
903   EVT VT = Op.getValueType();
904   if (VT.isVector() || !VT.isInteger())
905     return SDValue();
906
907   // If operation type is 'undesirable', e.g. i16 on x86, consider
908   // promoting it.
909   unsigned Opc = Op.getOpcode();
910   if (TLI.isTypeDesirableForOp(Opc, VT))
911     return SDValue();
912
913   EVT PVT = VT;
914   // Consult target whether it is a good idea to promote this operation and
915   // what's the right type to promote it to.
916   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
917     assert(PVT != VT && "Don't know what type to promote to!");
918
919     bool Replace0 = false;
920     SDValue N0 = Op.getOperand(0);
921     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
922     if (NN0.getNode() == 0)
923       return SDValue();
924
925     bool Replace1 = false;
926     SDValue N1 = Op.getOperand(1);
927     SDValue NN1;
928     if (N0 == N1)
929       NN1 = NN0;
930     else {
931       NN1 = PromoteOperand(N1, PVT, Replace1);
932       if (NN1.getNode() == 0)
933         return SDValue();
934     }
935
936     AddToWorkList(NN0.getNode());
937     if (NN1.getNode())
938       AddToWorkList(NN1.getNode());
939
940     if (Replace0)
941       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
942     if (Replace1)
943       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
944
945     DEBUG(dbgs() << "\nPromoting ";
946           Op.getNode()->dump(&DAG));
947     SDLoc dl(Op);
948     return DAG.getNode(ISD::TRUNCATE, dl, VT,
949                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
950   }
951   return SDValue();
952 }
953
954 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
955 /// target indicates it is beneficial. e.g. On x86, it's usually better to
956 /// promote i16 operations to i32 since i16 instructions are longer.
957 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
958   if (!LegalOperations)
959     return SDValue();
960
961   EVT VT = Op.getValueType();
962   if (VT.isVector() || !VT.isInteger())
963     return SDValue();
964
965   // If operation type is 'undesirable', e.g. i16 on x86, consider
966   // promoting it.
967   unsigned Opc = Op.getOpcode();
968   if (TLI.isTypeDesirableForOp(Opc, VT))
969     return SDValue();
970
971   EVT PVT = VT;
972   // Consult target whether it is a good idea to promote this operation and
973   // what's the right type to promote it to.
974   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
975     assert(PVT != VT && "Don't know what type to promote to!");
976
977     bool Replace = false;
978     SDValue N0 = Op.getOperand(0);
979     if (Opc == ISD::SRA)
980       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
981     else if (Opc == ISD::SRL)
982       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
983     else
984       N0 = PromoteOperand(N0, PVT, Replace);
985     if (N0.getNode() == 0)
986       return SDValue();
987
988     AddToWorkList(N0.getNode());
989     if (Replace)
990       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
991
992     DEBUG(dbgs() << "\nPromoting ";
993           Op.getNode()->dump(&DAG));
994     SDLoc dl(Op);
995     return DAG.getNode(ISD::TRUNCATE, dl, VT,
996                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
997   }
998   return SDValue();
999 }
1000
1001 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1002   if (!LegalOperations)
1003     return SDValue();
1004
1005   EVT VT = Op.getValueType();
1006   if (VT.isVector() || !VT.isInteger())
1007     return SDValue();
1008
1009   // If operation type is 'undesirable', e.g. i16 on x86, consider
1010   // promoting it.
1011   unsigned Opc = Op.getOpcode();
1012   if (TLI.isTypeDesirableForOp(Opc, VT))
1013     return SDValue();
1014
1015   EVT PVT = VT;
1016   // Consult target whether it is a good idea to promote this operation and
1017   // what's the right type to promote it to.
1018   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1019     assert(PVT != VT && "Don't know what type to promote to!");
1020     // fold (aext (aext x)) -> (aext x)
1021     // fold (aext (zext x)) -> (zext x)
1022     // fold (aext (sext x)) -> (sext x)
1023     DEBUG(dbgs() << "\nPromoting ";
1024           Op.getNode()->dump(&DAG));
1025     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1026   }
1027   return SDValue();
1028 }
1029
1030 bool DAGCombiner::PromoteLoad(SDValue Op) {
1031   if (!LegalOperations)
1032     return false;
1033
1034   EVT VT = Op.getValueType();
1035   if (VT.isVector() || !VT.isInteger())
1036     return false;
1037
1038   // If operation type is 'undesirable', e.g. i16 on x86, consider
1039   // promoting it.
1040   unsigned Opc = Op.getOpcode();
1041   if (TLI.isTypeDesirableForOp(Opc, VT))
1042     return false;
1043
1044   EVT PVT = VT;
1045   // Consult target whether it is a good idea to promote this operation and
1046   // what's the right type to promote it to.
1047   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1048     assert(PVT != VT && "Don't know what type to promote to!");
1049
1050     SDLoc dl(Op);
1051     SDNode *N = Op.getNode();
1052     LoadSDNode *LD = cast<LoadSDNode>(N);
1053     EVT MemVT = LD->getMemoryVT();
1054     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1055       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1056                                                   : ISD::EXTLOAD)
1057       : LD->getExtensionType();
1058     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1059                                    LD->getChain(), LD->getBasePtr(),
1060                                    MemVT, LD->getMemOperand());
1061     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1062
1063     DEBUG(dbgs() << "\nPromoting ";
1064           N->dump(&DAG);
1065           dbgs() << "\nTo: ";
1066           Result.getNode()->dump(&DAG);
1067           dbgs() << '\n');
1068     WorkListRemover DeadNodes(*this);
1069     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1070     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1071     removeFromWorkList(N);
1072     DAG.DeleteNode(N);
1073     AddToWorkList(Result.getNode());
1074     return true;
1075   }
1076   return false;
1077 }
1078
1079
1080 //===----------------------------------------------------------------------===//
1081 //  Main DAG Combiner implementation
1082 //===----------------------------------------------------------------------===//
1083
1084 void DAGCombiner::Run(CombineLevel AtLevel) {
1085   // set the instance variables, so that the various visit routines may use it.
1086   Level = AtLevel;
1087   LegalOperations = Level >= AfterLegalizeVectorOps;
1088   LegalTypes = Level >= AfterLegalizeTypes;
1089
1090   // Add all the dag nodes to the worklist.
1091   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1092        E = DAG.allnodes_end(); I != E; ++I)
1093     AddToWorkList(I);
1094
1095   // Create a dummy node (which is not added to allnodes), that adds a reference
1096   // to the root node, preventing it from being deleted, and tracking any
1097   // changes of the root.
1098   HandleSDNode Dummy(DAG.getRoot());
1099
1100   // The root of the dag may dangle to deleted nodes until the dag combiner is
1101   // done.  Set it to null to avoid confusion.
1102   DAG.setRoot(SDValue());
1103
1104   // while the worklist isn't empty, find a node and
1105   // try and combine it.
1106   while (!WorkListContents.empty()) {
1107     SDNode *N;
1108     // The WorkListOrder holds the SDNodes in order, but it may contain
1109     // duplicates.
1110     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1111     // worklist *should* contain, and check the node we want to visit is should
1112     // actually be visited.
1113     do {
1114       N = WorkListOrder.pop_back_val();
1115     } while (!WorkListContents.erase(N));
1116
1117     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1118     // N is deleted from the DAG, since they too may now be dead or may have a
1119     // reduced number of uses, allowing other xforms.
1120     if (N->use_empty() && N != &Dummy) {
1121       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1122         AddToWorkList(N->getOperand(i).getNode());
1123
1124       DAG.DeleteNode(N);
1125       continue;
1126     }
1127
1128     SDValue RV = combine(N);
1129
1130     if (RV.getNode() == 0)
1131       continue;
1132
1133     ++NodesCombined;
1134
1135     // If we get back the same node we passed in, rather than a new node or
1136     // zero, we know that the node must have defined multiple values and
1137     // CombineTo was used.  Since CombineTo takes care of the worklist
1138     // mechanics for us, we have no work to do in this case.
1139     if (RV.getNode() == N)
1140       continue;
1141
1142     assert(N->getOpcode() != ISD::DELETED_NODE &&
1143            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1144            "Node was deleted but visit returned new node!");
1145
1146     DEBUG(dbgs() << "\nReplacing.3 ";
1147           N->dump(&DAG);
1148           dbgs() << "\nWith: ";
1149           RV.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151
1152     // Transfer debug value.
1153     DAG.TransferDbgValues(SDValue(N, 0), RV);
1154     WorkListRemover DeadNodes(*this);
1155     if (N->getNumValues() == RV.getNode()->getNumValues())
1156       DAG.ReplaceAllUsesWith(N, RV.getNode());
1157     else {
1158       assert(N->getValueType(0) == RV.getValueType() &&
1159              N->getNumValues() == 1 && "Type mismatch");
1160       SDValue OpV = RV;
1161       DAG.ReplaceAllUsesWith(N, &OpV);
1162     }
1163
1164     // Push the new node and any users onto the worklist
1165     AddToWorkList(RV.getNode());
1166     AddUsersToWorkList(RV.getNode());
1167
1168     // Add any uses of the old node to the worklist in case this node is the
1169     // last one that uses them.  They may become dead after this node is
1170     // deleted.
1171     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1172       AddToWorkList(N->getOperand(i).getNode());
1173
1174     // Finally, if the node is now dead, remove it from the graph.  The node
1175     // may not be dead if the replacement process recursively simplified to
1176     // something else needing this node.
1177     if (N->use_empty()) {
1178       // Nodes can be reintroduced into the worklist.  Make sure we do not
1179       // process a node that has been replaced.
1180       removeFromWorkList(N);
1181
1182       // Finally, since the node is now dead, remove it from the graph.
1183       DAG.DeleteNode(N);
1184     }
1185   }
1186
1187   // If the root changed (e.g. it was a dead load, update the root).
1188   DAG.setRoot(Dummy.getValue());
1189   DAG.RemoveDeadNodes();
1190 }
1191
1192 SDValue DAGCombiner::visit(SDNode *N) {
1193   switch (N->getOpcode()) {
1194   default: break;
1195   case ISD::TokenFactor:        return visitTokenFactor(N);
1196   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1197   case ISD::ADD:                return visitADD(N);
1198   case ISD::SUB:                return visitSUB(N);
1199   case ISD::ADDC:               return visitADDC(N);
1200   case ISD::SUBC:               return visitSUBC(N);
1201   case ISD::ADDE:               return visitADDE(N);
1202   case ISD::SUBE:               return visitSUBE(N);
1203   case ISD::MUL:                return visitMUL(N);
1204   case ISD::SDIV:               return visitSDIV(N);
1205   case ISD::UDIV:               return visitUDIV(N);
1206   case ISD::SREM:               return visitSREM(N);
1207   case ISD::UREM:               return visitUREM(N);
1208   case ISD::MULHU:              return visitMULHU(N);
1209   case ISD::MULHS:              return visitMULHS(N);
1210   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1211   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1212   case ISD::SMULO:              return visitSMULO(N);
1213   case ISD::UMULO:              return visitUMULO(N);
1214   case ISD::SDIVREM:            return visitSDIVREM(N);
1215   case ISD::UDIVREM:            return visitUDIVREM(N);
1216   case ISD::AND:                return visitAND(N);
1217   case ISD::OR:                 return visitOR(N);
1218   case ISD::XOR:                return visitXOR(N);
1219   case ISD::SHL:                return visitSHL(N);
1220   case ISD::SRA:                return visitSRA(N);
1221   case ISD::SRL:                return visitSRL(N);
1222   case ISD::ROTR:
1223   case ISD::ROTL:               return visitRotate(N);
1224   case ISD::CTLZ:               return visitCTLZ(N);
1225   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1226   case ISD::CTTZ:               return visitCTTZ(N);
1227   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1228   case ISD::CTPOP:              return visitCTPOP(N);
1229   case ISD::SELECT:             return visitSELECT(N);
1230   case ISD::VSELECT:            return visitVSELECT(N);
1231   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1232   case ISD::SETCC:              return visitSETCC(N);
1233   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1234   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1235   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1236   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1237   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1238   case ISD::BITCAST:            return visitBITCAST(N);
1239   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1240   case ISD::FADD:               return visitFADD(N);
1241   case ISD::FSUB:               return visitFSUB(N);
1242   case ISD::FMUL:               return visitFMUL(N);
1243   case ISD::FMA:                return visitFMA(N);
1244   case ISD::FDIV:               return visitFDIV(N);
1245   case ISD::FREM:               return visitFREM(N);
1246   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1247   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1248   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1249   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1250   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1251   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1252   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1253   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1254   case ISD::FNEG:               return visitFNEG(N);
1255   case ISD::FABS:               return visitFABS(N);
1256   case ISD::FFLOOR:             return visitFFLOOR(N);
1257   case ISD::FCEIL:              return visitFCEIL(N);
1258   case ISD::FTRUNC:             return visitFTRUNC(N);
1259   case ISD::BRCOND:             return visitBRCOND(N);
1260   case ISD::BR_CC:              return visitBR_CC(N);
1261   case ISD::LOAD:               return visitLOAD(N);
1262   case ISD::STORE:              return visitSTORE(N);
1263   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1264   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1265   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1266   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1267   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1268   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1269   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1270   }
1271   return SDValue();
1272 }
1273
1274 SDValue DAGCombiner::combine(SDNode *N) {
1275   SDValue RV = visit(N);
1276
1277   // If nothing happened, try a target-specific DAG combine.
1278   if (RV.getNode() == 0) {
1279     assert(N->getOpcode() != ISD::DELETED_NODE &&
1280            "Node was deleted but visit returned NULL!");
1281
1282     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1283         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1284
1285       // Expose the DAG combiner to the target combiner impls.
1286       TargetLowering::DAGCombinerInfo
1287         DagCombineInfo(DAG, Level, false, this);
1288
1289       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1290     }
1291   }
1292
1293   // If nothing happened still, try promoting the operation.
1294   if (RV.getNode() == 0) {
1295     switch (N->getOpcode()) {
1296     default: break;
1297     case ISD::ADD:
1298     case ISD::SUB:
1299     case ISD::MUL:
1300     case ISD::AND:
1301     case ISD::OR:
1302     case ISD::XOR:
1303       RV = PromoteIntBinOp(SDValue(N, 0));
1304       break;
1305     case ISD::SHL:
1306     case ISD::SRA:
1307     case ISD::SRL:
1308       RV = PromoteIntShiftOp(SDValue(N, 0));
1309       break;
1310     case ISD::SIGN_EXTEND:
1311     case ISD::ZERO_EXTEND:
1312     case ISD::ANY_EXTEND:
1313       RV = PromoteExtend(SDValue(N, 0));
1314       break;
1315     case ISD::LOAD:
1316       if (PromoteLoad(SDValue(N, 0)))
1317         RV = SDValue(N, 0);
1318       break;
1319     }
1320   }
1321
1322   // If N is a commutative binary node, try commuting it to enable more
1323   // sdisel CSE.
1324   if (RV.getNode() == 0 &&
1325       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1326       N->getNumValues() == 1) {
1327     SDValue N0 = N->getOperand(0);
1328     SDValue N1 = N->getOperand(1);
1329
1330     // Constant operands are canonicalized to RHS.
1331     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1332       SDValue Ops[] = { N1, N0 };
1333       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1334                                             Ops, 2);
1335       if (CSENode)
1336         return SDValue(CSENode, 0);
1337     }
1338   }
1339
1340   return RV;
1341 }
1342
1343 /// getInputChainForNode - Given a node, return its input chain if it has one,
1344 /// otherwise return a null sd operand.
1345 static SDValue getInputChainForNode(SDNode *N) {
1346   if (unsigned NumOps = N->getNumOperands()) {
1347     if (N->getOperand(0).getValueType() == MVT::Other)
1348       return N->getOperand(0);
1349     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1350       return N->getOperand(NumOps-1);
1351     for (unsigned i = 1; i < NumOps-1; ++i)
1352       if (N->getOperand(i).getValueType() == MVT::Other)
1353         return N->getOperand(i);
1354   }
1355   return SDValue();
1356 }
1357
1358 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1359   // If N has two operands, where one has an input chain equal to the other,
1360   // the 'other' chain is redundant.
1361   if (N->getNumOperands() == 2) {
1362     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1363       return N->getOperand(0);
1364     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1365       return N->getOperand(1);
1366   }
1367
1368   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1369   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1370   SmallPtrSet<SDNode*, 16> SeenOps;
1371   bool Changed = false;             // If we should replace this token factor.
1372
1373   // Start out with this token factor.
1374   TFs.push_back(N);
1375
1376   // Iterate through token factors.  The TFs grows when new token factors are
1377   // encountered.
1378   for (unsigned i = 0; i < TFs.size(); ++i) {
1379     SDNode *TF = TFs[i];
1380
1381     // Check each of the operands.
1382     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1383       SDValue Op = TF->getOperand(i);
1384
1385       switch (Op.getOpcode()) {
1386       case ISD::EntryToken:
1387         // Entry tokens don't need to be added to the list. They are
1388         // rededundant.
1389         Changed = true;
1390         break;
1391
1392       case ISD::TokenFactor:
1393         if (Op.hasOneUse() &&
1394             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1395           // Queue up for processing.
1396           TFs.push_back(Op.getNode());
1397           // Clean up in case the token factor is removed.
1398           AddToWorkList(Op.getNode());
1399           Changed = true;
1400           break;
1401         }
1402         // Fall thru
1403
1404       default:
1405         // Only add if it isn't already in the list.
1406         if (SeenOps.insert(Op.getNode()))
1407           Ops.push_back(Op);
1408         else
1409           Changed = true;
1410         break;
1411       }
1412     }
1413   }
1414
1415   SDValue Result;
1416
1417   // If we've change things around then replace token factor.
1418   if (Changed) {
1419     if (Ops.empty()) {
1420       // The entry token is the only possible outcome.
1421       Result = DAG.getEntryNode();
1422     } else {
1423       // New and improved token factor.
1424       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1425                            MVT::Other, &Ops[0], Ops.size());
1426     }
1427
1428     // Don't add users to work list.
1429     return CombineTo(N, Result, false);
1430   }
1431
1432   return Result;
1433 }
1434
1435 /// MERGE_VALUES can always be eliminated.
1436 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1437   WorkListRemover DeadNodes(*this);
1438   // Replacing results may cause a different MERGE_VALUES to suddenly
1439   // be CSE'd with N, and carry its uses with it. Iterate until no
1440   // uses remain, to ensure that the node can be safely deleted.
1441   // First add the users of this node to the work list so that they
1442   // can be tried again once they have new operands.
1443   AddUsersToWorkList(N);
1444   do {
1445     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1446       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1447   } while (!N->use_empty());
1448   removeFromWorkList(N);
1449   DAG.DeleteNode(N);
1450   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1451 }
1452
1453 static
1454 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1455                               SelectionDAG &DAG) {
1456   EVT VT = N0.getValueType();
1457   SDValue N00 = N0.getOperand(0);
1458   SDValue N01 = N0.getOperand(1);
1459   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1460
1461   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1462       isa<ConstantSDNode>(N00.getOperand(1))) {
1463     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1464     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1465                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1466                                  N00.getOperand(0), N01),
1467                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1468                                  N00.getOperand(1), N01));
1469     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1470   }
1471
1472   return SDValue();
1473 }
1474
1475 SDValue DAGCombiner::visitADD(SDNode *N) {
1476   SDValue N0 = N->getOperand(0);
1477   SDValue N1 = N->getOperand(1);
1478   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1479   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1480   EVT VT = N0.getValueType();
1481
1482   // fold vector ops
1483   if (VT.isVector()) {
1484     SDValue FoldedVOp = SimplifyVBinOp(N);
1485     if (FoldedVOp.getNode()) return FoldedVOp;
1486
1487     // fold (add x, 0) -> x, vector edition
1488     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1489       return N0;
1490     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1491       return N1;
1492   }
1493
1494   // fold (add x, undef) -> undef
1495   if (N0.getOpcode() == ISD::UNDEF)
1496     return N0;
1497   if (N1.getOpcode() == ISD::UNDEF)
1498     return N1;
1499   // fold (add c1, c2) -> c1+c2
1500   if (N0C && N1C)
1501     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1502   // canonicalize constant to RHS
1503   if (N0C && !N1C)
1504     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1505   // fold (add x, 0) -> x
1506   if (N1C && N1C->isNullValue())
1507     return N0;
1508   // fold (add Sym, c) -> Sym+c
1509   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1510     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1511         GA->getOpcode() == ISD::GlobalAddress)
1512       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1513                                   GA->getOffset() +
1514                                     (uint64_t)N1C->getSExtValue());
1515   // fold ((c1-A)+c2) -> (c1+c2)-A
1516   if (N1C && N0.getOpcode() == ISD::SUB)
1517     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1518       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1519                          DAG.getConstant(N1C->getAPIntValue()+
1520                                          N0C->getAPIntValue(), VT),
1521                          N0.getOperand(1));
1522   // reassociate add
1523   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1524   if (RADD.getNode() != 0)
1525     return RADD;
1526   // fold ((0-A) + B) -> B-A
1527   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1528       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1529     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1530   // fold (A + (0-B)) -> A-B
1531   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1532       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1533     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1534   // fold (A+(B-A)) -> B
1535   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1536     return N1.getOperand(0);
1537   // fold ((B-A)+A) -> B
1538   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1539     return N0.getOperand(0);
1540   // fold (A+(B-(A+C))) to (B-C)
1541   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1542       N0 == N1.getOperand(1).getOperand(0))
1543     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1544                        N1.getOperand(1).getOperand(1));
1545   // fold (A+(B-(C+A))) to (B-C)
1546   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1547       N0 == N1.getOperand(1).getOperand(1))
1548     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1549                        N1.getOperand(1).getOperand(0));
1550   // fold (A+((B-A)+or-C)) to (B+or-C)
1551   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1552       N1.getOperand(0).getOpcode() == ISD::SUB &&
1553       N0 == N1.getOperand(0).getOperand(1))
1554     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1555                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1556
1557   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1558   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1559     SDValue N00 = N0.getOperand(0);
1560     SDValue N01 = N0.getOperand(1);
1561     SDValue N10 = N1.getOperand(0);
1562     SDValue N11 = N1.getOperand(1);
1563
1564     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1565       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1566                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1567                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1568   }
1569
1570   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1571     return SDValue(N, 0);
1572
1573   // fold (a+b) -> (a|b) iff a and b share no bits.
1574   if (VT.isInteger() && !VT.isVector()) {
1575     APInt LHSZero, LHSOne;
1576     APInt RHSZero, RHSOne;
1577     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1578
1579     if (LHSZero.getBoolValue()) {
1580       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1581
1582       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1583       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1584       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1585         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1586           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1587       }
1588     }
1589   }
1590
1591   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1592   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1593     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1594     if (Result.getNode()) return Result;
1595   }
1596   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1597     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1598     if (Result.getNode()) return Result;
1599   }
1600
1601   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1602   if (N1.getOpcode() == ISD::SHL &&
1603       N1.getOperand(0).getOpcode() == ISD::SUB)
1604     if (ConstantSDNode *C =
1605           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1606       if (C->getAPIntValue() == 0)
1607         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1608                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1609                                        N1.getOperand(0).getOperand(1),
1610                                        N1.getOperand(1)));
1611   if (N0.getOpcode() == ISD::SHL &&
1612       N0.getOperand(0).getOpcode() == ISD::SUB)
1613     if (ConstantSDNode *C =
1614           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1615       if (C->getAPIntValue() == 0)
1616         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1617                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1618                                        N0.getOperand(0).getOperand(1),
1619                                        N0.getOperand(1)));
1620
1621   if (N1.getOpcode() == ISD::AND) {
1622     SDValue AndOp0 = N1.getOperand(0);
1623     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1624     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1625     unsigned DestBits = VT.getScalarType().getSizeInBits();
1626
1627     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1628     // and similar xforms where the inner op is either ~0 or 0.
1629     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1630       SDLoc DL(N);
1631       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1632     }
1633   }
1634
1635   // add (sext i1), X -> sub X, (zext i1)
1636   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1637       N0.getOperand(0).getValueType() == MVT::i1 &&
1638       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1639     SDLoc DL(N);
1640     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1641     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1642   }
1643
1644   return SDValue();
1645 }
1646
1647 SDValue DAGCombiner::visitADDC(SDNode *N) {
1648   SDValue N0 = N->getOperand(0);
1649   SDValue N1 = N->getOperand(1);
1650   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1651   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1652   EVT VT = N0.getValueType();
1653
1654   // If the flag result is dead, turn this into an ADD.
1655   if (!N->hasAnyUseOfValue(1))
1656     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1657                      DAG.getNode(ISD::CARRY_FALSE,
1658                                  SDLoc(N), MVT::Glue));
1659
1660   // canonicalize constant to RHS.
1661   if (N0C && !N1C)
1662     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1663
1664   // fold (addc x, 0) -> x + no carry out
1665   if (N1C && N1C->isNullValue())
1666     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1667                                         SDLoc(N), MVT::Glue));
1668
1669   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1670   APInt LHSZero, LHSOne;
1671   APInt RHSZero, RHSOne;
1672   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1673
1674   if (LHSZero.getBoolValue()) {
1675     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1676
1677     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1678     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1679     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1680       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1681                        DAG.getNode(ISD::CARRY_FALSE,
1682                                    SDLoc(N), MVT::Glue));
1683   }
1684
1685   return SDValue();
1686 }
1687
1688 SDValue DAGCombiner::visitADDE(SDNode *N) {
1689   SDValue N0 = N->getOperand(0);
1690   SDValue N1 = N->getOperand(1);
1691   SDValue CarryIn = N->getOperand(2);
1692   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1693   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1694
1695   // canonicalize constant to RHS
1696   if (N0C && !N1C)
1697     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1698                        N1, N0, CarryIn);
1699
1700   // fold (adde x, y, false) -> (addc x, y)
1701   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1702     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1703
1704   return SDValue();
1705 }
1706
1707 // Since it may not be valid to emit a fold to zero for vector initializers
1708 // check if we can before folding.
1709 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1710                              SelectionDAG &DAG,
1711                              bool LegalOperations, bool LegalTypes) {
1712   if (!VT.isVector())
1713     return DAG.getConstant(0, VT);
1714   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1715     return DAG.getConstant(0, VT);
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitSUB(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1724   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1725     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1726   EVT VT = N0.getValueType();
1727
1728   // fold vector ops
1729   if (VT.isVector()) {
1730     SDValue FoldedVOp = SimplifyVBinOp(N);
1731     if (FoldedVOp.getNode()) return FoldedVOp;
1732
1733     // fold (sub x, 0) -> x, vector edition
1734     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1735       return N0;
1736   }
1737
1738   // fold (sub x, x) -> 0
1739   // FIXME: Refactor this and xor and other similar operations together.
1740   if (N0 == N1)
1741     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1742   // fold (sub c1, c2) -> c1-c2
1743   if (N0C && N1C)
1744     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1745   // fold (sub x, c) -> (add x, -c)
1746   if (N1C)
1747     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1748                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1749   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1750   if (N0C && N0C->isAllOnesValue())
1751     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1752   // fold A-(A-B) -> B
1753   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1754     return N1.getOperand(1);
1755   // fold (A+B)-A -> B
1756   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1757     return N0.getOperand(1);
1758   // fold (A+B)-B -> A
1759   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1760     return N0.getOperand(0);
1761   // fold C2-(A+C1) -> (C2-C1)-A
1762   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1763     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1764                                    VT);
1765     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1766                        N1.getOperand(0));
1767   }
1768   // fold ((A+(B+or-C))-B) -> A+or-C
1769   if (N0.getOpcode() == ISD::ADD &&
1770       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1771        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1772       N0.getOperand(1).getOperand(0) == N1)
1773     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1774                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1775   // fold ((A+(C+B))-B) -> A+C
1776   if (N0.getOpcode() == ISD::ADD &&
1777       N0.getOperand(1).getOpcode() == ISD::ADD &&
1778       N0.getOperand(1).getOperand(1) == N1)
1779     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1780                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1781   // fold ((A-(B-C))-C) -> A-B
1782   if (N0.getOpcode() == ISD::SUB &&
1783       N0.getOperand(1).getOpcode() == ISD::SUB &&
1784       N0.getOperand(1).getOperand(1) == N1)
1785     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1786                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1787
1788   // If either operand of a sub is undef, the result is undef
1789   if (N0.getOpcode() == ISD::UNDEF)
1790     return N0;
1791   if (N1.getOpcode() == ISD::UNDEF)
1792     return N1;
1793
1794   // If the relocation model supports it, consider symbol offsets.
1795   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1796     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1797       // fold (sub Sym, c) -> Sym-c
1798       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1799         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1800                                     GA->getOffset() -
1801                                       (uint64_t)N1C->getSExtValue());
1802       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1803       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1804         if (GA->getGlobal() == GB->getGlobal())
1805           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1806                                  VT);
1807     }
1808
1809   return SDValue();
1810 }
1811
1812 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1813   SDValue N0 = N->getOperand(0);
1814   SDValue N1 = N->getOperand(1);
1815   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1816   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1817   EVT VT = N0.getValueType();
1818
1819   // If the flag result is dead, turn this into an SUB.
1820   if (!N->hasAnyUseOfValue(1))
1821     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1822                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1823                                  MVT::Glue));
1824
1825   // fold (subc x, x) -> 0 + no borrow
1826   if (N0 == N1)
1827     return CombineTo(N, DAG.getConstant(0, VT),
1828                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1829                                  MVT::Glue));
1830
1831   // fold (subc x, 0) -> x + no borrow
1832   if (N1C && N1C->isNullValue())
1833     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1834                                         MVT::Glue));
1835
1836   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1837   if (N0C && N0C->isAllOnesValue())
1838     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1839                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1840                                  MVT::Glue));
1841
1842   return SDValue();
1843 }
1844
1845 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1846   SDValue N0 = N->getOperand(0);
1847   SDValue N1 = N->getOperand(1);
1848   SDValue CarryIn = N->getOperand(2);
1849
1850   // fold (sube x, y, false) -> (subc x, y)
1851   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1852     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1853
1854   return SDValue();
1855 }
1856
1857 SDValue DAGCombiner::visitMUL(SDNode *N) {
1858   SDValue N0 = N->getOperand(0);
1859   SDValue N1 = N->getOperand(1);
1860   EVT VT = N0.getValueType();
1861
1862   // fold (mul x, undef) -> 0
1863   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1864     return DAG.getConstant(0, VT);
1865
1866   bool N0IsConst = false;
1867   bool N1IsConst = false;
1868   APInt ConstValue0, ConstValue1;
1869   // fold vector ops
1870   if (VT.isVector()) {
1871     SDValue FoldedVOp = SimplifyVBinOp(N);
1872     if (FoldedVOp.getNode()) return FoldedVOp;
1873
1874     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1875     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1876   } else {
1877     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1878     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1879                             : APInt();
1880     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1881     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1882                             : APInt();
1883   }
1884
1885   // fold (mul c1, c2) -> c1*c2
1886   if (N0IsConst && N1IsConst)
1887     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1888
1889   // canonicalize constant to RHS
1890   if (N0IsConst && !N1IsConst)
1891     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1892   // fold (mul x, 0) -> 0
1893   if (N1IsConst && ConstValue1 == 0)
1894     return N1;
1895   // We require a splat of the entire scalar bit width for non-contiguous
1896   // bit patterns.
1897   bool IsFullSplat =
1898     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1899   // fold (mul x, 1) -> x
1900   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1901     return N0;
1902   // fold (mul x, -1) -> 0-x
1903   if (N1IsConst && ConstValue1.isAllOnesValue())
1904     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1905                        DAG.getConstant(0, VT), N0);
1906   // fold (mul x, (1 << c)) -> x << c
1907   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1908     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1909                        DAG.getConstant(ConstValue1.logBase2(),
1910                                        getShiftAmountTy(N0.getValueType())));
1911   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1912   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1913     unsigned Log2Val = (-ConstValue1).logBase2();
1914     // FIXME: If the input is something that is easily negated (e.g. a
1915     // single-use add), we should put the negate there.
1916     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1917                        DAG.getConstant(0, VT),
1918                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1919                             DAG.getConstant(Log2Val,
1920                                       getShiftAmountTy(N0.getValueType()))));
1921   }
1922
1923   APInt Val;
1924   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1925   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1926       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1927                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1928     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1929                              N1, N0.getOperand(1));
1930     AddToWorkList(C3.getNode());
1931     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1932                        N0.getOperand(0), C3);
1933   }
1934
1935   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1936   // use.
1937   {
1938     SDValue Sh(0,0), Y(0,0);
1939     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1940     if (N0.getOpcode() == ISD::SHL &&
1941         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1942                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1943         N0.getNode()->hasOneUse()) {
1944       Sh = N0; Y = N1;
1945     } else if (N1.getOpcode() == ISD::SHL &&
1946                isa<ConstantSDNode>(N1.getOperand(1)) &&
1947                N1.getNode()->hasOneUse()) {
1948       Sh = N1; Y = N0;
1949     }
1950
1951     if (Sh.getNode()) {
1952       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1953                                 Sh.getOperand(0), Y);
1954       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1955                          Mul, Sh.getOperand(1));
1956     }
1957   }
1958
1959   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1960   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1961       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1962                      isa<ConstantSDNode>(N0.getOperand(1))))
1963     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1964                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1965                                    N0.getOperand(0), N1),
1966                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1967                                    N0.getOperand(1), N1));
1968
1969   // reassociate mul
1970   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1971   if (RMUL.getNode() != 0)
1972     return RMUL;
1973
1974   return SDValue();
1975 }
1976
1977 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1978   SDValue N0 = N->getOperand(0);
1979   SDValue N1 = N->getOperand(1);
1980   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1981   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1982   EVT VT = N->getValueType(0);
1983
1984   // fold vector ops
1985   if (VT.isVector()) {
1986     SDValue FoldedVOp = SimplifyVBinOp(N);
1987     if (FoldedVOp.getNode()) return FoldedVOp;
1988   }
1989
1990   // fold (sdiv c1, c2) -> c1/c2
1991   if (N0C && N1C && !N1C->isNullValue())
1992     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1993   // fold (sdiv X, 1) -> X
1994   if (N1C && N1C->getAPIntValue() == 1LL)
1995     return N0;
1996   // fold (sdiv X, -1) -> 0-X
1997   if (N1C && N1C->isAllOnesValue())
1998     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1999                        DAG.getConstant(0, VT), N0);
2000   // If we know the sign bits of both operands are zero, strength reduce to a
2001   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2002   if (!VT.isVector()) {
2003     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2004       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2005                          N0, N1);
2006   }
2007   // fold (sdiv X, pow2) -> simple ops after legalize
2008   if (N1C && !N1C->isNullValue() &&
2009       (N1C->getAPIntValue().isPowerOf2() ||
2010        (-N1C->getAPIntValue()).isPowerOf2())) {
2011     // If dividing by powers of two is cheap, then don't perform the following
2012     // fold.
2013     if (TLI.isPow2DivCheap())
2014       return SDValue();
2015
2016     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2017
2018     // Splat the sign bit into the register
2019     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2020                               DAG.getConstant(VT.getSizeInBits()-1,
2021                                        getShiftAmountTy(N0.getValueType())));
2022     AddToWorkList(SGN.getNode());
2023
2024     // Add (N0 < 0) ? abs2 - 1 : 0;
2025     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2026                               DAG.getConstant(VT.getSizeInBits() - lg2,
2027                                        getShiftAmountTy(SGN.getValueType())));
2028     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2029     AddToWorkList(SRL.getNode());
2030     AddToWorkList(ADD.getNode());    // Divide by pow2
2031     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2032                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2033
2034     // If we're dividing by a positive value, we're done.  Otherwise, we must
2035     // negate the result.
2036     if (N1C->getAPIntValue().isNonNegative())
2037       return SRA;
2038
2039     AddToWorkList(SRA.getNode());
2040     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2041                        DAG.getConstant(0, VT), SRA);
2042   }
2043
2044   // if integer divide is expensive and we satisfy the requirements, emit an
2045   // alternate sequence.
2046   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2047     SDValue Op = BuildSDIV(N);
2048     if (Op.getNode()) return Op;
2049   }
2050
2051   // undef / X -> 0
2052   if (N0.getOpcode() == ISD::UNDEF)
2053     return DAG.getConstant(0, VT);
2054   // X / undef -> undef
2055   if (N1.getOpcode() == ISD::UNDEF)
2056     return N1;
2057
2058   return SDValue();
2059 }
2060
2061 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2062   SDValue N0 = N->getOperand(0);
2063   SDValue N1 = N->getOperand(1);
2064   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2065   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2066   EVT VT = N->getValueType(0);
2067
2068   // fold vector ops
2069   if (VT.isVector()) {
2070     SDValue FoldedVOp = SimplifyVBinOp(N);
2071     if (FoldedVOp.getNode()) return FoldedVOp;
2072   }
2073
2074   // fold (udiv c1, c2) -> c1/c2
2075   if (N0C && N1C && !N1C->isNullValue())
2076     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2077   // fold (udiv x, (1 << c)) -> x >>u c
2078   if (N1C && N1C->getAPIntValue().isPowerOf2())
2079     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2080                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2081                                        getShiftAmountTy(N0.getValueType())));
2082   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2083   if (N1.getOpcode() == ISD::SHL) {
2084     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2085       if (SHC->getAPIntValue().isPowerOf2()) {
2086         EVT ADDVT = N1.getOperand(1).getValueType();
2087         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2088                                   N1.getOperand(1),
2089                                   DAG.getConstant(SHC->getAPIntValue()
2090                                                                   .logBase2(),
2091                                                   ADDVT));
2092         AddToWorkList(Add.getNode());
2093         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2094       }
2095     }
2096   }
2097   // fold (udiv x, c) -> alternate
2098   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2099     SDValue Op = BuildUDIV(N);
2100     if (Op.getNode()) return Op;
2101   }
2102
2103   // undef / X -> 0
2104   if (N0.getOpcode() == ISD::UNDEF)
2105     return DAG.getConstant(0, VT);
2106   // X / undef -> undef
2107   if (N1.getOpcode() == ISD::UNDEF)
2108     return N1;
2109
2110   return SDValue();
2111 }
2112
2113 SDValue DAGCombiner::visitSREM(SDNode *N) {
2114   SDValue N0 = N->getOperand(0);
2115   SDValue N1 = N->getOperand(1);
2116   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2117   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2118   EVT VT = N->getValueType(0);
2119
2120   // fold (srem c1, c2) -> c1%c2
2121   if (N0C && N1C && !N1C->isNullValue())
2122     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2123   // If we know the sign bits of both operands are zero, strength reduce to a
2124   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2125   if (!VT.isVector()) {
2126     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2127       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2128   }
2129
2130   // If X/C can be simplified by the division-by-constant logic, lower
2131   // X%C to the equivalent of X-X/C*C.
2132   if (N1C && !N1C->isNullValue()) {
2133     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2134     AddToWorkList(Div.getNode());
2135     SDValue OptimizedDiv = combine(Div.getNode());
2136     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2137       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2138                                 OptimizedDiv, N1);
2139       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2140       AddToWorkList(Mul.getNode());
2141       return Sub;
2142     }
2143   }
2144
2145   // undef % X -> 0
2146   if (N0.getOpcode() == ISD::UNDEF)
2147     return DAG.getConstant(0, VT);
2148   // X % undef -> undef
2149   if (N1.getOpcode() == ISD::UNDEF)
2150     return N1;
2151
2152   return SDValue();
2153 }
2154
2155 SDValue DAGCombiner::visitUREM(SDNode *N) {
2156   SDValue N0 = N->getOperand(0);
2157   SDValue N1 = N->getOperand(1);
2158   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2159   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2160   EVT VT = N->getValueType(0);
2161
2162   // fold (urem c1, c2) -> c1%c2
2163   if (N0C && N1C && !N1C->isNullValue())
2164     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2165   // fold (urem x, pow2) -> (and x, pow2-1)
2166   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2167     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2168                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2169   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2170   if (N1.getOpcode() == ISD::SHL) {
2171     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2172       if (SHC->getAPIntValue().isPowerOf2()) {
2173         SDValue Add =
2174           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2175                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2176                                  VT));
2177         AddToWorkList(Add.getNode());
2178         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2179       }
2180     }
2181   }
2182
2183   // If X/C can be simplified by the division-by-constant logic, lower
2184   // X%C to the equivalent of X-X/C*C.
2185   if (N1C && !N1C->isNullValue()) {
2186     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2187     AddToWorkList(Div.getNode());
2188     SDValue OptimizedDiv = combine(Div.getNode());
2189     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2190       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2191                                 OptimizedDiv, N1);
2192       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2193       AddToWorkList(Mul.getNode());
2194       return Sub;
2195     }
2196   }
2197
2198   // undef % X -> 0
2199   if (N0.getOpcode() == ISD::UNDEF)
2200     return DAG.getConstant(0, VT);
2201   // X % undef -> undef
2202   if (N1.getOpcode() == ISD::UNDEF)
2203     return N1;
2204
2205   return SDValue();
2206 }
2207
2208 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2209   SDValue N0 = N->getOperand(0);
2210   SDValue N1 = N->getOperand(1);
2211   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2212   EVT VT = N->getValueType(0);
2213   SDLoc DL(N);
2214
2215   // fold (mulhs x, 0) -> 0
2216   if (N1C && N1C->isNullValue())
2217     return N1;
2218   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2219   if (N1C && N1C->getAPIntValue() == 1)
2220     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2221                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2222                                        getShiftAmountTy(N0.getValueType())));
2223   // fold (mulhs x, undef) -> 0
2224   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2225     return DAG.getConstant(0, VT);
2226
2227   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2228   // plus a shift.
2229   if (VT.isSimple() && !VT.isVector()) {
2230     MVT Simple = VT.getSimpleVT();
2231     unsigned SimpleSize = Simple.getSizeInBits();
2232     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2233     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2234       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2235       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2236       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2237       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2238             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2239       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2240     }
2241   }
2242
2243   return SDValue();
2244 }
2245
2246 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2247   SDValue N0 = N->getOperand(0);
2248   SDValue N1 = N->getOperand(1);
2249   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2250   EVT VT = N->getValueType(0);
2251   SDLoc DL(N);
2252
2253   // fold (mulhu x, 0) -> 0
2254   if (N1C && N1C->isNullValue())
2255     return N1;
2256   // fold (mulhu x, 1) -> 0
2257   if (N1C && N1C->getAPIntValue() == 1)
2258     return DAG.getConstant(0, N0.getValueType());
2259   // fold (mulhu x, undef) -> 0
2260   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2261     return DAG.getConstant(0, VT);
2262
2263   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2264   // plus a shift.
2265   if (VT.isSimple() && !VT.isVector()) {
2266     MVT Simple = VT.getSimpleVT();
2267     unsigned SimpleSize = Simple.getSizeInBits();
2268     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2269     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2270       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2271       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2272       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2273       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2274             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2275       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2276     }
2277   }
2278
2279   return SDValue();
2280 }
2281
2282 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2283 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2284 /// that are being performed. Return true if a simplification was made.
2285 ///
2286 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2287                                                 unsigned HiOp) {
2288   // If the high half is not needed, just compute the low half.
2289   bool HiExists = N->hasAnyUseOfValue(1);
2290   if (!HiExists &&
2291       (!LegalOperations ||
2292        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2293     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2294                               N->op_begin(), N->getNumOperands());
2295     return CombineTo(N, Res, Res);
2296   }
2297
2298   // If the low half is not needed, just compute the high half.
2299   bool LoExists = N->hasAnyUseOfValue(0);
2300   if (!LoExists &&
2301       (!LegalOperations ||
2302        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2303     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2304                               N->op_begin(), N->getNumOperands());
2305     return CombineTo(N, Res, Res);
2306   }
2307
2308   // If both halves are used, return as it is.
2309   if (LoExists && HiExists)
2310     return SDValue();
2311
2312   // If the two computed results can be simplified separately, separate them.
2313   if (LoExists) {
2314     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2315                              N->op_begin(), N->getNumOperands());
2316     AddToWorkList(Lo.getNode());
2317     SDValue LoOpt = combine(Lo.getNode());
2318     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2319         (!LegalOperations ||
2320          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2321       return CombineTo(N, LoOpt, LoOpt);
2322   }
2323
2324   if (HiExists) {
2325     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2326                              N->op_begin(), N->getNumOperands());
2327     AddToWorkList(Hi.getNode());
2328     SDValue HiOpt = combine(Hi.getNode());
2329     if (HiOpt.getNode() && HiOpt != Hi &&
2330         (!LegalOperations ||
2331          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2332       return CombineTo(N, HiOpt, HiOpt);
2333   }
2334
2335   return SDValue();
2336 }
2337
2338 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2339   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2340   if (Res.getNode()) return Res;
2341
2342   EVT VT = N->getValueType(0);
2343   SDLoc DL(N);
2344
2345   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2346   // plus a shift.
2347   if (VT.isSimple() && !VT.isVector()) {
2348     MVT Simple = VT.getSimpleVT();
2349     unsigned SimpleSize = Simple.getSizeInBits();
2350     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2351     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2352       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2353       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2354       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2355       // Compute the high part as N1.
2356       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2357             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2358       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2359       // Compute the low part as N0.
2360       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2361       return CombineTo(N, Lo, Hi);
2362     }
2363   }
2364
2365   return SDValue();
2366 }
2367
2368 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2369   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2370   if (Res.getNode()) return Res;
2371
2372   EVT VT = N->getValueType(0);
2373   SDLoc DL(N);
2374
2375   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2376   // plus a shift.
2377   if (VT.isSimple() && !VT.isVector()) {
2378     MVT Simple = VT.getSimpleVT();
2379     unsigned SimpleSize = Simple.getSizeInBits();
2380     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2381     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2382       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2383       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2384       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2385       // Compute the high part as N1.
2386       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2387             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2388       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2389       // Compute the low part as N0.
2390       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2391       return CombineTo(N, Lo, Hi);
2392     }
2393   }
2394
2395   return SDValue();
2396 }
2397
2398 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2399   // (smulo x, 2) -> (saddo x, x)
2400   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2401     if (C2->getAPIntValue() == 2)
2402       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2403                          N->getOperand(0), N->getOperand(0));
2404
2405   return SDValue();
2406 }
2407
2408 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2409   // (umulo x, 2) -> (uaddo x, x)
2410   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2411     if (C2->getAPIntValue() == 2)
2412       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2413                          N->getOperand(0), N->getOperand(0));
2414
2415   return SDValue();
2416 }
2417
2418 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2419   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2420   if (Res.getNode()) return Res;
2421
2422   return SDValue();
2423 }
2424
2425 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2426   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2427   if (Res.getNode()) return Res;
2428
2429   return SDValue();
2430 }
2431
2432 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2433 /// two operands of the same opcode, try to simplify it.
2434 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2435   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2436   EVT VT = N0.getValueType();
2437   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2438
2439   // Bail early if none of these transforms apply.
2440   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2441
2442   // For each of OP in AND/OR/XOR:
2443   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2444   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2445   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2446   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2447   //
2448   // do not sink logical op inside of a vector extend, since it may combine
2449   // into a vsetcc.
2450   EVT Op0VT = N0.getOperand(0).getValueType();
2451   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2452        N0.getOpcode() == ISD::SIGN_EXTEND ||
2453        // Avoid infinite looping with PromoteIntBinOp.
2454        (N0.getOpcode() == ISD::ANY_EXTEND &&
2455         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2456        (N0.getOpcode() == ISD::TRUNCATE &&
2457         (!TLI.isZExtFree(VT, Op0VT) ||
2458          !TLI.isTruncateFree(Op0VT, VT)) &&
2459         TLI.isTypeLegal(Op0VT))) &&
2460       !VT.isVector() &&
2461       Op0VT == N1.getOperand(0).getValueType() &&
2462       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2463     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2464                                  N0.getOperand(0).getValueType(),
2465                                  N0.getOperand(0), N1.getOperand(0));
2466     AddToWorkList(ORNode.getNode());
2467     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2468   }
2469
2470   // For each of OP in SHL/SRL/SRA/AND...
2471   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2472   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2473   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2474   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2475        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2476       N0.getOperand(1) == N1.getOperand(1)) {
2477     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2478                                  N0.getOperand(0).getValueType(),
2479                                  N0.getOperand(0), N1.getOperand(0));
2480     AddToWorkList(ORNode.getNode());
2481     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2482                        ORNode, N0.getOperand(1));
2483   }
2484
2485   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2486   // Only perform this optimization after type legalization and before
2487   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2488   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2489   // we don't want to undo this promotion.
2490   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2491   // on scalars.
2492   if ((N0.getOpcode() == ISD::BITCAST ||
2493        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2494       Level == AfterLegalizeTypes) {
2495     SDValue In0 = N0.getOperand(0);
2496     SDValue In1 = N1.getOperand(0);
2497     EVT In0Ty = In0.getValueType();
2498     EVT In1Ty = In1.getValueType();
2499     SDLoc DL(N);
2500     // If both incoming values are integers, and the original types are the
2501     // same.
2502     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2503       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2504       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2505       AddToWorkList(Op.getNode());
2506       return BC;
2507     }
2508   }
2509
2510   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2511   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2512   // If both shuffles use the same mask, and both shuffle within a single
2513   // vector, then it is worthwhile to move the swizzle after the operation.
2514   // The type-legalizer generates this pattern when loading illegal
2515   // vector types from memory. In many cases this allows additional shuffle
2516   // optimizations.
2517   // There are other cases where moving the shuffle after the xor/and/or
2518   // is profitable even if shuffles don't perform a swizzle.
2519   // If both shuffles use the same mask, and both shuffles have the same first
2520   // or second operand, then it might still be profitable to move the shuffle
2521   // after the xor/and/or operation.
2522   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2523     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2524     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2525
2526     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2527            "Inputs to shuffles are not the same type");
2528  
2529     // Check that both shuffles use the same mask. The masks are known to be of
2530     // the same length because the result vector type is the same.
2531     // Check also that shuffles have only one use to avoid introducing extra
2532     // instructions.
2533     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2534         SVN0->getMask().equals(SVN1->getMask())) {
2535       SDValue ShOp = N0->getOperand(1);
2536
2537       // Don't try to fold this node if it requires introducing a
2538       // build vector of all zeros that might be illegal at this stage.
2539       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2540         if (!LegalTypes)
2541           ShOp = DAG.getConstant(0, VT);
2542         else
2543           ShOp = SDValue();
2544       }
2545
2546       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2547       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2548       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2549       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2550         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2551                                       N0->getOperand(0), N1->getOperand(0));
2552         AddToWorkList(NewNode.getNode());
2553         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2554                                     &SVN0->getMask()[0]);
2555       }
2556
2557       // Don't try to fold this node if it requires introducing a
2558       // build vector of all zeros that might be illegal at this stage.
2559       ShOp = N0->getOperand(0);
2560       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2561         if (!LegalTypes)
2562           ShOp = DAG.getConstant(0, VT);
2563         else
2564           ShOp = SDValue();
2565       }
2566
2567       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2568       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2569       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2570       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2571         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2572                                       N0->getOperand(1), N1->getOperand(1));
2573         AddToWorkList(NewNode.getNode());
2574         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2575                                     &SVN0->getMask()[0]);
2576       }
2577     }
2578   }
2579
2580   return SDValue();
2581 }
2582
2583 SDValue DAGCombiner::visitAND(SDNode *N) {
2584   SDValue N0 = N->getOperand(0);
2585   SDValue N1 = N->getOperand(1);
2586   SDValue LL, LR, RL, RR, CC0, CC1;
2587   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2588   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2589   EVT VT = N1.getValueType();
2590   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2591
2592   // fold vector ops
2593   if (VT.isVector()) {
2594     SDValue FoldedVOp = SimplifyVBinOp(N);
2595     if (FoldedVOp.getNode()) return FoldedVOp;
2596
2597     // fold (and x, 0) -> 0, vector edition
2598     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2599       return N0;
2600     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2601       return N1;
2602
2603     // fold (and x, -1) -> x, vector edition
2604     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2605       return N1;
2606     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2607       return N0;
2608   }
2609
2610   // fold (and x, undef) -> 0
2611   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2612     return DAG.getConstant(0, VT);
2613   // fold (and c1, c2) -> c1&c2
2614   if (N0C && N1C)
2615     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2616   // canonicalize constant to RHS
2617   if (N0C && !N1C)
2618     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2619   // fold (and x, -1) -> x
2620   if (N1C && N1C->isAllOnesValue())
2621     return N0;
2622   // if (and x, c) is known to be zero, return 0
2623   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2624                                    APInt::getAllOnesValue(BitWidth)))
2625     return DAG.getConstant(0, VT);
2626   // reassociate and
2627   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2628   if (RAND.getNode() != 0)
2629     return RAND;
2630   // fold (and (or x, C), D) -> D if (C & D) == D
2631   if (N1C && N0.getOpcode() == ISD::OR)
2632     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2633       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2634         return N1;
2635   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2636   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2637     SDValue N0Op0 = N0.getOperand(0);
2638     APInt Mask = ~N1C->getAPIntValue();
2639     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2640     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2641       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2642                                  N0.getValueType(), N0Op0);
2643
2644       // Replace uses of the AND with uses of the Zero extend node.
2645       CombineTo(N, Zext);
2646
2647       // We actually want to replace all uses of the any_extend with the
2648       // zero_extend, to avoid duplicating things.  This will later cause this
2649       // AND to be folded.
2650       CombineTo(N0.getNode(), Zext);
2651       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2652     }
2653   }
2654   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2655   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2656   // already be zero by virtue of the width of the base type of the load.
2657   //
2658   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2659   // more cases.
2660   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2661        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2662       N0.getOpcode() == ISD::LOAD) {
2663     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2664                                          N0 : N0.getOperand(0) );
2665
2666     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2667     // This can be a pure constant or a vector splat, in which case we treat the
2668     // vector as a scalar and use the splat value.
2669     APInt Constant = APInt::getNullValue(1);
2670     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2671       Constant = C->getAPIntValue();
2672     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2673       APInt SplatValue, SplatUndef;
2674       unsigned SplatBitSize;
2675       bool HasAnyUndefs;
2676       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2677                                              SplatBitSize, HasAnyUndefs);
2678       if (IsSplat) {
2679         // Undef bits can contribute to a possible optimisation if set, so
2680         // set them.
2681         SplatValue |= SplatUndef;
2682
2683         // The splat value may be something like "0x00FFFFFF", which means 0 for
2684         // the first vector value and FF for the rest, repeating. We need a mask
2685         // that will apply equally to all members of the vector, so AND all the
2686         // lanes of the constant together.
2687         EVT VT = Vector->getValueType(0);
2688         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2689
2690         // If the splat value has been compressed to a bitlength lower
2691         // than the size of the vector lane, we need to re-expand it to
2692         // the lane size.
2693         if (BitWidth > SplatBitSize)
2694           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2695                SplatBitSize < BitWidth;
2696                SplatBitSize = SplatBitSize * 2)
2697             SplatValue |= SplatValue.shl(SplatBitSize);
2698
2699         Constant = APInt::getAllOnesValue(BitWidth);
2700         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2701           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2702       }
2703     }
2704
2705     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2706     // actually legal and isn't going to get expanded, else this is a false
2707     // optimisation.
2708     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2709                                                     Load->getMemoryVT());
2710
2711     // Resize the constant to the same size as the original memory access before
2712     // extension. If it is still the AllOnesValue then this AND is completely
2713     // unneeded.
2714     Constant =
2715       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2716
2717     bool B;
2718     switch (Load->getExtensionType()) {
2719     default: B = false; break;
2720     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2721     case ISD::ZEXTLOAD:
2722     case ISD::NON_EXTLOAD: B = true; break;
2723     }
2724
2725     if (B && Constant.isAllOnesValue()) {
2726       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2727       // preserve semantics once we get rid of the AND.
2728       SDValue NewLoad(Load, 0);
2729       if (Load->getExtensionType() == ISD::EXTLOAD) {
2730         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2731                               Load->getValueType(0), SDLoc(Load),
2732                               Load->getChain(), Load->getBasePtr(),
2733                               Load->getOffset(), Load->getMemoryVT(),
2734                               Load->getMemOperand());
2735         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2736         if (Load->getNumValues() == 3) {
2737           // PRE/POST_INC loads have 3 values.
2738           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2739                            NewLoad.getValue(2) };
2740           CombineTo(Load, To, 3, true);
2741         } else {
2742           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2743         }
2744       }
2745
2746       // Fold the AND away, taking care not to fold to the old load node if we
2747       // replaced it.
2748       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2749
2750       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2751     }
2752   }
2753   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2754   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2755     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2756     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2757
2758     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2759         LL.getValueType().isInteger()) {
2760       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2761       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2762         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2763                                      LR.getValueType(), LL, RL);
2764         AddToWorkList(ORNode.getNode());
2765         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2766       }
2767       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2768       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2769         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2770                                       LR.getValueType(), LL, RL);
2771         AddToWorkList(ANDNode.getNode());
2772         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2773       }
2774       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2775       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2776         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2777                                      LR.getValueType(), LL, RL);
2778         AddToWorkList(ORNode.getNode());
2779         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2780       }
2781     }
2782     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2783     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2784         Op0 == Op1 && LL.getValueType().isInteger() &&
2785       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2786                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2787                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2788                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2789       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2790                                     LL, DAG.getConstant(1, LL.getValueType()));
2791       AddToWorkList(ADDNode.getNode());
2792       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2793                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2794     }
2795     // canonicalize equivalent to ll == rl
2796     if (LL == RR && LR == RL) {
2797       Op1 = ISD::getSetCCSwappedOperands(Op1);
2798       std::swap(RL, RR);
2799     }
2800     if (LL == RL && LR == RR) {
2801       bool isInteger = LL.getValueType().isInteger();
2802       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2803       if (Result != ISD::SETCC_INVALID &&
2804           (!LegalOperations ||
2805            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2806             TLI.isOperationLegal(ISD::SETCC,
2807                             getSetCCResultType(N0.getSimpleValueType())))))
2808         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2809                             LL, LR, Result);
2810     }
2811   }
2812
2813   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2814   if (N0.getOpcode() == N1.getOpcode()) {
2815     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2816     if (Tmp.getNode()) return Tmp;
2817   }
2818
2819   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2820   // fold (and (sra)) -> (and (srl)) when possible.
2821   if (!VT.isVector() &&
2822       SimplifyDemandedBits(SDValue(N, 0)))
2823     return SDValue(N, 0);
2824
2825   // fold (zext_inreg (extload x)) -> (zextload x)
2826   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2827     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2828     EVT MemVT = LN0->getMemoryVT();
2829     // If we zero all the possible extended bits, then we can turn this into
2830     // a zextload if we are running before legalize or the operation is legal.
2831     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2832     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2833                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2834         ((!LegalOperations && !LN0->isVolatile()) ||
2835          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2836       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2837                                        LN0->getChain(), LN0->getBasePtr(),
2838                                        MemVT, LN0->getMemOperand());
2839       AddToWorkList(N);
2840       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2841       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2842     }
2843   }
2844   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2845   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2846       N0.hasOneUse()) {
2847     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2848     EVT MemVT = LN0->getMemoryVT();
2849     // If we zero all the possible extended bits, then we can turn this into
2850     // a zextload if we are running before legalize or the operation is legal.
2851     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2852     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2853                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2854         ((!LegalOperations && !LN0->isVolatile()) ||
2855          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2856       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2857                                        LN0->getChain(), LN0->getBasePtr(),
2858                                        MemVT, LN0->getMemOperand());
2859       AddToWorkList(N);
2860       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2861       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2862     }
2863   }
2864
2865   // fold (and (load x), 255) -> (zextload x, i8)
2866   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2867   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2868   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2869               (N0.getOpcode() == ISD::ANY_EXTEND &&
2870                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2871     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2872     LoadSDNode *LN0 = HasAnyExt
2873       ? cast<LoadSDNode>(N0.getOperand(0))
2874       : cast<LoadSDNode>(N0);
2875     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2876         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2877       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2878       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2879         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2880         EVT LoadedVT = LN0->getMemoryVT();
2881
2882         if (ExtVT == LoadedVT &&
2883             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2884           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2885
2886           SDValue NewLoad =
2887             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2888                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2889                            LN0->getMemOperand());
2890           AddToWorkList(N);
2891           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2892           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2893         }
2894
2895         // Do not change the width of a volatile load.
2896         // Do not generate loads of non-round integer types since these can
2897         // be expensive (and would be wrong if the type is not byte sized).
2898         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2899             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2900           EVT PtrType = LN0->getOperand(1).getValueType();
2901
2902           unsigned Alignment = LN0->getAlignment();
2903           SDValue NewPtr = LN0->getBasePtr();
2904
2905           // For big endian targets, we need to add an offset to the pointer
2906           // to load the correct bytes.  For little endian systems, we merely
2907           // need to read fewer bytes from the same pointer.
2908           if (TLI.isBigEndian()) {
2909             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2910             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2911             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2912             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2913                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2914             Alignment = MinAlign(Alignment, PtrOff);
2915           }
2916
2917           AddToWorkList(NewPtr.getNode());
2918
2919           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2920           SDValue Load =
2921             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2922                            LN0->getChain(), NewPtr,
2923                            LN0->getPointerInfo(),
2924                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2925                            Alignment, LN0->getTBAAInfo());
2926           AddToWorkList(N);
2927           CombineTo(LN0, Load, Load.getValue(1));
2928           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2929         }
2930       }
2931     }
2932   }
2933
2934   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2935       VT.getSizeInBits() <= 64) {
2936     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2937       APInt ADDC = ADDI->getAPIntValue();
2938       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2939         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2940         // immediate for an add, but it is legal if its top c2 bits are set,
2941         // transform the ADD so the immediate doesn't need to be materialized
2942         // in a register.
2943         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2944           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2945                                              SRLI->getZExtValue());
2946           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2947             ADDC |= Mask;
2948             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2949               SDValue NewAdd =
2950                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2951                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2952               CombineTo(N0.getNode(), NewAdd);
2953               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2954             }
2955           }
2956         }
2957       }
2958     }
2959   }
2960
2961   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2962   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2963     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2964                                        N0.getOperand(1), false);
2965     if (BSwap.getNode())
2966       return BSwap;
2967   }
2968
2969   return SDValue();
2970 }
2971
2972 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2973 ///
2974 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2975                                         bool DemandHighBits) {
2976   if (!LegalOperations)
2977     return SDValue();
2978
2979   EVT VT = N->getValueType(0);
2980   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2981     return SDValue();
2982   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2983     return SDValue();
2984
2985   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2986   bool LookPassAnd0 = false;
2987   bool LookPassAnd1 = false;
2988   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2989       std::swap(N0, N1);
2990   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2991       std::swap(N0, N1);
2992   if (N0.getOpcode() == ISD::AND) {
2993     if (!N0.getNode()->hasOneUse())
2994       return SDValue();
2995     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2996     if (!N01C || N01C->getZExtValue() != 0xFF00)
2997       return SDValue();
2998     N0 = N0.getOperand(0);
2999     LookPassAnd0 = true;
3000   }
3001
3002   if (N1.getOpcode() == ISD::AND) {
3003     if (!N1.getNode()->hasOneUse())
3004       return SDValue();
3005     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3006     if (!N11C || N11C->getZExtValue() != 0xFF)
3007       return SDValue();
3008     N1 = N1.getOperand(0);
3009     LookPassAnd1 = true;
3010   }
3011
3012   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3013     std::swap(N0, N1);
3014   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3015     return SDValue();
3016   if (!N0.getNode()->hasOneUse() ||
3017       !N1.getNode()->hasOneUse())
3018     return SDValue();
3019
3020   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3021   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3022   if (!N01C || !N11C)
3023     return SDValue();
3024   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3025     return SDValue();
3026
3027   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3028   SDValue N00 = N0->getOperand(0);
3029   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3030     if (!N00.getNode()->hasOneUse())
3031       return SDValue();
3032     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3033     if (!N001C || N001C->getZExtValue() != 0xFF)
3034       return SDValue();
3035     N00 = N00.getOperand(0);
3036     LookPassAnd0 = true;
3037   }
3038
3039   SDValue N10 = N1->getOperand(0);
3040   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3041     if (!N10.getNode()->hasOneUse())
3042       return SDValue();
3043     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3044     if (!N101C || N101C->getZExtValue() != 0xFF00)
3045       return SDValue();
3046     N10 = N10.getOperand(0);
3047     LookPassAnd1 = true;
3048   }
3049
3050   if (N00 != N10)
3051     return SDValue();
3052
3053   // Make sure everything beyond the low halfword gets set to zero since the SRL
3054   // 16 will clear the top bits.
3055   unsigned OpSizeInBits = VT.getSizeInBits();
3056   if (DemandHighBits && OpSizeInBits > 16) {
3057     // If the left-shift isn't masked out then the only way this is a bswap is
3058     // if all bits beyond the low 8 are 0. In that case the entire pattern
3059     // reduces to a left shift anyway: leave it for other parts of the combiner.
3060     if (!LookPassAnd0)
3061       return SDValue();
3062
3063     // However, if the right shift isn't masked out then it might be because
3064     // it's not needed. See if we can spot that too.
3065     if (!LookPassAnd1 &&
3066         !DAG.MaskedValueIsZero(
3067             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3068       return SDValue();
3069   }
3070
3071   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3072   if (OpSizeInBits > 16)
3073     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3074                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3075   return Res;
3076 }
3077
3078 /// isBSwapHWordElement - Return true if the specified node is an element
3079 /// that makes up a 32-bit packed halfword byteswap. i.e.
3080 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3081 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3082   if (!N.getNode()->hasOneUse())
3083     return false;
3084
3085   unsigned Opc = N.getOpcode();
3086   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3087     return false;
3088
3089   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3090   if (!N1C)
3091     return false;
3092
3093   unsigned Num;
3094   switch (N1C->getZExtValue()) {
3095   default:
3096     return false;
3097   case 0xFF:       Num = 0; break;
3098   case 0xFF00:     Num = 1; break;
3099   case 0xFF0000:   Num = 2; break;
3100   case 0xFF000000: Num = 3; break;
3101   }
3102
3103   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3104   SDValue N0 = N.getOperand(0);
3105   if (Opc == ISD::AND) {
3106     if (Num == 0 || Num == 2) {
3107       // (x >> 8) & 0xff
3108       // (x >> 8) & 0xff0000
3109       if (N0.getOpcode() != ISD::SRL)
3110         return false;
3111       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3112       if (!C || C->getZExtValue() != 8)
3113         return false;
3114     } else {
3115       // (x << 8) & 0xff00
3116       // (x << 8) & 0xff000000
3117       if (N0.getOpcode() != ISD::SHL)
3118         return false;
3119       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3120       if (!C || C->getZExtValue() != 8)
3121         return false;
3122     }
3123   } else if (Opc == ISD::SHL) {
3124     // (x & 0xff) << 8
3125     // (x & 0xff0000) << 8
3126     if (Num != 0 && Num != 2)
3127       return false;
3128     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3129     if (!C || C->getZExtValue() != 8)
3130       return false;
3131   } else { // Opc == ISD::SRL
3132     // (x & 0xff00) >> 8
3133     // (x & 0xff000000) >> 8
3134     if (Num != 1 && Num != 3)
3135       return false;
3136     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3137     if (!C || C->getZExtValue() != 8)
3138       return false;
3139   }
3140
3141   if (Parts[Num])
3142     return false;
3143
3144   Parts[Num] = N0.getOperand(0).getNode();
3145   return true;
3146 }
3147
3148 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3149 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3150 /// => (rotl (bswap x), 16)
3151 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3152   if (!LegalOperations)
3153     return SDValue();
3154
3155   EVT VT = N->getValueType(0);
3156   if (VT != MVT::i32)
3157     return SDValue();
3158   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3159     return SDValue();
3160
3161   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3162   // Look for either
3163   // (or (or (and), (and)), (or (and), (and)))
3164   // (or (or (or (and), (and)), (and)), (and))
3165   if (N0.getOpcode() != ISD::OR)
3166     return SDValue();
3167   SDValue N00 = N0.getOperand(0);
3168   SDValue N01 = N0.getOperand(1);
3169
3170   if (N1.getOpcode() == ISD::OR &&
3171       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3172     // (or (or (and), (and)), (or (and), (and)))
3173     SDValue N000 = N00.getOperand(0);
3174     if (!isBSwapHWordElement(N000, Parts))
3175       return SDValue();
3176
3177     SDValue N001 = N00.getOperand(1);
3178     if (!isBSwapHWordElement(N001, Parts))
3179       return SDValue();
3180     SDValue N010 = N01.getOperand(0);
3181     if (!isBSwapHWordElement(N010, Parts))
3182       return SDValue();
3183     SDValue N011 = N01.getOperand(1);
3184     if (!isBSwapHWordElement(N011, Parts))
3185       return SDValue();
3186   } else {
3187     // (or (or (or (and), (and)), (and)), (and))
3188     if (!isBSwapHWordElement(N1, Parts))
3189       return SDValue();
3190     if (!isBSwapHWordElement(N01, Parts))
3191       return SDValue();
3192     if (N00.getOpcode() != ISD::OR)
3193       return SDValue();
3194     SDValue N000 = N00.getOperand(0);
3195     if (!isBSwapHWordElement(N000, Parts))
3196       return SDValue();
3197     SDValue N001 = N00.getOperand(1);
3198     if (!isBSwapHWordElement(N001, Parts))
3199       return SDValue();
3200   }
3201
3202   // Make sure the parts are all coming from the same node.
3203   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3204     return SDValue();
3205
3206   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3207                               SDValue(Parts[0],0));
3208
3209   // Result of the bswap should be rotated by 16. If it's not legal, then
3210   // do  (x << 16) | (x >> 16).
3211   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3212   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3213     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3214   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3215     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3216   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3217                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3218                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3219 }
3220
3221 SDValue DAGCombiner::visitOR(SDNode *N) {
3222   SDValue N0 = N->getOperand(0);
3223   SDValue N1 = N->getOperand(1);
3224   SDValue LL, LR, RL, RR, CC0, CC1;
3225   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3226   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3227   EVT VT = N1.getValueType();
3228
3229   // fold vector ops
3230   if (VT.isVector()) {
3231     SDValue FoldedVOp = SimplifyVBinOp(N);
3232     if (FoldedVOp.getNode()) return FoldedVOp;
3233
3234     // fold (or x, 0) -> x, vector edition
3235     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3236       return N1;
3237     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3238       return N0;
3239
3240     // fold (or x, -1) -> -1, vector edition
3241     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3242       return N0;
3243     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3244       return N1;
3245
3246     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3247     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3248     // Do this only if the resulting shuffle is legal.
3249     if (isa<ShuffleVectorSDNode>(N0) &&
3250         isa<ShuffleVectorSDNode>(N1) &&
3251         N0->getOperand(1) == N1->getOperand(1) &&
3252         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3253       bool CanFold = true;
3254       unsigned NumElts = VT.getVectorNumElements();
3255       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3256       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3257       // We construct two shuffle masks:
3258       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3259       // and N1 as the second operand.
3260       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3261       // and N0 as the second operand.
3262       // We do this because OR is commutable and therefore there might be
3263       // two ways to fold this node into a shuffle.
3264       SmallVector<int,4> Mask1;
3265       SmallVector<int,4> Mask2;
3266       
3267       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3268         int M0 = SV0->getMaskElt(i);
3269         int M1 = SV1->getMaskElt(i);
3270    
3271         // Both shuffle indexes are undef. Propagate Undef.
3272         if (M0 < 0 && M1 < 0) {
3273           Mask1.push_back(M0);
3274           Mask2.push_back(M0);
3275           continue;
3276         }
3277
3278         if (M0 < 0 || M1 < 0 ||
3279             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3280             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3281           CanFold = false;
3282           break;
3283         }
3284         
3285         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3286         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3287       }
3288
3289       if (CanFold) {
3290         // Fold this sequence only if the resulting shuffle is 'legal'.
3291         if (TLI.isShuffleMaskLegal(Mask1, VT))
3292           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3293                                       N1->getOperand(0), &Mask1[0]);
3294         if (TLI.isShuffleMaskLegal(Mask2, VT))
3295           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3296                                       N0->getOperand(0), &Mask2[0]);
3297       }
3298     }
3299   }
3300
3301   // fold (or x, undef) -> -1
3302   if (!LegalOperations &&
3303       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3304     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3305     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3306   }
3307   // fold (or c1, c2) -> c1|c2
3308   if (N0C && N1C)
3309     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3310   // canonicalize constant to RHS
3311   if (N0C && !N1C)
3312     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3313   // fold (or x, 0) -> x
3314   if (N1C && N1C->isNullValue())
3315     return N0;
3316   // fold (or x, -1) -> -1
3317   if (N1C && N1C->isAllOnesValue())
3318     return N1;
3319   // fold (or x, c) -> c iff (x & ~c) == 0
3320   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3321     return N1;
3322
3323   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3324   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3325   if (BSwap.getNode() != 0)
3326     return BSwap;
3327   BSwap = MatchBSwapHWordLow(N, N0, N1);
3328   if (BSwap.getNode() != 0)
3329     return BSwap;
3330
3331   // reassociate or
3332   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3333   if (ROR.getNode() != 0)
3334     return ROR;
3335   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3336   // iff (c1 & c2) == 0.
3337   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3338              isa<ConstantSDNode>(N0.getOperand(1))) {
3339     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3340     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3341       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3342       if (!COR.getNode())
3343         return SDValue();
3344       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3345                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3346                                      N0.getOperand(0), N1), COR);
3347     }
3348   }
3349   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3350   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3351     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3352     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3353
3354     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3355         LL.getValueType().isInteger()) {
3356       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3357       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3358       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3359           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3360         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3361                                      LR.getValueType(), LL, RL);
3362         AddToWorkList(ORNode.getNode());
3363         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3364       }
3365       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3366       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3367       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3368           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3369         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3370                                       LR.getValueType(), LL, RL);
3371         AddToWorkList(ANDNode.getNode());
3372         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3373       }
3374     }
3375     // canonicalize equivalent to ll == rl
3376     if (LL == RR && LR == RL) {
3377       Op1 = ISD::getSetCCSwappedOperands(Op1);
3378       std::swap(RL, RR);
3379     }
3380     if (LL == RL && LR == RR) {
3381       bool isInteger = LL.getValueType().isInteger();
3382       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3383       if (Result != ISD::SETCC_INVALID &&
3384           (!LegalOperations ||
3385            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3386             TLI.isOperationLegal(ISD::SETCC,
3387               getSetCCResultType(N0.getValueType())))))
3388         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3389                             LL, LR, Result);
3390     }
3391   }
3392
3393   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3394   if (N0.getOpcode() == N1.getOpcode()) {
3395     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3396     if (Tmp.getNode()) return Tmp;
3397   }
3398
3399   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3400   if (N0.getOpcode() == ISD::AND &&
3401       N1.getOpcode() == ISD::AND &&
3402       N0.getOperand(1).getOpcode() == ISD::Constant &&
3403       N1.getOperand(1).getOpcode() == ISD::Constant &&
3404       // Don't increase # computations.
3405       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3406     // We can only do this xform if we know that bits from X that are set in C2
3407     // but not in C1 are already zero.  Likewise for Y.
3408     const APInt &LHSMask =
3409       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3410     const APInt &RHSMask =
3411       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3412
3413     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3414         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3415       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3416                               N0.getOperand(0), N1.getOperand(0));
3417       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3418                          DAG.getConstant(LHSMask | RHSMask, VT));
3419     }
3420   }
3421
3422   // See if this is some rotate idiom.
3423   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3424     return SDValue(Rot, 0);
3425
3426   // Simplify the operands using demanded-bits information.
3427   if (!VT.isVector() &&
3428       SimplifyDemandedBits(SDValue(N, 0)))
3429     return SDValue(N, 0);
3430
3431   return SDValue();
3432 }
3433
3434 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3435 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3436   if (Op.getOpcode() == ISD::AND) {
3437     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3438       Mask = Op.getOperand(1);
3439       Op = Op.getOperand(0);
3440     } else {
3441       return false;
3442     }
3443   }
3444
3445   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3446     Shift = Op;
3447     return true;
3448   }
3449
3450   return false;
3451 }
3452
3453 // Return true if we can prove that, whenever Neg and Pos are both in the
3454 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3455 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3456 //
3457 //     (or (shift1 X, Neg), (shift2 X, Pos))
3458 //
3459 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3460 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3461 // to consider shift amounts with defined behavior.
3462 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3463   // If OpSize is a power of 2 then:
3464   //
3465   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3466   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3467   //
3468   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3469   // for the stronger condition:
3470   //
3471   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3472   //
3473   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3474   // we can just replace Neg with Neg' for the rest of the function.
3475   //
3476   // In other cases we check for the even stronger condition:
3477   //
3478   //     Neg == OpSize - Pos                                    [B]
3479   //
3480   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3481   // behavior if Pos == 0 (and consequently Neg == OpSize).
3482   //
3483   // We could actually use [A] whenever OpSize is a power of 2, but the
3484   // only extra cases that it would match are those uninteresting ones
3485   // where Neg and Pos are never in range at the same time.  E.g. for
3486   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3487   // as well as (sub 32, Pos), but:
3488   //
3489   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3490   //
3491   // always invokes undefined behavior for 32-bit X.
3492   //
3493   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3494   unsigned MaskLoBits = 0;
3495   if (Neg.getOpcode() == ISD::AND &&
3496       isPowerOf2_64(OpSize) &&
3497       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3498       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3499     Neg = Neg.getOperand(0);
3500     MaskLoBits = Log2_64(OpSize);
3501   }
3502
3503   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3504   if (Neg.getOpcode() != ISD::SUB)
3505     return 0;
3506   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3507   if (!NegC)
3508     return 0;
3509   SDValue NegOp1 = Neg.getOperand(1);
3510
3511   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3512   // Pos'.  The truncation is redundant for the purpose of the equality.
3513   if (MaskLoBits &&
3514       Pos.getOpcode() == ISD::AND &&
3515       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3516       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3517     Pos = Pos.getOperand(0);
3518
3519   // The condition we need is now:
3520   //
3521   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3522   //
3523   // If NegOp1 == Pos then we need:
3524   //
3525   //              OpSize & Mask == NegC & Mask
3526   //
3527   // (because "x & Mask" is a truncation and distributes through subtraction).
3528   APInt Width;
3529   if (Pos == NegOp1)
3530     Width = NegC->getAPIntValue();
3531   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3532   // Then the condition we want to prove becomes:
3533   //
3534   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3535   //
3536   // which, again because "x & Mask" is a truncation, becomes:
3537   //
3538   //                NegC & Mask == (OpSize - PosC) & Mask
3539   //              OpSize & Mask == (NegC + PosC) & Mask
3540   else if (Pos.getOpcode() == ISD::ADD &&
3541            Pos.getOperand(0) == NegOp1 &&
3542            Pos.getOperand(1).getOpcode() == ISD::Constant)
3543     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3544              NegC->getAPIntValue());
3545   else
3546     return false;
3547
3548   // Now we just need to check that OpSize & Mask == Width & Mask.
3549   if (MaskLoBits)
3550     // Opsize & Mask is 0 since Mask is Opsize - 1.
3551     return Width.getLoBits(MaskLoBits) == 0;
3552   return Width == OpSize;
3553 }
3554
3555 // A subroutine of MatchRotate used once we have found an OR of two opposite
3556 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3557 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3558 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3559 // Neg with outer conversions stripped away.
3560 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3561                                        SDValue Neg, SDValue InnerPos,
3562                                        SDValue InnerNeg, unsigned PosOpcode,
3563                                        unsigned NegOpcode, SDLoc DL) {
3564   // fold (or (shl x, (*ext y)),
3565   //          (srl x, (*ext (sub 32, y)))) ->
3566   //   (rotl x, y) or (rotr x, (sub 32, y))
3567   //
3568   // fold (or (shl x, (*ext (sub 32, y))),
3569   //          (srl x, (*ext y))) ->
3570   //   (rotr x, y) or (rotl x, (sub 32, y))
3571   EVT VT = Shifted.getValueType();
3572   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3573     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3574     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3575                        HasPos ? Pos : Neg).getNode();
3576   }
3577
3578   // fold (or (shl (*ext x), (*ext y)),
3579   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3580   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3581   //
3582   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3583   //          (srl (*ext x), (*ext y))) ->
3584   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3585   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3586       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3587     SDValue InnerShifted = Shifted.getOperand(0);
3588     EVT InnerVT = InnerShifted.getValueType();
3589     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3590     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3591       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3592         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3593                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3594         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3595       }
3596     }
3597   }
3598
3599   return 0;
3600 }
3601
3602 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3603 // idioms for rotate, and if the target supports rotation instructions, generate
3604 // a rot[lr].
3605 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3606   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3607   EVT VT = LHS.getValueType();
3608   if (!TLI.isTypeLegal(VT)) return 0;
3609
3610   // The target must have at least one rotate flavor.
3611   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3612   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3613   if (!HasROTL && !HasROTR) return 0;
3614
3615   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3616   SDValue LHSShift;   // The shift.
3617   SDValue LHSMask;    // AND value if any.
3618   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3619     return 0; // Not part of a rotate.
3620
3621   SDValue RHSShift;   // The shift.
3622   SDValue RHSMask;    // AND value if any.
3623   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3624     return 0; // Not part of a rotate.
3625
3626   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3627     return 0;   // Not shifting the same value.
3628
3629   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3630     return 0;   // Shifts must disagree.
3631
3632   // Canonicalize shl to left side in a shl/srl pair.
3633   if (RHSShift.getOpcode() == ISD::SHL) {
3634     std::swap(LHS, RHS);
3635     std::swap(LHSShift, RHSShift);
3636     std::swap(LHSMask , RHSMask );
3637   }
3638
3639   unsigned OpSizeInBits = VT.getSizeInBits();
3640   SDValue LHSShiftArg = LHSShift.getOperand(0);
3641   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3642   SDValue RHSShiftArg = RHSShift.getOperand(0);
3643   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3644
3645   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3646   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3647   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3648       RHSShiftAmt.getOpcode() == ISD::Constant) {
3649     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3650     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3651     if ((LShVal + RShVal) != OpSizeInBits)
3652       return 0;
3653
3654     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3655                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3656
3657     // If there is an AND of either shifted operand, apply it to the result.
3658     if (LHSMask.getNode() || RHSMask.getNode()) {
3659       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3660
3661       if (LHSMask.getNode()) {
3662         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3663         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3664       }
3665       if (RHSMask.getNode()) {
3666         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3667         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3668       }
3669
3670       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3671     }
3672
3673     return Rot.getNode();
3674   }
3675
3676   // If there is a mask here, and we have a variable shift, we can't be sure
3677   // that we're masking out the right stuff.
3678   if (LHSMask.getNode() || RHSMask.getNode())
3679     return 0;
3680
3681   // If the shift amount is sign/zext/any-extended just peel it off.
3682   SDValue LExtOp0 = LHSShiftAmt;
3683   SDValue RExtOp0 = RHSShiftAmt;
3684   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3685        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3686        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3687        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3688       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3689        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3690        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3691        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3692     LExtOp0 = LHSShiftAmt.getOperand(0);
3693     RExtOp0 = RHSShiftAmt.getOperand(0);
3694   }
3695
3696   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3697                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3698   if (TryL)
3699     return TryL;
3700
3701   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3702                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3703   if (TryR)
3704     return TryR;
3705
3706   return 0;
3707 }
3708
3709 SDValue DAGCombiner::visitXOR(SDNode *N) {
3710   SDValue N0 = N->getOperand(0);
3711   SDValue N1 = N->getOperand(1);
3712   SDValue LHS, RHS, CC;
3713   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3714   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3715   EVT VT = N0.getValueType();
3716
3717   // fold vector ops
3718   if (VT.isVector()) {
3719     SDValue FoldedVOp = SimplifyVBinOp(N);
3720     if (FoldedVOp.getNode()) return FoldedVOp;
3721
3722     // fold (xor x, 0) -> x, vector edition
3723     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3724       return N1;
3725     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3726       return N0;
3727   }
3728
3729   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3730   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3731     return DAG.getConstant(0, VT);
3732   // fold (xor x, undef) -> undef
3733   if (N0.getOpcode() == ISD::UNDEF)
3734     return N0;
3735   if (N1.getOpcode() == ISD::UNDEF)
3736     return N1;
3737   // fold (xor c1, c2) -> c1^c2
3738   if (N0C && N1C)
3739     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3740   // canonicalize constant to RHS
3741   if (N0C && !N1C)
3742     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3743   // fold (xor x, 0) -> x
3744   if (N1C && N1C->isNullValue())
3745     return N0;
3746   // reassociate xor
3747   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3748   if (RXOR.getNode() != 0)
3749     return RXOR;
3750
3751   // fold !(x cc y) -> (x !cc y)
3752   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3753     bool isInt = LHS.getValueType().isInteger();
3754     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3755                                                isInt);
3756
3757     if (!LegalOperations ||
3758         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3759       switch (N0.getOpcode()) {
3760       default:
3761         llvm_unreachable("Unhandled SetCC Equivalent!");
3762       case ISD::SETCC:
3763         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3764       case ISD::SELECT_CC:
3765         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3766                                N0.getOperand(3), NotCC);
3767       }
3768     }
3769   }
3770
3771   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3772   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3773       N0.getNode()->hasOneUse() &&
3774       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3775     SDValue V = N0.getOperand(0);
3776     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3777                     DAG.getConstant(1, V.getValueType()));
3778     AddToWorkList(V.getNode());
3779     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3780   }
3781
3782   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3783   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3784       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3785     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3786     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3787       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3788       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3789       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3790       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3791       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3792     }
3793   }
3794   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3795   if (N1C && N1C->isAllOnesValue() &&
3796       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3797     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3798     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3799       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3800       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3801       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3802       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3803       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3804     }
3805   }
3806   // fold (xor (and x, y), y) -> (and (not x), y)
3807   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3808       N0->getOperand(1) == N1) {
3809     SDValue X = N0->getOperand(0);
3810     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3811     AddToWorkList(NotX.getNode());
3812     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3813   }
3814   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3815   if (N1C && N0.getOpcode() == ISD::XOR) {
3816     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3817     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3818     if (N00C)
3819       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3820                          DAG.getConstant(N1C->getAPIntValue() ^
3821                                          N00C->getAPIntValue(), VT));
3822     if (N01C)
3823       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3824                          DAG.getConstant(N1C->getAPIntValue() ^
3825                                          N01C->getAPIntValue(), VT));
3826   }
3827   // fold (xor x, x) -> 0
3828   if (N0 == N1)
3829     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3830
3831   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3832   if (N0.getOpcode() == N1.getOpcode()) {
3833     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3834     if (Tmp.getNode()) return Tmp;
3835   }
3836
3837   // Simplify the expression using non-local knowledge.
3838   if (!VT.isVector() &&
3839       SimplifyDemandedBits(SDValue(N, 0)))
3840     return SDValue(N, 0);
3841
3842   return SDValue();
3843 }
3844
3845 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3846 /// the shift amount is a constant.
3847 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3848   // We can't and shouldn't fold opaque constants.
3849   if (Amt->isOpaque())
3850     return SDValue();
3851
3852   SDNode *LHS = N->getOperand(0).getNode();
3853   if (!LHS->hasOneUse()) return SDValue();
3854
3855   // We want to pull some binops through shifts, so that we have (and (shift))
3856   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3857   // thing happens with address calculations, so it's important to canonicalize
3858   // it.
3859   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3860
3861   switch (LHS->getOpcode()) {
3862   default: return SDValue();
3863   case ISD::OR:
3864   case ISD::XOR:
3865     HighBitSet = false; // We can only transform sra if the high bit is clear.
3866     break;
3867   case ISD::AND:
3868     HighBitSet = true;  // We can only transform sra if the high bit is set.
3869     break;
3870   case ISD::ADD:
3871     if (N->getOpcode() != ISD::SHL)
3872       return SDValue(); // only shl(add) not sr[al](add).
3873     HighBitSet = false; // We can only transform sra if the high bit is clear.
3874     break;
3875   }
3876
3877   // We require the RHS of the binop to be a constant and not opaque as well.
3878   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3879   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3880
3881   // FIXME: disable this unless the input to the binop is a shift by a constant.
3882   // If it is not a shift, it pessimizes some common cases like:
3883   //
3884   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3885   //    int bar(int *X, int i) { return X[i & 255]; }
3886   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3887   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3888        BinOpLHSVal->getOpcode() != ISD::SRA &&
3889        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3890       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3891     return SDValue();
3892
3893   EVT VT = N->getValueType(0);
3894
3895   // If this is a signed shift right, and the high bit is modified by the
3896   // logical operation, do not perform the transformation. The highBitSet
3897   // boolean indicates the value of the high bit of the constant which would
3898   // cause it to be modified for this operation.
3899   if (N->getOpcode() == ISD::SRA) {
3900     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3901     if (BinOpRHSSignSet != HighBitSet)
3902       return SDValue();
3903   }
3904
3905   // Fold the constants, shifting the binop RHS by the shift amount.
3906   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3907                                N->getValueType(0),
3908                                LHS->getOperand(1), N->getOperand(1));
3909   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3910
3911   // Create the new shift.
3912   SDValue NewShift = DAG.getNode(N->getOpcode(),
3913                                  SDLoc(LHS->getOperand(0)),
3914                                  VT, LHS->getOperand(0), N->getOperand(1));
3915
3916   // Create the new binop.
3917   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3918 }
3919
3920 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3921   assert(N->getOpcode() == ISD::TRUNCATE);
3922   assert(N->getOperand(0).getOpcode() == ISD::AND);
3923
3924   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3925   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3926     SDValue N01 = N->getOperand(0).getOperand(1);
3927
3928     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3929       EVT TruncVT = N->getValueType(0);
3930       SDValue N00 = N->getOperand(0).getOperand(0);
3931       APInt TruncC = N01C->getAPIntValue();
3932       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3933
3934       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3935                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3936                          DAG.getConstant(TruncC, TruncVT));
3937     }
3938   }
3939
3940   return SDValue();
3941 }
3942
3943 SDValue DAGCombiner::visitRotate(SDNode *N) {
3944   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3945   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3946       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3947     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3948     if (NewOp1.getNode())
3949       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3950                          N->getOperand(0), NewOp1);
3951   }
3952   return SDValue();
3953 }
3954
3955 SDValue DAGCombiner::visitSHL(SDNode *N) {
3956   SDValue N0 = N->getOperand(0);
3957   SDValue N1 = N->getOperand(1);
3958   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3959   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3960   EVT VT = N0.getValueType();
3961   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3962
3963   // fold vector ops
3964   if (VT.isVector()) {
3965     SDValue FoldedVOp = SimplifyVBinOp(N);
3966     if (FoldedVOp.getNode()) return FoldedVOp;
3967
3968     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3969     // If setcc produces all-one true value then:
3970     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3971     if (N1CV && N1CV->isConstant()) {
3972       if (N0.getOpcode() == ISD::AND &&
3973           TLI.getBooleanContents(true) ==
3974           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3975         SDValue N00 = N0->getOperand(0);
3976         SDValue N01 = N0->getOperand(1);
3977         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3978
3979         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3980           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3981           if (C.getNode())
3982             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3983         }
3984       } else {
3985         N1C = isConstOrConstSplat(N1);
3986       }
3987     }
3988   }
3989
3990   // fold (shl c1, c2) -> c1<<c2
3991   if (N0C && N1C)
3992     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3993   // fold (shl 0, x) -> 0
3994   if (N0C && N0C->isNullValue())
3995     return N0;
3996   // fold (shl x, c >= size(x)) -> undef
3997   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3998     return DAG.getUNDEF(VT);
3999   // fold (shl x, 0) -> x
4000   if (N1C && N1C->isNullValue())
4001     return N0;
4002   // fold (shl undef, x) -> 0
4003   if (N0.getOpcode() == ISD::UNDEF)
4004     return DAG.getConstant(0, VT);
4005   // if (shl x, c) is known to be zero, return 0
4006   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4007                             APInt::getAllOnesValue(OpSizeInBits)))
4008     return DAG.getConstant(0, VT);
4009   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4010   if (N1.getOpcode() == ISD::TRUNCATE &&
4011       N1.getOperand(0).getOpcode() == ISD::AND) {
4012     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4013     if (NewOp1.getNode())
4014       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4015   }
4016
4017   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4018     return SDValue(N, 0);
4019
4020   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4021   if (N1C && N0.getOpcode() == ISD::SHL) {
4022     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4023       uint64_t c1 = N0C1->getZExtValue();
4024       uint64_t c2 = N1C->getZExtValue();
4025       if (c1 + c2 >= OpSizeInBits)
4026         return DAG.getConstant(0, VT);
4027       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4028                          DAG.getConstant(c1 + c2, N1.getValueType()));
4029     }
4030   }
4031
4032   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4033   // For this to be valid, the second form must not preserve any of the bits
4034   // that are shifted out by the inner shift in the first form.  This means
4035   // the outer shift size must be >= the number of bits added by the ext.
4036   // As a corollary, we don't care what kind of ext it is.
4037   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4038               N0.getOpcode() == ISD::ANY_EXTEND ||
4039               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4040       N0.getOperand(0).getOpcode() == ISD::SHL) {
4041     SDValue N0Op0 = N0.getOperand(0);
4042     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4043       uint64_t c1 = N0Op0C1->getZExtValue();
4044       uint64_t c2 = N1C->getZExtValue();
4045       EVT InnerShiftVT = N0Op0.getValueType();
4046       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4047       if (c2 >= OpSizeInBits - InnerShiftSize) {
4048         if (c1 + c2 >= OpSizeInBits)
4049           return DAG.getConstant(0, VT);
4050         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4051                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4052                                        N0Op0->getOperand(0)),
4053                            DAG.getConstant(c1 + c2, N1.getValueType()));
4054       }
4055     }
4056   }
4057
4058   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4059   // Only fold this if the inner zext has no other uses to avoid increasing
4060   // the total number of instructions.
4061   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4062       N0.getOperand(0).getOpcode() == ISD::SRL) {
4063     SDValue N0Op0 = N0.getOperand(0);
4064     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4065       uint64_t c1 = N0Op0C1->getZExtValue();
4066       if (c1 < VT.getScalarSizeInBits()) {
4067         uint64_t c2 = N1C->getZExtValue();
4068         if (c1 == c2) {
4069           SDValue NewOp0 = N0.getOperand(0);
4070           EVT CountVT = NewOp0.getOperand(1).getValueType();
4071           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4072                                        NewOp0, DAG.getConstant(c2, CountVT));
4073           AddToWorkList(NewSHL.getNode());
4074           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4075         }
4076       }
4077     }
4078   }
4079
4080   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4081   //                               (and (srl x, (sub c1, c2), MASK)
4082   // Only fold this if the inner shift has no other uses -- if it does, folding
4083   // this will increase the total number of instructions.
4084   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4085     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4086       uint64_t c1 = N0C1->getZExtValue();
4087       if (c1 < OpSizeInBits) {
4088         uint64_t c2 = N1C->getZExtValue();
4089         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4090         SDValue Shift;
4091         if (c2 > c1) {
4092           Mask = Mask.shl(c2 - c1);
4093           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4094                               DAG.getConstant(c2 - c1, N1.getValueType()));
4095         } else {
4096           Mask = Mask.lshr(c1 - c2);
4097           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4098                               DAG.getConstant(c1 - c2, N1.getValueType()));
4099         }
4100         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4101                            DAG.getConstant(Mask, VT));
4102       }
4103     }
4104   }
4105   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4106   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4107     unsigned BitSize = VT.getScalarSizeInBits();
4108     SDValue HiBitsMask =
4109       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4110                                             BitSize - N1C->getZExtValue()), VT);
4111     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4112                        HiBitsMask);
4113   }
4114
4115   if (N1C) {
4116     SDValue NewSHL = visitShiftByConstant(N, N1C);
4117     if (NewSHL.getNode())
4118       return NewSHL;
4119   }
4120
4121   return SDValue();
4122 }
4123
4124 SDValue DAGCombiner::visitSRA(SDNode *N) {
4125   SDValue N0 = N->getOperand(0);
4126   SDValue N1 = N->getOperand(1);
4127   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4128   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4129   EVT VT = N0.getValueType();
4130   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4131
4132   // fold vector ops
4133   if (VT.isVector()) {
4134     SDValue FoldedVOp = SimplifyVBinOp(N);
4135     if (FoldedVOp.getNode()) return FoldedVOp;
4136
4137     N1C = isConstOrConstSplat(N1);
4138   }
4139
4140   // fold (sra c1, c2) -> (sra c1, c2)
4141   if (N0C && N1C)
4142     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4143   // fold (sra 0, x) -> 0
4144   if (N0C && N0C->isNullValue())
4145     return N0;
4146   // fold (sra -1, x) -> -1
4147   if (N0C && N0C->isAllOnesValue())
4148     return N0;
4149   // fold (sra x, (setge c, size(x))) -> undef
4150   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4151     return DAG.getUNDEF(VT);
4152   // fold (sra x, 0) -> x
4153   if (N1C && N1C->isNullValue())
4154     return N0;
4155   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4156   // sext_inreg.
4157   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4158     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4159     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4160     if (VT.isVector())
4161       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4162                                ExtVT, VT.getVectorNumElements());
4163     if ((!LegalOperations ||
4164          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4165       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4166                          N0.getOperand(0), DAG.getValueType(ExtVT));
4167   }
4168
4169   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4170   if (N1C && N0.getOpcode() == ISD::SRA) {
4171     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4172       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4173       if (Sum >= OpSizeInBits)
4174         Sum = OpSizeInBits - 1;
4175       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4176                          DAG.getConstant(Sum, N1.getValueType()));
4177     }
4178   }
4179
4180   // fold (sra (shl X, m), (sub result_size, n))
4181   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4182   // result_size - n != m.
4183   // If truncate is free for the target sext(shl) is likely to result in better
4184   // code.
4185   if (N0.getOpcode() == ISD::SHL && N1C) {
4186     // Get the two constanst of the shifts, CN0 = m, CN = n.
4187     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4188     if (N01C) {
4189       LLVMContext &Ctx = *DAG.getContext();
4190       // Determine what the truncate's result bitsize and type would be.
4191       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4192
4193       if (VT.isVector())
4194         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4195
4196       // Determine the residual right-shift amount.
4197       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4198
4199       // If the shift is not a no-op (in which case this should be just a sign
4200       // extend already), the truncated to type is legal, sign_extend is legal
4201       // on that type, and the truncate to that type is both legal and free,
4202       // perform the transform.
4203       if ((ShiftAmt > 0) &&
4204           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4205           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4206           TLI.isTruncateFree(VT, TruncVT)) {
4207
4208           SDValue Amt = DAG.getConstant(ShiftAmt,
4209               getShiftAmountTy(N0.getOperand(0).getValueType()));
4210           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4211                                       N0.getOperand(0), Amt);
4212           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4213                                       Shift);
4214           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4215                              N->getValueType(0), Trunc);
4216       }
4217     }
4218   }
4219
4220   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4221   if (N1.getOpcode() == ISD::TRUNCATE &&
4222       N1.getOperand(0).getOpcode() == ISD::AND) {
4223     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4224     if (NewOp1.getNode())
4225       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4226   }
4227
4228   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4229   //      if c1 is equal to the number of bits the trunc removes
4230   if (N0.getOpcode() == ISD::TRUNCATE &&
4231       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4232        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4233       N0.getOperand(0).hasOneUse() &&
4234       N0.getOperand(0).getOperand(1).hasOneUse() &&
4235       N1C) {
4236     SDValue N0Op0 = N0.getOperand(0);
4237     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4238       unsigned LargeShiftVal = LargeShift->getZExtValue();
4239       EVT LargeVT = N0Op0.getValueType();
4240
4241       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4242         SDValue Amt =
4243           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4244                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4245         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4246                                   N0Op0.getOperand(0), Amt);
4247         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4248       }
4249     }
4250   }
4251
4252   // Simplify, based on bits shifted out of the LHS.
4253   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4254     return SDValue(N, 0);
4255
4256
4257   // If the sign bit is known to be zero, switch this to a SRL.
4258   if (DAG.SignBitIsZero(N0))
4259     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4260
4261   if (N1C) {
4262     SDValue NewSRA = visitShiftByConstant(N, N1C);
4263     if (NewSRA.getNode())
4264       return NewSRA;
4265   }
4266
4267   return SDValue();
4268 }
4269
4270 SDValue DAGCombiner::visitSRL(SDNode *N) {
4271   SDValue N0 = N->getOperand(0);
4272   SDValue N1 = N->getOperand(1);
4273   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4274   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4275   EVT VT = N0.getValueType();
4276   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4277
4278   // fold vector ops
4279   if (VT.isVector()) {
4280     SDValue FoldedVOp = SimplifyVBinOp(N);
4281     if (FoldedVOp.getNode()) return FoldedVOp;
4282
4283     N1C = isConstOrConstSplat(N1);
4284   }
4285
4286   // fold (srl c1, c2) -> c1 >>u c2
4287   if (N0C && N1C)
4288     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4289   // fold (srl 0, x) -> 0
4290   if (N0C && N0C->isNullValue())
4291     return N0;
4292   // fold (srl x, c >= size(x)) -> undef
4293   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4294     return DAG.getUNDEF(VT);
4295   // fold (srl x, 0) -> x
4296   if (N1C && N1C->isNullValue())
4297     return N0;
4298   // if (srl x, c) is known to be zero, return 0
4299   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4300                                    APInt::getAllOnesValue(OpSizeInBits)))
4301     return DAG.getConstant(0, VT);
4302
4303   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4304   if (N1C && N0.getOpcode() == ISD::SRL) {
4305     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4306       uint64_t c1 = N01C->getZExtValue();
4307       uint64_t c2 = N1C->getZExtValue();
4308       if (c1 + c2 >= OpSizeInBits)
4309         return DAG.getConstant(0, VT);
4310       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4311                          DAG.getConstant(c1 + c2, N1.getValueType()));
4312     }
4313   }
4314
4315   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4316   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4317       N0.getOperand(0).getOpcode() == ISD::SRL &&
4318       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4319     uint64_t c1 =
4320       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4321     uint64_t c2 = N1C->getZExtValue();
4322     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4323     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4324     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4325     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4326     if (c1 + OpSizeInBits == InnerShiftSize) {
4327       if (c1 + c2 >= InnerShiftSize)
4328         return DAG.getConstant(0, VT);
4329       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4330                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4331                                      N0.getOperand(0)->getOperand(0),
4332                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4333     }
4334   }
4335
4336   // fold (srl (shl x, c), c) -> (and x, cst2)
4337   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4338     unsigned BitSize = N0.getScalarValueSizeInBits();
4339     if (BitSize <= 64) {
4340       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4341       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4342                          DAG.getConstant(~0ULL >> ShAmt, VT));
4343     }
4344   }
4345
4346   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4347   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4348     // Shifting in all undef bits?
4349     EVT SmallVT = N0.getOperand(0).getValueType();
4350     unsigned BitSize = SmallVT.getScalarSizeInBits();
4351     if (N1C->getZExtValue() >= BitSize)
4352       return DAG.getUNDEF(VT);
4353
4354     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4355       uint64_t ShiftAmt = N1C->getZExtValue();
4356       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4357                                        N0.getOperand(0),
4358                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4359       AddToWorkList(SmallShift.getNode());
4360       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4361       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4362                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4363                          DAG.getConstant(Mask, VT));
4364     }
4365   }
4366
4367   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4368   // bit, which is unmodified by sra.
4369   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4370     if (N0.getOpcode() == ISD::SRA)
4371       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4372   }
4373
4374   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4375   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4376       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4377     APInt KnownZero, KnownOne;
4378     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4379
4380     // If any of the input bits are KnownOne, then the input couldn't be all
4381     // zeros, thus the result of the srl will always be zero.
4382     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4383
4384     // If all of the bits input the to ctlz node are known to be zero, then
4385     // the result of the ctlz is "32" and the result of the shift is one.
4386     APInt UnknownBits = ~KnownZero;
4387     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4388
4389     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4390     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4391       // Okay, we know that only that the single bit specified by UnknownBits
4392       // could be set on input to the CTLZ node. If this bit is set, the SRL
4393       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4394       // to an SRL/XOR pair, which is likely to simplify more.
4395       unsigned ShAmt = UnknownBits.countTrailingZeros();
4396       SDValue Op = N0.getOperand(0);
4397
4398       if (ShAmt) {
4399         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4400                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4401         AddToWorkList(Op.getNode());
4402       }
4403
4404       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4405                          Op, DAG.getConstant(1, VT));
4406     }
4407   }
4408
4409   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4410   if (N1.getOpcode() == ISD::TRUNCATE &&
4411       N1.getOperand(0).getOpcode() == ISD::AND) {
4412     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4413     if (NewOp1.getNode())
4414       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4415   }
4416
4417   // fold operands of srl based on knowledge that the low bits are not
4418   // demanded.
4419   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4420     return SDValue(N, 0);
4421
4422   if (N1C) {
4423     SDValue NewSRL = visitShiftByConstant(N, N1C);
4424     if (NewSRL.getNode())
4425       return NewSRL;
4426   }
4427
4428   // Attempt to convert a srl of a load into a narrower zero-extending load.
4429   SDValue NarrowLoad = ReduceLoadWidth(N);
4430   if (NarrowLoad.getNode())
4431     return NarrowLoad;
4432
4433   // Here is a common situation. We want to optimize:
4434   //
4435   //   %a = ...
4436   //   %b = and i32 %a, 2
4437   //   %c = srl i32 %b, 1
4438   //   brcond i32 %c ...
4439   //
4440   // into
4441   //
4442   //   %a = ...
4443   //   %b = and %a, 2
4444   //   %c = setcc eq %b, 0
4445   //   brcond %c ...
4446   //
4447   // However when after the source operand of SRL is optimized into AND, the SRL
4448   // itself may not be optimized further. Look for it and add the BRCOND into
4449   // the worklist.
4450   if (N->hasOneUse()) {
4451     SDNode *Use = *N->use_begin();
4452     if (Use->getOpcode() == ISD::BRCOND)
4453       AddToWorkList(Use);
4454     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4455       // Also look pass the truncate.
4456       Use = *Use->use_begin();
4457       if (Use->getOpcode() == ISD::BRCOND)
4458         AddToWorkList(Use);
4459     }
4460   }
4461
4462   return SDValue();
4463 }
4464
4465 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4466   SDValue N0 = N->getOperand(0);
4467   EVT VT = N->getValueType(0);
4468
4469   // fold (ctlz c1) -> c2
4470   if (isa<ConstantSDNode>(N0))
4471     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4472   return SDValue();
4473 }
4474
4475 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4476   SDValue N0 = N->getOperand(0);
4477   EVT VT = N->getValueType(0);
4478
4479   // fold (ctlz_zero_undef c1) -> c2
4480   if (isa<ConstantSDNode>(N0))
4481     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4482   return SDValue();
4483 }
4484
4485 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4486   SDValue N0 = N->getOperand(0);
4487   EVT VT = N->getValueType(0);
4488
4489   // fold (cttz c1) -> c2
4490   if (isa<ConstantSDNode>(N0))
4491     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4492   return SDValue();
4493 }
4494
4495 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4496   SDValue N0 = N->getOperand(0);
4497   EVT VT = N->getValueType(0);
4498
4499   // fold (cttz_zero_undef c1) -> c2
4500   if (isa<ConstantSDNode>(N0))
4501     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4502   return SDValue();
4503 }
4504
4505 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4506   SDValue N0 = N->getOperand(0);
4507   EVT VT = N->getValueType(0);
4508
4509   // fold (ctpop c1) -> c2
4510   if (isa<ConstantSDNode>(N0))
4511     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4512   return SDValue();
4513 }
4514
4515 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4516   SDValue N0 = N->getOperand(0);
4517   SDValue N1 = N->getOperand(1);
4518   SDValue N2 = N->getOperand(2);
4519   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4520   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4521   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4522   EVT VT = N->getValueType(0);
4523   EVT VT0 = N0.getValueType();
4524
4525   // fold (select C, X, X) -> X
4526   if (N1 == N2)
4527     return N1;
4528   // fold (select true, X, Y) -> X
4529   if (N0C && !N0C->isNullValue())
4530     return N1;
4531   // fold (select false, X, Y) -> Y
4532   if (N0C && N0C->isNullValue())
4533     return N2;
4534   // fold (select C, 1, X) -> (or C, X)
4535   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4536     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4537   // fold (select C, 0, 1) -> (xor C, 1)
4538   if (VT.isInteger() &&
4539       (VT0 == MVT::i1 ||
4540        (VT0.isInteger() &&
4541         TLI.getBooleanContents(false) ==
4542         TargetLowering::ZeroOrOneBooleanContent)) &&
4543       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4544     SDValue XORNode;
4545     if (VT == VT0)
4546       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4547                          N0, DAG.getConstant(1, VT0));
4548     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4549                           N0, DAG.getConstant(1, VT0));
4550     AddToWorkList(XORNode.getNode());
4551     if (VT.bitsGT(VT0))
4552       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4553     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4554   }
4555   // fold (select C, 0, X) -> (and (not C), X)
4556   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4557     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4558     AddToWorkList(NOTNode.getNode());
4559     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4560   }
4561   // fold (select C, X, 1) -> (or (not C), X)
4562   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4563     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4564     AddToWorkList(NOTNode.getNode());
4565     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4566   }
4567   // fold (select C, X, 0) -> (and C, X)
4568   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4569     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4570   // fold (select X, X, Y) -> (or X, Y)
4571   // fold (select X, 1, Y) -> (or X, Y)
4572   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4573     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4574   // fold (select X, Y, X) -> (and X, Y)
4575   // fold (select X, Y, 0) -> (and X, Y)
4576   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4577     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4578
4579   // If we can fold this based on the true/false value, do so.
4580   if (SimplifySelectOps(N, N1, N2))
4581     return SDValue(N, 0);  // Don't revisit N.
4582
4583   // fold selects based on a setcc into other things, such as min/max/abs
4584   if (N0.getOpcode() == ISD::SETCC) {
4585     // FIXME:
4586     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4587     // having to say they don't support SELECT_CC on every type the DAG knows
4588     // about, since there is no way to mark an opcode illegal at all value types
4589     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4590         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4591       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4592                          N0.getOperand(0), N0.getOperand(1),
4593                          N1, N2, N0.getOperand(2));
4594     return SimplifySelect(SDLoc(N), N0, N1, N2);
4595   }
4596
4597   return SDValue();
4598 }
4599
4600 static
4601 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4602   SDLoc DL(N);
4603   EVT LoVT, HiVT;
4604   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4605
4606   // Split the inputs.
4607   SDValue Lo, Hi, LL, LH, RL, RH;
4608   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4609   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4610
4611   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4612   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4613
4614   return std::make_pair(Lo, Hi);
4615 }
4616
4617 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4618   SDValue N0 = N->getOperand(0);
4619   SDValue N1 = N->getOperand(1);
4620   SDValue N2 = N->getOperand(2);
4621   SDLoc DL(N);
4622
4623   // Canonicalize integer abs.
4624   // vselect (setg[te] X,  0),  X, -X ->
4625   // vselect (setgt    X, -1),  X, -X ->
4626   // vselect (setl[te] X,  0), -X,  X ->
4627   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4628   if (N0.getOpcode() == ISD::SETCC) {
4629     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4630     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4631     bool isAbs = false;
4632     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4633
4634     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4635          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4636         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4637       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4638     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4639              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4640       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4641
4642     if (isAbs) {
4643       EVT VT = LHS.getValueType();
4644       SDValue Shift = DAG.getNode(
4645           ISD::SRA, DL, VT, LHS,
4646           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4647       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4648       AddToWorkList(Shift.getNode());
4649       AddToWorkList(Add.getNode());
4650       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4651     }
4652   }
4653
4654   // If the VSELECT result requires splitting and the mask is provided by a
4655   // SETCC, then split both nodes and its operands before legalization. This
4656   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4657   // and enables future optimizations (e.g. min/max pattern matching on X86).
4658   if (N0.getOpcode() == ISD::SETCC) {
4659     EVT VT = N->getValueType(0);
4660
4661     // Check if any splitting is required.
4662     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4663         TargetLowering::TypeSplitVector)
4664       return SDValue();
4665
4666     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4667     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4668     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4669     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4670
4671     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4672     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4673
4674     // Add the new VSELECT nodes to the work list in case they need to be split
4675     // again.
4676     AddToWorkList(Lo.getNode());
4677     AddToWorkList(Hi.getNode());
4678
4679     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4680   }
4681
4682   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4683   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4684     return N1;
4685   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4686   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4687     return N2;
4688
4689   return SDValue();
4690 }
4691
4692 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4693   SDValue N0 = N->getOperand(0);
4694   SDValue N1 = N->getOperand(1);
4695   SDValue N2 = N->getOperand(2);
4696   SDValue N3 = N->getOperand(3);
4697   SDValue N4 = N->getOperand(4);
4698   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4699
4700   // fold select_cc lhs, rhs, x, x, cc -> x
4701   if (N2 == N3)
4702     return N2;
4703
4704   // Determine if the condition we're dealing with is constant
4705   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4706                               N0, N1, CC, SDLoc(N), false);
4707   if (SCC.getNode()) {
4708     AddToWorkList(SCC.getNode());
4709
4710     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4711       if (!SCCC->isNullValue())
4712         return N2;    // cond always true -> true val
4713       else
4714         return N3;    // cond always false -> false val
4715     }
4716
4717     // Fold to a simpler select_cc
4718     if (SCC.getOpcode() == ISD::SETCC)
4719       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4720                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4721                          SCC.getOperand(2));
4722   }
4723
4724   // If we can fold this based on the true/false value, do so.
4725   if (SimplifySelectOps(N, N2, N3))
4726     return SDValue(N, 0);  // Don't revisit N.
4727
4728   // fold select_cc into other things, such as min/max/abs
4729   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4730 }
4731
4732 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4733   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4734                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4735                        SDLoc(N));
4736 }
4737
4738 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4739 // dag node into a ConstantSDNode or a build_vector of constants.
4740 // This function is called by the DAGCombiner when visiting sext/zext/aext
4741 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4742 // Vector extends are not folded if operations are legal; this is to
4743 // avoid introducing illegal build_vector dag nodes.
4744 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4745                                          SelectionDAG &DAG, bool LegalTypes,
4746                                          bool LegalOperations) {
4747   unsigned Opcode = N->getOpcode();
4748   SDValue N0 = N->getOperand(0);
4749   EVT VT = N->getValueType(0);
4750
4751   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4752          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4753
4754   // fold (sext c1) -> c1
4755   // fold (zext c1) -> c1
4756   // fold (aext c1) -> c1
4757   if (isa<ConstantSDNode>(N0))
4758     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4759
4760   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4761   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4762   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4763   EVT SVT = VT.getScalarType();
4764   if (!(VT.isVector() &&
4765       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4766       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4767     return 0;
4768   
4769   // We can fold this node into a build_vector.
4770   unsigned VTBits = SVT.getSizeInBits();
4771   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4772   unsigned ShAmt = VTBits - EVTBits;
4773   SmallVector<SDValue, 8> Elts;
4774   unsigned NumElts = N0->getNumOperands();
4775   SDLoc DL(N);
4776
4777   for (unsigned i=0; i != NumElts; ++i) {
4778     SDValue Op = N0->getOperand(i);
4779     if (Op->getOpcode() == ISD::UNDEF) {
4780       Elts.push_back(DAG.getUNDEF(SVT));
4781       continue;
4782     }
4783
4784     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4785     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4786     if (Opcode == ISD::SIGN_EXTEND)
4787       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4788                                      SVT));
4789     else
4790       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4791                                      SVT));
4792   }
4793
4794   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4795 }
4796
4797 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4798 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4799 // transformation. Returns true if extension are possible and the above
4800 // mentioned transformation is profitable.
4801 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4802                                     unsigned ExtOpc,
4803                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4804                                     const TargetLowering &TLI) {
4805   bool HasCopyToRegUses = false;
4806   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4807   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4808                             UE = N0.getNode()->use_end();
4809        UI != UE; ++UI) {
4810     SDNode *User = *UI;
4811     if (User == N)
4812       continue;
4813     if (UI.getUse().getResNo() != N0.getResNo())
4814       continue;
4815     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4816     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4817       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4818       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4819         // Sign bits will be lost after a zext.
4820         return false;
4821       bool Add = false;
4822       for (unsigned i = 0; i != 2; ++i) {
4823         SDValue UseOp = User->getOperand(i);
4824         if (UseOp == N0)
4825           continue;
4826         if (!isa<ConstantSDNode>(UseOp))
4827           return false;
4828         Add = true;
4829       }
4830       if (Add)
4831         ExtendNodes.push_back(User);
4832       continue;
4833     }
4834     // If truncates aren't free and there are users we can't
4835     // extend, it isn't worthwhile.
4836     if (!isTruncFree)
4837       return false;
4838     // Remember if this value is live-out.
4839     if (User->getOpcode() == ISD::CopyToReg)
4840       HasCopyToRegUses = true;
4841   }
4842
4843   if (HasCopyToRegUses) {
4844     bool BothLiveOut = false;
4845     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4846          UI != UE; ++UI) {
4847       SDUse &Use = UI.getUse();
4848       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4849         BothLiveOut = true;
4850         break;
4851       }
4852     }
4853     if (BothLiveOut)
4854       // Both unextended and extended values are live out. There had better be
4855       // a good reason for the transformation.
4856       return ExtendNodes.size();
4857   }
4858   return true;
4859 }
4860
4861 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4862                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4863                                   ISD::NodeType ExtType) {
4864   // Extend SetCC uses if necessary.
4865   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4866     SDNode *SetCC = SetCCs[i];
4867     SmallVector<SDValue, 4> Ops;
4868
4869     for (unsigned j = 0; j != 2; ++j) {
4870       SDValue SOp = SetCC->getOperand(j);
4871       if (SOp == Trunc)
4872         Ops.push_back(ExtLoad);
4873       else
4874         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4875     }
4876
4877     Ops.push_back(SetCC->getOperand(2));
4878     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4879                                  &Ops[0], Ops.size()));
4880   }
4881 }
4882
4883 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4884   SDValue N0 = N->getOperand(0);
4885   EVT VT = N->getValueType(0);
4886
4887   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4888                                               LegalOperations))
4889     return SDValue(Res, 0);
4890
4891   // fold (sext (sext x)) -> (sext x)
4892   // fold (sext (aext x)) -> (sext x)
4893   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4894     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4895                        N0.getOperand(0));
4896
4897   if (N0.getOpcode() == ISD::TRUNCATE) {
4898     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4899     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4900     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4901     if (NarrowLoad.getNode()) {
4902       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4903       if (NarrowLoad.getNode() != N0.getNode()) {
4904         CombineTo(N0.getNode(), NarrowLoad);
4905         // CombineTo deleted the truncate, if needed, but not what's under it.
4906         AddToWorkList(oye);
4907       }
4908       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4909     }
4910
4911     // See if the value being truncated is already sign extended.  If so, just
4912     // eliminate the trunc/sext pair.
4913     SDValue Op = N0.getOperand(0);
4914     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4915     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4916     unsigned DestBits = VT.getScalarType().getSizeInBits();
4917     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4918
4919     if (OpBits == DestBits) {
4920       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4921       // bits, it is already ready.
4922       if (NumSignBits > DestBits-MidBits)
4923         return Op;
4924     } else if (OpBits < DestBits) {
4925       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4926       // bits, just sext from i32.
4927       if (NumSignBits > OpBits-MidBits)
4928         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4929     } else {
4930       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4931       // bits, just truncate to i32.
4932       if (NumSignBits > OpBits-MidBits)
4933         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4934     }
4935
4936     // fold (sext (truncate x)) -> (sextinreg x).
4937     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4938                                                  N0.getValueType())) {
4939       if (OpBits < DestBits)
4940         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4941       else if (OpBits > DestBits)
4942         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4943       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4944                          DAG.getValueType(N0.getValueType()));
4945     }
4946   }
4947
4948   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4949   // None of the supported targets knows how to perform load and sign extend
4950   // on vectors in one instruction.  We only perform this transformation on
4951   // scalars.
4952   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4953       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4954       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4955        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4956     bool DoXform = true;
4957     SmallVector<SDNode*, 4> SetCCs;
4958     if (!N0.hasOneUse())
4959       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4960     if (DoXform) {
4961       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4962       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4963                                        LN0->getChain(),
4964                                        LN0->getBasePtr(), N0.getValueType(),
4965                                        LN0->getMemOperand());
4966       CombineTo(N, ExtLoad);
4967       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4968                                   N0.getValueType(), ExtLoad);
4969       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4970       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4971                       ISD::SIGN_EXTEND);
4972       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4973     }
4974   }
4975
4976   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4977   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4978   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4979       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4980     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4981     EVT MemVT = LN0->getMemoryVT();
4982     if ((!LegalOperations && !LN0->isVolatile()) ||
4983         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4984       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4985                                        LN0->getChain(),
4986                                        LN0->getBasePtr(), MemVT,
4987                                        LN0->getMemOperand());
4988       CombineTo(N, ExtLoad);
4989       CombineTo(N0.getNode(),
4990                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4991                             N0.getValueType(), ExtLoad),
4992                 ExtLoad.getValue(1));
4993       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4994     }
4995   }
4996
4997   // fold (sext (and/or/xor (load x), cst)) ->
4998   //      (and/or/xor (sextload x), (sext cst))
4999   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5000        N0.getOpcode() == ISD::XOR) &&
5001       isa<LoadSDNode>(N0.getOperand(0)) &&
5002       N0.getOperand(1).getOpcode() == ISD::Constant &&
5003       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5004       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5005     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5006     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5007       bool DoXform = true;
5008       SmallVector<SDNode*, 4> SetCCs;
5009       if (!N0.hasOneUse())
5010         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5011                                           SetCCs, TLI);
5012       if (DoXform) {
5013         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5014                                          LN0->getChain(), LN0->getBasePtr(),
5015                                          LN0->getMemoryVT(),
5016                                          LN0->getMemOperand());
5017         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5018         Mask = Mask.sext(VT.getSizeInBits());
5019         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5020                                   ExtLoad, DAG.getConstant(Mask, VT));
5021         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5022                                     SDLoc(N0.getOperand(0)),
5023                                     N0.getOperand(0).getValueType(), ExtLoad);
5024         CombineTo(N, And);
5025         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5026         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5027                         ISD::SIGN_EXTEND);
5028         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5029       }
5030     }
5031   }
5032
5033   if (N0.getOpcode() == ISD::SETCC) {
5034     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5035     // Only do this before legalize for now.
5036     if (VT.isVector() && !LegalOperations &&
5037         TLI.getBooleanContents(true) ==
5038           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5039       EVT N0VT = N0.getOperand(0).getValueType();
5040       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5041       // of the same size as the compared operands. Only optimize sext(setcc())
5042       // if this is the case.
5043       EVT SVT = getSetCCResultType(N0VT);
5044
5045       // We know that the # elements of the results is the same as the
5046       // # elements of the compare (and the # elements of the compare result
5047       // for that matter).  Check to see that they are the same size.  If so,
5048       // we know that the element size of the sext'd result matches the
5049       // element size of the compare operands.
5050       if (VT.getSizeInBits() == SVT.getSizeInBits())
5051         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5052                              N0.getOperand(1),
5053                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5054
5055       // If the desired elements are smaller or larger than the source
5056       // elements we can use a matching integer vector type and then
5057       // truncate/sign extend
5058       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5059       if (SVT == MatchingVectorType) {
5060         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5061                                N0.getOperand(0), N0.getOperand(1),
5062                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5063         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5064       }
5065     }
5066
5067     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5068     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5069     SDValue NegOne =
5070       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5071     SDValue SCC =
5072       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5073                        NegOne, DAG.getConstant(0, VT),
5074                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5075     if (SCC.getNode()) return SCC;
5076
5077     if (!VT.isVector()) {
5078       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5079       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5080         SDLoc DL(N);
5081         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5082         SDValue SetCC = DAG.getSetCC(DL,
5083                                      SetCCVT,
5084                                      N0.getOperand(0), N0.getOperand(1), CC);
5085         EVT SelectVT = getSetCCResultType(VT);
5086         return DAG.getSelect(DL, VT,
5087                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5088                              NegOne, DAG.getConstant(0, VT));
5089
5090       }
5091     }
5092   }
5093
5094   // fold (sext x) -> (zext x) if the sign bit is known zero.
5095   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5096       DAG.SignBitIsZero(N0))
5097     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5098
5099   return SDValue();
5100 }
5101
5102 // isTruncateOf - If N is a truncate of some other value, return true, record
5103 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5104 // This function computes KnownZero to avoid a duplicated call to
5105 // ComputeMaskedBits in the caller.
5106 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5107                          APInt &KnownZero) {
5108   APInt KnownOne;
5109   if (N->getOpcode() == ISD::TRUNCATE) {
5110     Op = N->getOperand(0);
5111     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5112     return true;
5113   }
5114
5115   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5116       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5117     return false;
5118
5119   SDValue Op0 = N->getOperand(0);
5120   SDValue Op1 = N->getOperand(1);
5121   assert(Op0.getValueType() == Op1.getValueType());
5122
5123   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5124   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5125   if (COp0 && COp0->isNullValue())
5126     Op = Op1;
5127   else if (COp1 && COp1->isNullValue())
5128     Op = Op0;
5129   else
5130     return false;
5131
5132   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5133
5134   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5135     return false;
5136
5137   return true;
5138 }
5139
5140 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5141   SDValue N0 = N->getOperand(0);
5142   EVT VT = N->getValueType(0);
5143
5144   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5145                                               LegalOperations))
5146     return SDValue(Res, 0);
5147
5148   // fold (zext (zext x)) -> (zext x)
5149   // fold (zext (aext x)) -> (zext x)
5150   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5151     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5152                        N0.getOperand(0));
5153
5154   // fold (zext (truncate x)) -> (zext x) or
5155   //      (zext (truncate x)) -> (truncate x)
5156   // This is valid when the truncated bits of x are already zero.
5157   // FIXME: We should extend this to work for vectors too.
5158   SDValue Op;
5159   APInt KnownZero;
5160   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5161     APInt TruncatedBits =
5162       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5163       APInt(Op.getValueSizeInBits(), 0) :
5164       APInt::getBitsSet(Op.getValueSizeInBits(),
5165                         N0.getValueSizeInBits(),
5166                         std::min(Op.getValueSizeInBits(),
5167                                  VT.getSizeInBits()));
5168     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5169       if (VT.bitsGT(Op.getValueType()))
5170         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5171       if (VT.bitsLT(Op.getValueType()))
5172         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5173
5174       return Op;
5175     }
5176   }
5177
5178   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5179   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5180   if (N0.getOpcode() == ISD::TRUNCATE) {
5181     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5182     if (NarrowLoad.getNode()) {
5183       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5184       if (NarrowLoad.getNode() != N0.getNode()) {
5185         CombineTo(N0.getNode(), NarrowLoad);
5186         // CombineTo deleted the truncate, if needed, but not what's under it.
5187         AddToWorkList(oye);
5188       }
5189       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5190     }
5191   }
5192
5193   // fold (zext (truncate x)) -> (and x, mask)
5194   if (N0.getOpcode() == ISD::TRUNCATE &&
5195       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5196
5197     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5198     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5199     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5200     if (NarrowLoad.getNode()) {
5201       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5202       if (NarrowLoad.getNode() != N0.getNode()) {
5203         CombineTo(N0.getNode(), NarrowLoad);
5204         // CombineTo deleted the truncate, if needed, but not what's under it.
5205         AddToWorkList(oye);
5206       }
5207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5208     }
5209
5210     SDValue Op = N0.getOperand(0);
5211     if (Op.getValueType().bitsLT(VT)) {
5212       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5213       AddToWorkList(Op.getNode());
5214     } else if (Op.getValueType().bitsGT(VT)) {
5215       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5216       AddToWorkList(Op.getNode());
5217     }
5218     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5219                                   N0.getValueType().getScalarType());
5220   }
5221
5222   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5223   // if either of the casts is not free.
5224   if (N0.getOpcode() == ISD::AND &&
5225       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5226       N0.getOperand(1).getOpcode() == ISD::Constant &&
5227       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5228                            N0.getValueType()) ||
5229        !TLI.isZExtFree(N0.getValueType(), VT))) {
5230     SDValue X = N0.getOperand(0).getOperand(0);
5231     if (X.getValueType().bitsLT(VT)) {
5232       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5233     } else if (X.getValueType().bitsGT(VT)) {
5234       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5235     }
5236     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5237     Mask = Mask.zext(VT.getSizeInBits());
5238     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5239                        X, DAG.getConstant(Mask, VT));
5240   }
5241
5242   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5243   // None of the supported targets knows how to perform load and vector_zext
5244   // on vectors in one instruction.  We only perform this transformation on
5245   // scalars.
5246   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5247       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5248       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5249        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5250     bool DoXform = true;
5251     SmallVector<SDNode*, 4> SetCCs;
5252     if (!N0.hasOneUse())
5253       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5254     if (DoXform) {
5255       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5256       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5257                                        LN0->getChain(),
5258                                        LN0->getBasePtr(), N0.getValueType(),
5259                                        LN0->getMemOperand());
5260       CombineTo(N, ExtLoad);
5261       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5262                                   N0.getValueType(), ExtLoad);
5263       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5264
5265       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5266                       ISD::ZERO_EXTEND);
5267       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5268     }
5269   }
5270
5271   // fold (zext (and/or/xor (load x), cst)) ->
5272   //      (and/or/xor (zextload x), (zext cst))
5273   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5274        N0.getOpcode() == ISD::XOR) &&
5275       isa<LoadSDNode>(N0.getOperand(0)) &&
5276       N0.getOperand(1).getOpcode() == ISD::Constant &&
5277       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5278       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5279     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5280     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5281       bool DoXform = true;
5282       SmallVector<SDNode*, 4> SetCCs;
5283       if (!N0.hasOneUse())
5284         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5285                                           SetCCs, TLI);
5286       if (DoXform) {
5287         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5288                                          LN0->getChain(), LN0->getBasePtr(),
5289                                          LN0->getMemoryVT(),
5290                                          LN0->getMemOperand());
5291         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5292         Mask = Mask.zext(VT.getSizeInBits());
5293         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5294                                   ExtLoad, DAG.getConstant(Mask, VT));
5295         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5296                                     SDLoc(N0.getOperand(0)),
5297                                     N0.getOperand(0).getValueType(), ExtLoad);
5298         CombineTo(N, And);
5299         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5300         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5301                         ISD::ZERO_EXTEND);
5302         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5303       }
5304     }
5305   }
5306
5307   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5308   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5309   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5310       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5311     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5312     EVT MemVT = LN0->getMemoryVT();
5313     if ((!LegalOperations && !LN0->isVolatile()) ||
5314         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5315       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5316                                        LN0->getChain(),
5317                                        LN0->getBasePtr(), MemVT,
5318                                        LN0->getMemOperand());
5319       CombineTo(N, ExtLoad);
5320       CombineTo(N0.getNode(),
5321                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5322                             ExtLoad),
5323                 ExtLoad.getValue(1));
5324       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5325     }
5326   }
5327
5328   if (N0.getOpcode() == ISD::SETCC) {
5329     if (!LegalOperations && VT.isVector() &&
5330         N0.getValueType().getVectorElementType() == MVT::i1) {
5331       EVT N0VT = N0.getOperand(0).getValueType();
5332       if (getSetCCResultType(N0VT) == N0.getValueType())
5333         return SDValue();
5334
5335       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5336       // Only do this before legalize for now.
5337       EVT EltVT = VT.getVectorElementType();
5338       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5339                                     DAG.getConstant(1, EltVT));
5340       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5341         // We know that the # elements of the results is the same as the
5342         // # elements of the compare (and the # elements of the compare result
5343         // for that matter).  Check to see that they are the same size.  If so,
5344         // we know that the element size of the sext'd result matches the
5345         // element size of the compare operands.
5346         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5347                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5348                                          N0.getOperand(1),
5349                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5350                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5351                                        &OneOps[0], OneOps.size()));
5352
5353       // If the desired elements are smaller or larger than the source
5354       // elements we can use a matching integer vector type and then
5355       // truncate/sign extend
5356       EVT MatchingElementType =
5357         EVT::getIntegerVT(*DAG.getContext(),
5358                           N0VT.getScalarType().getSizeInBits());
5359       EVT MatchingVectorType =
5360         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5361                          N0VT.getVectorNumElements());
5362       SDValue VsetCC =
5363         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5364                       N0.getOperand(1),
5365                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5366       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5367                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5368                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5369                                      &OneOps[0], OneOps.size()));
5370     }
5371
5372     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5373     SDValue SCC =
5374       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5375                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5376                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5377     if (SCC.getNode()) return SCC;
5378   }
5379
5380   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5381   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5382       isa<ConstantSDNode>(N0.getOperand(1)) &&
5383       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5384       N0.hasOneUse()) {
5385     SDValue ShAmt = N0.getOperand(1);
5386     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5387     if (N0.getOpcode() == ISD::SHL) {
5388       SDValue InnerZExt = N0.getOperand(0);
5389       // If the original shl may be shifting out bits, do not perform this
5390       // transformation.
5391       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5392         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5393       if (ShAmtVal > KnownZeroBits)
5394         return SDValue();
5395     }
5396
5397     SDLoc DL(N);
5398
5399     // Ensure that the shift amount is wide enough for the shifted value.
5400     if (VT.getSizeInBits() >= 256)
5401       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5402
5403     return DAG.getNode(N0.getOpcode(), DL, VT,
5404                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5405                        ShAmt);
5406   }
5407
5408   return SDValue();
5409 }
5410
5411 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5412   SDValue N0 = N->getOperand(0);
5413   EVT VT = N->getValueType(0);
5414
5415   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5416                                               LegalOperations))
5417     return SDValue(Res, 0);
5418
5419   // fold (aext (aext x)) -> (aext x)
5420   // fold (aext (zext x)) -> (zext x)
5421   // fold (aext (sext x)) -> (sext x)
5422   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5423       N0.getOpcode() == ISD::ZERO_EXTEND ||
5424       N0.getOpcode() == ISD::SIGN_EXTEND)
5425     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5426
5427   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5428   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5429   if (N0.getOpcode() == ISD::TRUNCATE) {
5430     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5431     if (NarrowLoad.getNode()) {
5432       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5433       if (NarrowLoad.getNode() != N0.getNode()) {
5434         CombineTo(N0.getNode(), NarrowLoad);
5435         // CombineTo deleted the truncate, if needed, but not what's under it.
5436         AddToWorkList(oye);
5437       }
5438       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5439     }
5440   }
5441
5442   // fold (aext (truncate x))
5443   if (N0.getOpcode() == ISD::TRUNCATE) {
5444     SDValue TruncOp = N0.getOperand(0);
5445     if (TruncOp.getValueType() == VT)
5446       return TruncOp; // x iff x size == zext size.
5447     if (TruncOp.getValueType().bitsGT(VT))
5448       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5449     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5450   }
5451
5452   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5453   // if the trunc is not free.
5454   if (N0.getOpcode() == ISD::AND &&
5455       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5456       N0.getOperand(1).getOpcode() == ISD::Constant &&
5457       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5458                           N0.getValueType())) {
5459     SDValue X = N0.getOperand(0).getOperand(0);
5460     if (X.getValueType().bitsLT(VT)) {
5461       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5462     } else if (X.getValueType().bitsGT(VT)) {
5463       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5464     }
5465     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5466     Mask = Mask.zext(VT.getSizeInBits());
5467     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5468                        X, DAG.getConstant(Mask, VT));
5469   }
5470
5471   // fold (aext (load x)) -> (aext (truncate (extload x)))
5472   // None of the supported targets knows how to perform load and any_ext
5473   // on vectors in one instruction.  We only perform this transformation on
5474   // scalars.
5475   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5476       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5477       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5478        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5479     bool DoXform = true;
5480     SmallVector<SDNode*, 4> SetCCs;
5481     if (!N0.hasOneUse())
5482       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5483     if (DoXform) {
5484       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5485       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5486                                        LN0->getChain(),
5487                                        LN0->getBasePtr(), N0.getValueType(),
5488                                        LN0->getMemOperand());
5489       CombineTo(N, ExtLoad);
5490       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5491                                   N0.getValueType(), ExtLoad);
5492       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5493       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5494                       ISD::ANY_EXTEND);
5495       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5496     }
5497   }
5498
5499   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5500   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5501   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5502   if (N0.getOpcode() == ISD::LOAD &&
5503       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5504       N0.hasOneUse()) {
5505     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5506     ISD::LoadExtType ExtType = LN0->getExtensionType();
5507     EVT MemVT = LN0->getMemoryVT();
5508     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5509       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5510                                        VT, LN0->getChain(), LN0->getBasePtr(),
5511                                        MemVT, LN0->getMemOperand());
5512       CombineTo(N, ExtLoad);
5513       CombineTo(N0.getNode(),
5514                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5515                             N0.getValueType(), ExtLoad),
5516                 ExtLoad.getValue(1));
5517       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5518     }
5519   }
5520
5521   if (N0.getOpcode() == ISD::SETCC) {
5522     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5523     // Only do this before legalize for now.
5524     if (VT.isVector() && !LegalOperations) {
5525       EVT N0VT = N0.getOperand(0).getValueType();
5526         // We know that the # elements of the results is the same as the
5527         // # elements of the compare (and the # elements of the compare result
5528         // for that matter).  Check to see that they are the same size.  If so,
5529         // we know that the element size of the sext'd result matches the
5530         // element size of the compare operands.
5531       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5532         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5533                              N0.getOperand(1),
5534                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5535       // If the desired elements are smaller or larger than the source
5536       // elements we can use a matching integer vector type and then
5537       // truncate/sign extend
5538       else {
5539         EVT MatchingElementType =
5540           EVT::getIntegerVT(*DAG.getContext(),
5541                             N0VT.getScalarType().getSizeInBits());
5542         EVT MatchingVectorType =
5543           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5544                            N0VT.getVectorNumElements());
5545         SDValue VsetCC =
5546           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5547                         N0.getOperand(1),
5548                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5549         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5550       }
5551     }
5552
5553     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5554     SDValue SCC =
5555       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5556                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5557                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5558     if (SCC.getNode())
5559       return SCC;
5560   }
5561
5562   return SDValue();
5563 }
5564
5565 /// GetDemandedBits - See if the specified operand can be simplified with the
5566 /// knowledge that only the bits specified by Mask are used.  If so, return the
5567 /// simpler operand, otherwise return a null SDValue.
5568 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5569   switch (V.getOpcode()) {
5570   default: break;
5571   case ISD::Constant: {
5572     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5573     assert(CV != 0 && "Const value should be ConstSDNode.");
5574     const APInt &CVal = CV->getAPIntValue();
5575     APInt NewVal = CVal & Mask;
5576     if (NewVal != CVal)
5577       return DAG.getConstant(NewVal, V.getValueType());
5578     break;
5579   }
5580   case ISD::OR:
5581   case ISD::XOR:
5582     // If the LHS or RHS don't contribute bits to the or, drop them.
5583     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5584       return V.getOperand(1);
5585     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5586       return V.getOperand(0);
5587     break;
5588   case ISD::SRL:
5589     // Only look at single-use SRLs.
5590     if (!V.getNode()->hasOneUse())
5591       break;
5592     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5593       // See if we can recursively simplify the LHS.
5594       unsigned Amt = RHSC->getZExtValue();
5595
5596       // Watch out for shift count overflow though.
5597       if (Amt >= Mask.getBitWidth()) break;
5598       APInt NewMask = Mask << Amt;
5599       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5600       if (SimplifyLHS.getNode())
5601         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5602                            SimplifyLHS, V.getOperand(1));
5603     }
5604   }
5605   return SDValue();
5606 }
5607
5608 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5609 /// bits and then truncated to a narrower type and where N is a multiple
5610 /// of number of bits of the narrower type, transform it to a narrower load
5611 /// from address + N / num of bits of new type. If the result is to be
5612 /// extended, also fold the extension to form a extending load.
5613 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5614   unsigned Opc = N->getOpcode();
5615
5616   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5617   SDValue N0 = N->getOperand(0);
5618   EVT VT = N->getValueType(0);
5619   EVT ExtVT = VT;
5620
5621   // This transformation isn't valid for vector loads.
5622   if (VT.isVector())
5623     return SDValue();
5624
5625   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5626   // extended to VT.
5627   if (Opc == ISD::SIGN_EXTEND_INREG) {
5628     ExtType = ISD::SEXTLOAD;
5629     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5630   } else if (Opc == ISD::SRL) {
5631     // Another special-case: SRL is basically zero-extending a narrower value.
5632     ExtType = ISD::ZEXTLOAD;
5633     N0 = SDValue(N, 0);
5634     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5635     if (!N01) return SDValue();
5636     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5637                               VT.getSizeInBits() - N01->getZExtValue());
5638   }
5639   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5640     return SDValue();
5641
5642   unsigned EVTBits = ExtVT.getSizeInBits();
5643
5644   // Do not generate loads of non-round integer types since these can
5645   // be expensive (and would be wrong if the type is not byte sized).
5646   if (!ExtVT.isRound())
5647     return SDValue();
5648
5649   unsigned ShAmt = 0;
5650   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5651     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5652       ShAmt = N01->getZExtValue();
5653       // Is the shift amount a multiple of size of VT?
5654       if ((ShAmt & (EVTBits-1)) == 0) {
5655         N0 = N0.getOperand(0);
5656         // Is the load width a multiple of size of VT?
5657         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5658           return SDValue();
5659       }
5660
5661       // At this point, we must have a load or else we can't do the transform.
5662       if (!isa<LoadSDNode>(N0)) return SDValue();
5663
5664       // Because a SRL must be assumed to *need* to zero-extend the high bits
5665       // (as opposed to anyext the high bits), we can't combine the zextload
5666       // lowering of SRL and an sextload.
5667       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5668         return SDValue();
5669
5670       // If the shift amount is larger than the input type then we're not
5671       // accessing any of the loaded bytes.  If the load was a zextload/extload
5672       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5673       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5674         return SDValue();
5675     }
5676   }
5677
5678   // If the load is shifted left (and the result isn't shifted back right),
5679   // we can fold the truncate through the shift.
5680   unsigned ShLeftAmt = 0;
5681   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5682       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5683     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5684       ShLeftAmt = N01->getZExtValue();
5685       N0 = N0.getOperand(0);
5686     }
5687   }
5688
5689   // If we haven't found a load, we can't narrow it.  Don't transform one with
5690   // multiple uses, this would require adding a new load.
5691   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5692     return SDValue();
5693
5694   // Don't change the width of a volatile load.
5695   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5696   if (LN0->isVolatile())
5697     return SDValue();
5698
5699   // Verify that we are actually reducing a load width here.
5700   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5701     return SDValue();
5702
5703   // For the transform to be legal, the load must produce only two values
5704   // (the value loaded and the chain).  Don't transform a pre-increment
5705   // load, for example, which produces an extra value.  Otherwise the
5706   // transformation is not equivalent, and the downstream logic to replace
5707   // uses gets things wrong.
5708   if (LN0->getNumValues() > 2)
5709     return SDValue();
5710
5711   // If the load that we're shrinking is an extload and we're not just
5712   // discarding the extension we can't simply shrink the load. Bail.
5713   // TODO: It would be possible to merge the extensions in some cases.
5714   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5715       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5716     return SDValue();
5717
5718   EVT PtrType = N0.getOperand(1).getValueType();
5719
5720   if (PtrType == MVT::Untyped || PtrType.isExtended())
5721     // It's not possible to generate a constant of extended or untyped type.
5722     return SDValue();
5723
5724   // For big endian targets, we need to adjust the offset to the pointer to
5725   // load the correct bytes.
5726   if (TLI.isBigEndian()) {
5727     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5728     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5729     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5730   }
5731
5732   uint64_t PtrOff = ShAmt / 8;
5733   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5734   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5735                                PtrType, LN0->getBasePtr(),
5736                                DAG.getConstant(PtrOff, PtrType));
5737   AddToWorkList(NewPtr.getNode());
5738
5739   SDValue Load;
5740   if (ExtType == ISD::NON_EXTLOAD)
5741     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5742                         LN0->getPointerInfo().getWithOffset(PtrOff),
5743                         LN0->isVolatile(), LN0->isNonTemporal(),
5744                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5745   else
5746     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5747                           LN0->getPointerInfo().getWithOffset(PtrOff),
5748                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5749                           NewAlign, LN0->getTBAAInfo());
5750
5751   // Replace the old load's chain with the new load's chain.
5752   WorkListRemover DeadNodes(*this);
5753   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5754
5755   // Shift the result left, if we've swallowed a left shift.
5756   SDValue Result = Load;
5757   if (ShLeftAmt != 0) {
5758     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5759     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5760       ShImmTy = VT;
5761     // If the shift amount is as large as the result size (but, presumably,
5762     // no larger than the source) then the useful bits of the result are
5763     // zero; we can't simply return the shortened shift, because the result
5764     // of that operation is undefined.
5765     if (ShLeftAmt >= VT.getSizeInBits())
5766       Result = DAG.getConstant(0, VT);
5767     else
5768       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5769                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5770   }
5771
5772   // Return the new loaded value.
5773   return Result;
5774 }
5775
5776 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5777   SDValue N0 = N->getOperand(0);
5778   SDValue N1 = N->getOperand(1);
5779   EVT VT = N->getValueType(0);
5780   EVT EVT = cast<VTSDNode>(N1)->getVT();
5781   unsigned VTBits = VT.getScalarType().getSizeInBits();
5782   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5783
5784   // fold (sext_in_reg c1) -> c1
5785   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5786     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5787
5788   // If the input is already sign extended, just drop the extension.
5789   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5790     return N0;
5791
5792   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5793   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5794       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5795     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5796                        N0.getOperand(0), N1);
5797
5798   // fold (sext_in_reg (sext x)) -> (sext x)
5799   // fold (sext_in_reg (aext x)) -> (sext x)
5800   // if x is small enough.
5801   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5802     SDValue N00 = N0.getOperand(0);
5803     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5804         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5805       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5806   }
5807
5808   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5809   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5810     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5811
5812   // fold operands of sext_in_reg based on knowledge that the top bits are not
5813   // demanded.
5814   if (SimplifyDemandedBits(SDValue(N, 0)))
5815     return SDValue(N, 0);
5816
5817   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5818   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5819   SDValue NarrowLoad = ReduceLoadWidth(N);
5820   if (NarrowLoad.getNode())
5821     return NarrowLoad;
5822
5823   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5824   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5825   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5826   if (N0.getOpcode() == ISD::SRL) {
5827     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5828       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5829         // We can turn this into an SRA iff the input to the SRL is already sign
5830         // extended enough.
5831         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5832         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5833           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5834                              N0.getOperand(0), N0.getOperand(1));
5835       }
5836   }
5837
5838   // fold (sext_inreg (extload x)) -> (sextload x)
5839   if (ISD::isEXTLoad(N0.getNode()) &&
5840       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5841       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5842       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5843        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5844     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5845     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5846                                      LN0->getChain(),
5847                                      LN0->getBasePtr(), EVT,
5848                                      LN0->getMemOperand());
5849     CombineTo(N, ExtLoad);
5850     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5851     AddToWorkList(ExtLoad.getNode());
5852     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5853   }
5854   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5855   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5856       N0.hasOneUse() &&
5857       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5858       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5859        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5860     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5862                                      LN0->getChain(),
5863                                      LN0->getBasePtr(), EVT,
5864                                      LN0->getMemOperand());
5865     CombineTo(N, ExtLoad);
5866     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5867     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5868   }
5869
5870   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5871   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5872     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5873                                        N0.getOperand(1), false);
5874     if (BSwap.getNode() != 0)
5875       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5876                          BSwap, N1);
5877   }
5878
5879   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5880   // into a build_vector.
5881   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5882     SmallVector<SDValue, 8> Elts;
5883     unsigned NumElts = N0->getNumOperands();
5884     unsigned ShAmt = VTBits - EVTBits;
5885
5886     for (unsigned i = 0; i != NumElts; ++i) {
5887       SDValue Op = N0->getOperand(i);
5888       if (Op->getOpcode() == ISD::UNDEF) {
5889         Elts.push_back(Op);
5890         continue;
5891       }
5892
5893       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5894       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5895       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5896                                      Op.getValueType()));
5897     }
5898
5899     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5900   }
5901
5902   return SDValue();
5903 }
5904
5905 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5906   SDValue N0 = N->getOperand(0);
5907   EVT VT = N->getValueType(0);
5908   bool isLE = TLI.isLittleEndian();
5909
5910   // noop truncate
5911   if (N0.getValueType() == N->getValueType(0))
5912     return N0;
5913   // fold (truncate c1) -> c1
5914   if (isa<ConstantSDNode>(N0))
5915     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5916   // fold (truncate (truncate x)) -> (truncate x)
5917   if (N0.getOpcode() == ISD::TRUNCATE)
5918     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5919   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5920   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5921       N0.getOpcode() == ISD::SIGN_EXTEND ||
5922       N0.getOpcode() == ISD::ANY_EXTEND) {
5923     if (N0.getOperand(0).getValueType().bitsLT(VT))
5924       // if the source is smaller than the dest, we still need an extend
5925       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5926                          N0.getOperand(0));
5927     if (N0.getOperand(0).getValueType().bitsGT(VT))
5928       // if the source is larger than the dest, than we just need the truncate
5929       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5930     // if the source and dest are the same type, we can drop both the extend
5931     // and the truncate.
5932     return N0.getOperand(0);
5933   }
5934
5935   // Fold extract-and-trunc into a narrow extract. For example:
5936   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5937   //   i32 y = TRUNCATE(i64 x)
5938   //        -- becomes --
5939   //   v16i8 b = BITCAST (v2i64 val)
5940   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5941   //
5942   // Note: We only run this optimization after type legalization (which often
5943   // creates this pattern) and before operation legalization after which
5944   // we need to be more careful about the vector instructions that we generate.
5945   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5946       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5947
5948     EVT VecTy = N0.getOperand(0).getValueType();
5949     EVT ExTy = N0.getValueType();
5950     EVT TrTy = N->getValueType(0);
5951
5952     unsigned NumElem = VecTy.getVectorNumElements();
5953     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5954
5955     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5956     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5957
5958     SDValue EltNo = N0->getOperand(1);
5959     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5960       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5961       EVT IndexTy = TLI.getVectorIdxTy();
5962       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5963
5964       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5965                               NVT, N0.getOperand(0));
5966
5967       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5968                          SDLoc(N), TrTy, V,
5969                          DAG.getConstant(Index, IndexTy));
5970     }
5971   }
5972
5973   // Fold a series of buildvector, bitcast, and truncate if possible.
5974   // For example fold
5975   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5976   //   (2xi32 (buildvector x, y)).
5977   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5978       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5979       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5980       N0.getOperand(0).hasOneUse()) {
5981
5982     SDValue BuildVect = N0.getOperand(0);
5983     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5984     EVT TruncVecEltTy = VT.getVectorElementType();
5985
5986     // Check that the element types match.
5987     if (BuildVectEltTy == TruncVecEltTy) {
5988       // Now we only need to compute the offset of the truncated elements.
5989       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5990       unsigned TruncVecNumElts = VT.getVectorNumElements();
5991       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5992
5993       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5994              "Invalid number of elements");
5995
5996       SmallVector<SDValue, 8> Opnds;
5997       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5998         Opnds.push_back(BuildVect.getOperand(i));
5999
6000       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6001                          Opnds.size());
6002     }
6003   }
6004
6005   // See if we can simplify the input to this truncate through knowledge that
6006   // only the low bits are being used.
6007   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6008   // Currently we only perform this optimization on scalars because vectors
6009   // may have different active low bits.
6010   if (!VT.isVector()) {
6011     SDValue Shorter =
6012       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6013                                                VT.getSizeInBits()));
6014     if (Shorter.getNode())
6015       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6016   }
6017   // fold (truncate (load x)) -> (smaller load x)
6018   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6019   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6020     SDValue Reduced = ReduceLoadWidth(N);
6021     if (Reduced.getNode())
6022       return Reduced;
6023     // Handle the case where the load remains an extending load even
6024     // after truncation.
6025     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6026       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6027       if (!LN0->isVolatile() &&
6028           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6029         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6030                                          VT, LN0->getChain(), LN0->getBasePtr(),
6031                                          LN0->getMemoryVT(),
6032                                          LN0->getMemOperand());
6033         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6034         return NewLoad;
6035       }
6036     }
6037   }
6038   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6039   // where ... are all 'undef'.
6040   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6041     SmallVector<EVT, 8> VTs;
6042     SDValue V;
6043     unsigned Idx = 0;
6044     unsigned NumDefs = 0;
6045
6046     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6047       SDValue X = N0.getOperand(i);
6048       if (X.getOpcode() != ISD::UNDEF) {
6049         V = X;
6050         Idx = i;
6051         NumDefs++;
6052       }
6053       // Stop if more than one members are non-undef.
6054       if (NumDefs > 1)
6055         break;
6056       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6057                                      VT.getVectorElementType(),
6058                                      X.getValueType().getVectorNumElements()));
6059     }
6060
6061     if (NumDefs == 0)
6062       return DAG.getUNDEF(VT);
6063
6064     if (NumDefs == 1) {
6065       assert(V.getNode() && "The single defined operand is empty!");
6066       SmallVector<SDValue, 8> Opnds;
6067       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6068         if (i != Idx) {
6069           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6070           continue;
6071         }
6072         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6073         AddToWorkList(NV.getNode());
6074         Opnds.push_back(NV);
6075       }
6076       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6077                          &Opnds[0], Opnds.size());
6078     }
6079   }
6080
6081   // Simplify the operands using demanded-bits information.
6082   if (!VT.isVector() &&
6083       SimplifyDemandedBits(SDValue(N, 0)))
6084     return SDValue(N, 0);
6085
6086   return SDValue();
6087 }
6088
6089 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6090   SDValue Elt = N->getOperand(i);
6091   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6092     return Elt.getNode();
6093   return Elt.getOperand(Elt.getResNo()).getNode();
6094 }
6095
6096 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6097 /// if load locations are consecutive.
6098 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6099   assert(N->getOpcode() == ISD::BUILD_PAIR);
6100
6101   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6102   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6103   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6104       LD1->getAddressSpace() != LD2->getAddressSpace())
6105     return SDValue();
6106   EVT LD1VT = LD1->getValueType(0);
6107
6108   if (ISD::isNON_EXTLoad(LD2) &&
6109       LD2->hasOneUse() &&
6110       // If both are volatile this would reduce the number of volatile loads.
6111       // If one is volatile it might be ok, but play conservative and bail out.
6112       !LD1->isVolatile() &&
6113       !LD2->isVolatile() &&
6114       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6115     unsigned Align = LD1->getAlignment();
6116     unsigned NewAlign = TLI.getDataLayout()->
6117       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6118
6119     if (NewAlign <= Align &&
6120         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6121       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6122                          LD1->getBasePtr(), LD1->getPointerInfo(),
6123                          false, false, false, Align);
6124   }
6125
6126   return SDValue();
6127 }
6128
6129 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6130   SDValue N0 = N->getOperand(0);
6131   EVT VT = N->getValueType(0);
6132
6133   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6134   // Only do this before legalize, since afterward the target may be depending
6135   // on the bitconvert.
6136   // First check to see if this is all constant.
6137   if (!LegalTypes &&
6138       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6139       VT.isVector()) {
6140     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6141
6142     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6143     assert(!DestEltVT.isVector() &&
6144            "Element type of vector ValueType must not be vector!");
6145     if (isSimple)
6146       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6147   }
6148
6149   // If the input is a constant, let getNode fold it.
6150   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6151     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6152     if (Res.getNode() != N) {
6153       if (!LegalOperations ||
6154           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6155         return Res;
6156
6157       // Folding it resulted in an illegal node, and it's too late to
6158       // do that. Clean up the old node and forego the transformation.
6159       // Ideally this won't happen very often, because instcombine
6160       // and the earlier dagcombine runs (where illegal nodes are
6161       // permitted) should have folded most of them already.
6162       DAG.DeleteNode(Res.getNode());
6163     }
6164   }
6165
6166   // (conv (conv x, t1), t2) -> (conv x, t2)
6167   if (N0.getOpcode() == ISD::BITCAST)
6168     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6169                        N0.getOperand(0));
6170
6171   // fold (conv (load x)) -> (load (conv*)x)
6172   // If the resultant load doesn't need a higher alignment than the original!
6173   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6174       // Do not change the width of a volatile load.
6175       !cast<LoadSDNode>(N0)->isVolatile() &&
6176       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6177       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6178     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6179     unsigned Align = TLI.getDataLayout()->
6180       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6181     unsigned OrigAlign = LN0->getAlignment();
6182
6183     if (Align <= OrigAlign) {
6184       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6185                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6186                                  LN0->isVolatile(), LN0->isNonTemporal(),
6187                                  LN0->isInvariant(), OrigAlign,
6188                                  LN0->getTBAAInfo());
6189       AddToWorkList(N);
6190       CombineTo(N0.getNode(),
6191                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6192                             N0.getValueType(), Load),
6193                 Load.getValue(1));
6194       return Load;
6195     }
6196   }
6197
6198   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6199   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6200   // This often reduces constant pool loads.
6201   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6202        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6203       N0.getNode()->hasOneUse() && VT.isInteger() &&
6204       !VT.isVector() && !N0.getValueType().isVector()) {
6205     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6206                                   N0.getOperand(0));
6207     AddToWorkList(NewConv.getNode());
6208
6209     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6210     if (N0.getOpcode() == ISD::FNEG)
6211       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6212                          NewConv, DAG.getConstant(SignBit, VT));
6213     assert(N0.getOpcode() == ISD::FABS);
6214     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6215                        NewConv, DAG.getConstant(~SignBit, VT));
6216   }
6217
6218   // fold (bitconvert (fcopysign cst, x)) ->
6219   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6220   // Note that we don't handle (copysign x, cst) because this can always be
6221   // folded to an fneg or fabs.
6222   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6223       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6224       VT.isInteger() && !VT.isVector()) {
6225     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6226     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6227     if (isTypeLegal(IntXVT)) {
6228       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6229                               IntXVT, N0.getOperand(1));
6230       AddToWorkList(X.getNode());
6231
6232       // If X has a different width than the result/lhs, sext it or truncate it.
6233       unsigned VTWidth = VT.getSizeInBits();
6234       if (OrigXWidth < VTWidth) {
6235         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6236         AddToWorkList(X.getNode());
6237       } else if (OrigXWidth > VTWidth) {
6238         // To get the sign bit in the right place, we have to shift it right
6239         // before truncating.
6240         X = DAG.getNode(ISD::SRL, SDLoc(X),
6241                         X.getValueType(), X,
6242                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6243         AddToWorkList(X.getNode());
6244         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6245         AddToWorkList(X.getNode());
6246       }
6247
6248       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6249       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6250                       X, DAG.getConstant(SignBit, VT));
6251       AddToWorkList(X.getNode());
6252
6253       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6254                                 VT, N0.getOperand(0));
6255       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6256                         Cst, DAG.getConstant(~SignBit, VT));
6257       AddToWorkList(Cst.getNode());
6258
6259       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6260     }
6261   }
6262
6263   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6264   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6265     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6266     if (CombineLD.getNode())
6267       return CombineLD;
6268   }
6269
6270   return SDValue();
6271 }
6272
6273 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6274   EVT VT = N->getValueType(0);
6275   return CombineConsecutiveLoads(N, VT);
6276 }
6277
6278 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6279 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6280 /// destination element value type.
6281 SDValue DAGCombiner::
6282 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6283   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6284
6285   // If this is already the right type, we're done.
6286   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6287
6288   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6289   unsigned DstBitSize = DstEltVT.getSizeInBits();
6290
6291   // If this is a conversion of N elements of one type to N elements of another
6292   // type, convert each element.  This handles FP<->INT cases.
6293   if (SrcBitSize == DstBitSize) {
6294     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6295                               BV->getValueType(0).getVectorNumElements());
6296
6297     // Due to the FP element handling below calling this routine recursively,
6298     // we can end up with a scalar-to-vector node here.
6299     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6300       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6301                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6302                                      DstEltVT, BV->getOperand(0)));
6303
6304     SmallVector<SDValue, 8> Ops;
6305     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6306       SDValue Op = BV->getOperand(i);
6307       // If the vector element type is not legal, the BUILD_VECTOR operands
6308       // are promoted and implicitly truncated.  Make that explicit here.
6309       if (Op.getValueType() != SrcEltVT)
6310         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6311       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6312                                 DstEltVT, Op));
6313       AddToWorkList(Ops.back().getNode());
6314     }
6315     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6316                        &Ops[0], Ops.size());
6317   }
6318
6319   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6320   // handle annoying details of growing/shrinking FP values, we convert them to
6321   // int first.
6322   if (SrcEltVT.isFloatingPoint()) {
6323     // Convert the input float vector to a int vector where the elements are the
6324     // same sizes.
6325     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6326     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6327     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6328     SrcEltVT = IntVT;
6329   }
6330
6331   // Now we know the input is an integer vector.  If the output is a FP type,
6332   // convert to integer first, then to FP of the right size.
6333   if (DstEltVT.isFloatingPoint()) {
6334     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6335     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6336     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6337
6338     // Next, convert to FP elements of the same size.
6339     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6340   }
6341
6342   // Okay, we know the src/dst types are both integers of differing types.
6343   // Handling growing first.
6344   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6345   if (SrcBitSize < DstBitSize) {
6346     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6347
6348     SmallVector<SDValue, 8> Ops;
6349     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6350          i += NumInputsPerOutput) {
6351       bool isLE = TLI.isLittleEndian();
6352       APInt NewBits = APInt(DstBitSize, 0);
6353       bool EltIsUndef = true;
6354       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6355         // Shift the previously computed bits over.
6356         NewBits <<= SrcBitSize;
6357         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6358         if (Op.getOpcode() == ISD::UNDEF) continue;
6359         EltIsUndef = false;
6360
6361         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6362                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6363       }
6364
6365       if (EltIsUndef)
6366         Ops.push_back(DAG.getUNDEF(DstEltVT));
6367       else
6368         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6369     }
6370
6371     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6372     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6373                        &Ops[0], Ops.size());
6374   }
6375
6376   // Finally, this must be the case where we are shrinking elements: each input
6377   // turns into multiple outputs.
6378   bool isS2V = ISD::isScalarToVector(BV);
6379   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6380   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6381                             NumOutputsPerInput*BV->getNumOperands());
6382   SmallVector<SDValue, 8> Ops;
6383
6384   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6385     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6386       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6387         Ops.push_back(DAG.getUNDEF(DstEltVT));
6388       continue;
6389     }
6390
6391     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6392                   getAPIntValue().zextOrTrunc(SrcBitSize);
6393
6394     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6395       APInt ThisVal = OpVal.trunc(DstBitSize);
6396       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6397       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6398         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6399         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6400                            Ops[0]);
6401       OpVal = OpVal.lshr(DstBitSize);
6402     }
6403
6404     // For big endian targets, swap the order of the pieces of each element.
6405     if (TLI.isBigEndian())
6406       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6407   }
6408
6409   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6410                      &Ops[0], Ops.size());
6411 }
6412
6413 SDValue DAGCombiner::visitFADD(SDNode *N) {
6414   SDValue N0 = N->getOperand(0);
6415   SDValue N1 = N->getOperand(1);
6416   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6417   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6418   EVT VT = N->getValueType(0);
6419
6420   // fold vector ops
6421   if (VT.isVector()) {
6422     SDValue FoldedVOp = SimplifyVBinOp(N);
6423     if (FoldedVOp.getNode()) return FoldedVOp;
6424   }
6425
6426   // fold (fadd c1, c2) -> c1 + c2
6427   if (N0CFP && N1CFP)
6428     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6429   // canonicalize constant to RHS
6430   if (N0CFP && !N1CFP)
6431     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6432   // fold (fadd A, 0) -> A
6433   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6434       N1CFP->getValueAPF().isZero())
6435     return N0;
6436   // fold (fadd A, (fneg B)) -> (fsub A, B)
6437   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6438     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6439     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6440                        GetNegatedExpression(N1, DAG, LegalOperations));
6441   // fold (fadd (fneg A), B) -> (fsub B, A)
6442   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6443     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6444     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6445                        GetNegatedExpression(N0, DAG, LegalOperations));
6446
6447   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6448   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6449       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6450       isa<ConstantFPSDNode>(N0.getOperand(1)))
6451     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6452                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6453                                    N0.getOperand(1), N1));
6454
6455   // No FP constant should be created after legalization as Instruction
6456   // Selection pass has hard time in dealing with FP constant.
6457   //
6458   // We don't need test this condition for transformation like following, as
6459   // the DAG being transformed implies it is legal to take FP constant as
6460   // operand.
6461   //
6462   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6463   //
6464   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6465
6466   // If allow, fold (fadd (fneg x), x) -> 0.0
6467   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6468       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6469     return DAG.getConstantFP(0.0, VT);
6470
6471     // If allow, fold (fadd x, (fneg x)) -> 0.0
6472   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6473       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6474     return DAG.getConstantFP(0.0, VT);
6475
6476   // In unsafe math mode, we can fold chains of FADD's of the same value
6477   // into multiplications.  This transform is not safe in general because
6478   // we are reducing the number of rounding steps.
6479   if (DAG.getTarget().Options.UnsafeFPMath &&
6480       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6481       !N0CFP && !N1CFP) {
6482     if (N0.getOpcode() == ISD::FMUL) {
6483       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6484       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6485
6486       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6487       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6488         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6489                                      SDValue(CFP00, 0),
6490                                      DAG.getConstantFP(1.0, VT));
6491         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6492                            N1, NewCFP);
6493       }
6494
6495       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6496       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6497         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6498                                      SDValue(CFP01, 0),
6499                                      DAG.getConstantFP(1.0, VT));
6500         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6501                            N1, NewCFP);
6502       }
6503
6504       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6505       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6506           N1.getOperand(0) == N1.getOperand(1) &&
6507           N0.getOperand(1) == N1.getOperand(0)) {
6508         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6509                                      SDValue(CFP00, 0),
6510                                      DAG.getConstantFP(2.0, VT));
6511         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6512                            N0.getOperand(1), NewCFP);
6513       }
6514
6515       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6516       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6517           N1.getOperand(0) == N1.getOperand(1) &&
6518           N0.getOperand(0) == N1.getOperand(0)) {
6519         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6520                                      SDValue(CFP01, 0),
6521                                      DAG.getConstantFP(2.0, VT));
6522         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6523                            N0.getOperand(0), NewCFP);
6524       }
6525     }
6526
6527     if (N1.getOpcode() == ISD::FMUL) {
6528       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6529       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6530
6531       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6532       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6533         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6534                                      SDValue(CFP10, 0),
6535                                      DAG.getConstantFP(1.0, VT));
6536         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6537                            N0, NewCFP);
6538       }
6539
6540       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6541       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6542         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6543                                      SDValue(CFP11, 0),
6544                                      DAG.getConstantFP(1.0, VT));
6545         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6546                            N0, NewCFP);
6547       }
6548
6549
6550       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6551       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6552           N0.getOperand(0) == N0.getOperand(1) &&
6553           N1.getOperand(1) == N0.getOperand(0)) {
6554         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6555                                      SDValue(CFP10, 0),
6556                                      DAG.getConstantFP(2.0, VT));
6557         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6558                            N1.getOperand(1), NewCFP);
6559       }
6560
6561       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6562       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6563           N0.getOperand(0) == N0.getOperand(1) &&
6564           N1.getOperand(0) == N0.getOperand(0)) {
6565         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6566                                      SDValue(CFP11, 0),
6567                                      DAG.getConstantFP(2.0, VT));
6568         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6569                            N1.getOperand(0), NewCFP);
6570       }
6571     }
6572
6573     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6574       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6575       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6576       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6577           (N0.getOperand(0) == N1))
6578         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6579                            N1, DAG.getConstantFP(3.0, VT));
6580     }
6581
6582     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6583       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6584       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6585       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6586           N1.getOperand(0) == N0)
6587         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6588                            N0, DAG.getConstantFP(3.0, VT));
6589     }
6590
6591     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6592     if (AllowNewFpConst &&
6593         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6594         N0.getOperand(0) == N0.getOperand(1) &&
6595         N1.getOperand(0) == N1.getOperand(1) &&
6596         N0.getOperand(0) == N1.getOperand(0))
6597       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6598                          N0.getOperand(0),
6599                          DAG.getConstantFP(4.0, VT));
6600   }
6601
6602   // FADD -> FMA combines:
6603   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6604        DAG.getTarget().Options.UnsafeFPMath) &&
6605       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6606       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6607
6608     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6609     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6610       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6611                          N0.getOperand(0), N0.getOperand(1), N1);
6612
6613     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6614     // Note: Commutes FADD operands.
6615     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6616       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6617                          N1.getOperand(0), N1.getOperand(1), N0);
6618   }
6619
6620   return SDValue();
6621 }
6622
6623 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6624   SDValue N0 = N->getOperand(0);
6625   SDValue N1 = N->getOperand(1);
6626   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6627   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6628   EVT VT = N->getValueType(0);
6629   SDLoc dl(N);
6630
6631   // fold vector ops
6632   if (VT.isVector()) {
6633     SDValue FoldedVOp = SimplifyVBinOp(N);
6634     if (FoldedVOp.getNode()) return FoldedVOp;
6635   }
6636
6637   // fold (fsub c1, c2) -> c1-c2
6638   if (N0CFP && N1CFP)
6639     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6640   // fold (fsub A, 0) -> A
6641   if (DAG.getTarget().Options.UnsafeFPMath &&
6642       N1CFP && N1CFP->getValueAPF().isZero())
6643     return N0;
6644   // fold (fsub 0, B) -> -B
6645   if (DAG.getTarget().Options.UnsafeFPMath &&
6646       N0CFP && N0CFP->getValueAPF().isZero()) {
6647     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6648       return GetNegatedExpression(N1, DAG, LegalOperations);
6649     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6650       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6651   }
6652   // fold (fsub A, (fneg B)) -> (fadd A, B)
6653   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6654     return DAG.getNode(ISD::FADD, dl, VT, N0,
6655                        GetNegatedExpression(N1, DAG, LegalOperations));
6656
6657   // If 'unsafe math' is enabled, fold
6658   //    (fsub x, x) -> 0.0 &
6659   //    (fsub x, (fadd x, y)) -> (fneg y) &
6660   //    (fsub x, (fadd y, x)) -> (fneg y)
6661   if (DAG.getTarget().Options.UnsafeFPMath) {
6662     if (N0 == N1)
6663       return DAG.getConstantFP(0.0f, VT);
6664
6665     if (N1.getOpcode() == ISD::FADD) {
6666       SDValue N10 = N1->getOperand(0);
6667       SDValue N11 = N1->getOperand(1);
6668
6669       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6670                                           &DAG.getTarget().Options))
6671         return GetNegatedExpression(N11, DAG, LegalOperations);
6672
6673       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6674                                           &DAG.getTarget().Options))
6675         return GetNegatedExpression(N10, DAG, LegalOperations);
6676     }
6677   }
6678
6679   // FSUB -> FMA combines:
6680   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6681        DAG.getTarget().Options.UnsafeFPMath) &&
6682       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6683       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6684
6685     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6686     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6687       return DAG.getNode(ISD::FMA, dl, VT,
6688                          N0.getOperand(0), N0.getOperand(1),
6689                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6690
6691     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6692     // Note: Commutes FSUB operands.
6693     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6694       return DAG.getNode(ISD::FMA, dl, VT,
6695                          DAG.getNode(ISD::FNEG, dl, VT,
6696                          N1.getOperand(0)),
6697                          N1.getOperand(1), N0);
6698
6699     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6700     if (N0.getOpcode() == ISD::FNEG &&
6701         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6702         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6703       SDValue N00 = N0.getOperand(0).getOperand(0);
6704       SDValue N01 = N0.getOperand(0).getOperand(1);
6705       return DAG.getNode(ISD::FMA, dl, VT,
6706                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6707                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6708     }
6709   }
6710
6711   return SDValue();
6712 }
6713
6714 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6715   SDValue N0 = N->getOperand(0);
6716   SDValue N1 = N->getOperand(1);
6717   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6718   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6719   EVT VT = N->getValueType(0);
6720   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6721
6722   // fold vector ops
6723   if (VT.isVector()) {
6724     SDValue FoldedVOp = SimplifyVBinOp(N);
6725     if (FoldedVOp.getNode()) return FoldedVOp;
6726   }
6727
6728   // fold (fmul c1, c2) -> c1*c2
6729   if (N0CFP && N1CFP)
6730     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6731   // canonicalize constant to RHS
6732   if (N0CFP && !N1CFP)
6733     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6734   // fold (fmul A, 0) -> 0
6735   if (DAG.getTarget().Options.UnsafeFPMath &&
6736       N1CFP && N1CFP->getValueAPF().isZero())
6737     return N1;
6738   // fold (fmul A, 0) -> 0, vector edition.
6739   if (DAG.getTarget().Options.UnsafeFPMath &&
6740       ISD::isBuildVectorAllZeros(N1.getNode()))
6741     return N1;
6742   // fold (fmul A, 1.0) -> A
6743   if (N1CFP && N1CFP->isExactlyValue(1.0))
6744     return N0;
6745   // fold (fmul X, 2.0) -> (fadd X, X)
6746   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6747     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6748   // fold (fmul X, -1.0) -> (fneg X)
6749   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6750     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6751       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6752
6753   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6754   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6755                                        &DAG.getTarget().Options)) {
6756     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6757                                          &DAG.getTarget().Options)) {
6758       // Both can be negated for free, check to see if at least one is cheaper
6759       // negated.
6760       if (LHSNeg == 2 || RHSNeg == 2)
6761         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6762                            GetNegatedExpression(N0, DAG, LegalOperations),
6763                            GetNegatedExpression(N1, DAG, LegalOperations));
6764     }
6765   }
6766
6767   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6768   if (DAG.getTarget().Options.UnsafeFPMath &&
6769       N1CFP && N0.getOpcode() == ISD::FMUL &&
6770       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6771     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6772                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6773                                    N0.getOperand(1), N1));
6774
6775   return SDValue();
6776 }
6777
6778 SDValue DAGCombiner::visitFMA(SDNode *N) {
6779   SDValue N0 = N->getOperand(0);
6780   SDValue N1 = N->getOperand(1);
6781   SDValue N2 = N->getOperand(2);
6782   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6783   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6784   EVT VT = N->getValueType(0);
6785   SDLoc dl(N);
6786
6787   if (DAG.getTarget().Options.UnsafeFPMath) {
6788     if (N0CFP && N0CFP->isZero())
6789       return N2;
6790     if (N1CFP && N1CFP->isZero())
6791       return N2;
6792   }
6793   if (N0CFP && N0CFP->isExactlyValue(1.0))
6794     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6795   if (N1CFP && N1CFP->isExactlyValue(1.0))
6796     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6797
6798   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6799   if (N0CFP && !N1CFP)
6800     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6801
6802   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6803   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6804       N2.getOpcode() == ISD::FMUL &&
6805       N0 == N2.getOperand(0) &&
6806       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6807     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6808                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6809   }
6810
6811
6812   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6813   if (DAG.getTarget().Options.UnsafeFPMath &&
6814       N0.getOpcode() == ISD::FMUL && N1CFP &&
6815       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6816     return DAG.getNode(ISD::FMA, dl, VT,
6817                        N0.getOperand(0),
6818                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6819                        N2);
6820   }
6821
6822   // (fma x, 1, y) -> (fadd x, y)
6823   // (fma x, -1, y) -> (fadd (fneg x), y)
6824   if (N1CFP) {
6825     if (N1CFP->isExactlyValue(1.0))
6826       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6827
6828     if (N1CFP->isExactlyValue(-1.0) &&
6829         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6830       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6831       AddToWorkList(RHSNeg.getNode());
6832       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6833     }
6834   }
6835
6836   // (fma x, c, x) -> (fmul x, (c+1))
6837   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6838     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6839                        DAG.getNode(ISD::FADD, dl, VT,
6840                                    N1, DAG.getConstantFP(1.0, VT)));
6841
6842   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6843   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6844       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6845     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6846                        DAG.getNode(ISD::FADD, dl, VT,
6847                                    N1, DAG.getConstantFP(-1.0, VT)));
6848
6849
6850   return SDValue();
6851 }
6852
6853 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6854   SDValue N0 = N->getOperand(0);
6855   SDValue N1 = N->getOperand(1);
6856   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6857   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6858   EVT VT = N->getValueType(0);
6859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6860
6861   // fold vector ops
6862   if (VT.isVector()) {
6863     SDValue FoldedVOp = SimplifyVBinOp(N);
6864     if (FoldedVOp.getNode()) return FoldedVOp;
6865   }
6866
6867   // fold (fdiv c1, c2) -> c1/c2
6868   if (N0CFP && N1CFP)
6869     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6870
6871   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6872   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6873     // Compute the reciprocal 1.0 / c2.
6874     APFloat N1APF = N1CFP->getValueAPF();
6875     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6876     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6877     // Only do the transform if the reciprocal is a legal fp immediate that
6878     // isn't too nasty (eg NaN, denormal, ...).
6879     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6880         (!LegalOperations ||
6881          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6882          // backend)... we should handle this gracefully after Legalize.
6883          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6884          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6885          TLI.isFPImmLegal(Recip, VT)))
6886       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6887                          DAG.getConstantFP(Recip, VT));
6888   }
6889
6890   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6891   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6892                                        &DAG.getTarget().Options)) {
6893     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6894                                          &DAG.getTarget().Options)) {
6895       // Both can be negated for free, check to see if at least one is cheaper
6896       // negated.
6897       if (LHSNeg == 2 || RHSNeg == 2)
6898         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6899                            GetNegatedExpression(N0, DAG, LegalOperations),
6900                            GetNegatedExpression(N1, DAG, LegalOperations));
6901     }
6902   }
6903
6904   return SDValue();
6905 }
6906
6907 SDValue DAGCombiner::visitFREM(SDNode *N) {
6908   SDValue N0 = N->getOperand(0);
6909   SDValue N1 = N->getOperand(1);
6910   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6911   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6912   EVT VT = N->getValueType(0);
6913
6914   // fold (frem c1, c2) -> fmod(c1,c2)
6915   if (N0CFP && N1CFP)
6916     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6917
6918   return SDValue();
6919 }
6920
6921 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6922   SDValue N0 = N->getOperand(0);
6923   SDValue N1 = N->getOperand(1);
6924   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6925   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6926   EVT VT = N->getValueType(0);
6927
6928   if (N0CFP && N1CFP)  // Constant fold
6929     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6930
6931   if (N1CFP) {
6932     const APFloat& V = N1CFP->getValueAPF();
6933     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6934     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6935     if (!V.isNegative()) {
6936       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6937         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6938     } else {
6939       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6940         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6941                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6942     }
6943   }
6944
6945   // copysign(fabs(x), y) -> copysign(x, y)
6946   // copysign(fneg(x), y) -> copysign(x, y)
6947   // copysign(copysign(x,z), y) -> copysign(x, y)
6948   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6949       N0.getOpcode() == ISD::FCOPYSIGN)
6950     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6951                        N0.getOperand(0), N1);
6952
6953   // copysign(x, abs(y)) -> abs(x)
6954   if (N1.getOpcode() == ISD::FABS)
6955     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6956
6957   // copysign(x, copysign(y,z)) -> copysign(x, z)
6958   if (N1.getOpcode() == ISD::FCOPYSIGN)
6959     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6960                        N0, N1.getOperand(1));
6961
6962   // copysign(x, fp_extend(y)) -> copysign(x, y)
6963   // copysign(x, fp_round(y)) -> copysign(x, y)
6964   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6965     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6966                        N0, N1.getOperand(0));
6967
6968   return SDValue();
6969 }
6970
6971 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6972   SDValue N0 = N->getOperand(0);
6973   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6974   EVT VT = N->getValueType(0);
6975   EVT OpVT = N0.getValueType();
6976
6977   // fold (sint_to_fp c1) -> c1fp
6978   if (N0C &&
6979       // ...but only if the target supports immediate floating-point values
6980       (!LegalOperations ||
6981        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6982     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6983
6984   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6985   // but UINT_TO_FP is legal on this target, try to convert.
6986   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6987       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6988     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6989     if (DAG.SignBitIsZero(N0))
6990       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6991   }
6992
6993   // The next optimizations are desirable only if SELECT_CC can be lowered.
6994   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6995   // having to say they don't support SELECT_CC on every type the DAG knows
6996   // about, since there is no way to mark an opcode illegal at all value types
6997   // (See also visitSELECT)
6998   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6999     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7000     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7001         !VT.isVector() &&
7002         (!LegalOperations ||
7003          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7004       SDValue Ops[] =
7005         { N0.getOperand(0), N0.getOperand(1),
7006           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7007           N0.getOperand(2) };
7008       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7009     }
7010
7011     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7012     //      (select_cc x, y, 1.0, 0.0,, cc)
7013     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7014         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7015         (!LegalOperations ||
7016          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7017       SDValue Ops[] =
7018         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7019           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7020           N0.getOperand(0).getOperand(2) };
7021       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7022     }
7023   }
7024
7025   return SDValue();
7026 }
7027
7028 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7029   SDValue N0 = N->getOperand(0);
7030   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7031   EVT VT = N->getValueType(0);
7032   EVT OpVT = N0.getValueType();
7033
7034   // fold (uint_to_fp c1) -> c1fp
7035   if (N0C &&
7036       // ...but only if the target supports immediate floating-point values
7037       (!LegalOperations ||
7038        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7039     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7040
7041   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7042   // but SINT_TO_FP is legal on this target, try to convert.
7043   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7044       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7045     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7046     if (DAG.SignBitIsZero(N0))
7047       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7048   }
7049
7050   // The next optimizations are desirable only if SELECT_CC can be lowered.
7051   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7052   // having to say they don't support SELECT_CC on every type the DAG knows
7053   // about, since there is no way to mark an opcode illegal at all value types
7054   // (See also visitSELECT)
7055   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7056     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7057
7058     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7059         (!LegalOperations ||
7060          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7061       SDValue Ops[] =
7062         { N0.getOperand(0), N0.getOperand(1),
7063           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7064           N0.getOperand(2) };
7065       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7066     }
7067   }
7068
7069   return SDValue();
7070 }
7071
7072 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7073   SDValue N0 = N->getOperand(0);
7074   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7075   EVT VT = N->getValueType(0);
7076
7077   // fold (fp_to_sint c1fp) -> c1
7078   if (N0CFP)
7079     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7080
7081   return SDValue();
7082 }
7083
7084 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7085   SDValue N0 = N->getOperand(0);
7086   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7087   EVT VT = N->getValueType(0);
7088
7089   // fold (fp_to_uint c1fp) -> c1
7090   if (N0CFP)
7091     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7092
7093   return SDValue();
7094 }
7095
7096 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7097   SDValue N0 = N->getOperand(0);
7098   SDValue N1 = N->getOperand(1);
7099   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7100   EVT VT = N->getValueType(0);
7101
7102   // fold (fp_round c1fp) -> c1fp
7103   if (N0CFP)
7104     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7105
7106   // fold (fp_round (fp_extend x)) -> x
7107   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7108     return N0.getOperand(0);
7109
7110   // fold (fp_round (fp_round x)) -> (fp_round x)
7111   if (N0.getOpcode() == ISD::FP_ROUND) {
7112     // This is a value preserving truncation if both round's are.
7113     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7114                    N0.getNode()->getConstantOperandVal(1) == 1;
7115     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7116                        DAG.getIntPtrConstant(IsTrunc));
7117   }
7118
7119   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7120   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7121     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7122                               N0.getOperand(0), N1);
7123     AddToWorkList(Tmp.getNode());
7124     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7125                        Tmp, N0.getOperand(1));
7126   }
7127
7128   return SDValue();
7129 }
7130
7131 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7132   SDValue N0 = N->getOperand(0);
7133   EVT VT = N->getValueType(0);
7134   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7135   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7136
7137   // fold (fp_round_inreg c1fp) -> c1fp
7138   if (N0CFP && isTypeLegal(EVT)) {
7139     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7140     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7141   }
7142
7143   return SDValue();
7144 }
7145
7146 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7147   SDValue N0 = N->getOperand(0);
7148   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7149   EVT VT = N->getValueType(0);
7150
7151   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7152   if (N->hasOneUse() &&
7153       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7154     return SDValue();
7155
7156   // fold (fp_extend c1fp) -> c1fp
7157   if (N0CFP)
7158     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7159
7160   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7161   // value of X.
7162   if (N0.getOpcode() == ISD::FP_ROUND
7163       && N0.getNode()->getConstantOperandVal(1) == 1) {
7164     SDValue In = N0.getOperand(0);
7165     if (In.getValueType() == VT) return In;
7166     if (VT.bitsLT(In.getValueType()))
7167       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7168                          In, N0.getOperand(1));
7169     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7170   }
7171
7172   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7173   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7174       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7175        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7176     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7177     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7178                                      LN0->getChain(),
7179                                      LN0->getBasePtr(), N0.getValueType(),
7180                                      LN0->getMemOperand());
7181     CombineTo(N, ExtLoad);
7182     CombineTo(N0.getNode(),
7183               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7184                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7185               ExtLoad.getValue(1));
7186     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7187   }
7188
7189   return SDValue();
7190 }
7191
7192 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7193   SDValue N0 = N->getOperand(0);
7194   EVT VT = N->getValueType(0);
7195
7196   if (VT.isVector()) {
7197     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7198     if (FoldedVOp.getNode()) return FoldedVOp;
7199   }
7200
7201   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7202                          &DAG.getTarget().Options))
7203     return GetNegatedExpression(N0, DAG, LegalOperations);
7204
7205   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7206   // constant pool values.
7207   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7208       !VT.isVector() &&
7209       N0.getNode()->hasOneUse() &&
7210       N0.getOperand(0).getValueType().isInteger()) {
7211     SDValue Int = N0.getOperand(0);
7212     EVT IntVT = Int.getValueType();
7213     if (IntVT.isInteger() && !IntVT.isVector()) {
7214       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7215               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7216       AddToWorkList(Int.getNode());
7217       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7218                          VT, Int);
7219     }
7220   }
7221
7222   // (fneg (fmul c, x)) -> (fmul -c, x)
7223   if (N0.getOpcode() == ISD::FMUL) {
7224     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7225     if (CFP1)
7226       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7227                          N0.getOperand(0),
7228                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7229                                      N0.getOperand(1)));
7230   }
7231
7232   return SDValue();
7233 }
7234
7235 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7236   SDValue N0 = N->getOperand(0);
7237   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7238   EVT VT = N->getValueType(0);
7239
7240   // fold (fceil c1) -> fceil(c1)
7241   if (N0CFP)
7242     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7243
7244   return SDValue();
7245 }
7246
7247 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7248   SDValue N0 = N->getOperand(0);
7249   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7250   EVT VT = N->getValueType(0);
7251
7252   // fold (ftrunc c1) -> ftrunc(c1)
7253   if (N0CFP)
7254     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7255
7256   return SDValue();
7257 }
7258
7259 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7260   SDValue N0 = N->getOperand(0);
7261   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7262   EVT VT = N->getValueType(0);
7263
7264   // fold (ffloor c1) -> ffloor(c1)
7265   if (N0CFP)
7266     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7267
7268   return SDValue();
7269 }
7270
7271 SDValue DAGCombiner::visitFABS(SDNode *N) {
7272   SDValue N0 = N->getOperand(0);
7273   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7274   EVT VT = N->getValueType(0);
7275
7276   if (VT.isVector()) {
7277     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7278     if (FoldedVOp.getNode()) return FoldedVOp;
7279   }
7280
7281   // fold (fabs c1) -> fabs(c1)
7282   if (N0CFP)
7283     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7284   // fold (fabs (fabs x)) -> (fabs x)
7285   if (N0.getOpcode() == ISD::FABS)
7286     return N->getOperand(0);
7287   // fold (fabs (fneg x)) -> (fabs x)
7288   // fold (fabs (fcopysign x, y)) -> (fabs x)
7289   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7290     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7291
7292   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7293   // constant pool values.
7294   if (!TLI.isFAbsFree(VT) &&
7295       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7296       N0.getOperand(0).getValueType().isInteger() &&
7297       !N0.getOperand(0).getValueType().isVector()) {
7298     SDValue Int = N0.getOperand(0);
7299     EVT IntVT = Int.getValueType();
7300     if (IntVT.isInteger() && !IntVT.isVector()) {
7301       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7302              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7303       AddToWorkList(Int.getNode());
7304       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7305                          N->getValueType(0), Int);
7306     }
7307   }
7308
7309   return SDValue();
7310 }
7311
7312 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7313   SDValue Chain = N->getOperand(0);
7314   SDValue N1 = N->getOperand(1);
7315   SDValue N2 = N->getOperand(2);
7316
7317   // If N is a constant we could fold this into a fallthrough or unconditional
7318   // branch. However that doesn't happen very often in normal code, because
7319   // Instcombine/SimplifyCFG should have handled the available opportunities.
7320   // If we did this folding here, it would be necessary to update the
7321   // MachineBasicBlock CFG, which is awkward.
7322
7323   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7324   // on the target.
7325   if (N1.getOpcode() == ISD::SETCC &&
7326       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7327                                    N1.getOperand(0).getValueType())) {
7328     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7329                        Chain, N1.getOperand(2),
7330                        N1.getOperand(0), N1.getOperand(1), N2);
7331   }
7332
7333   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7334       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7335        (N1.getOperand(0).hasOneUse() &&
7336         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7337     SDNode *Trunc = 0;
7338     if (N1.getOpcode() == ISD::TRUNCATE) {
7339       // Look pass the truncate.
7340       Trunc = N1.getNode();
7341       N1 = N1.getOperand(0);
7342     }
7343
7344     // Match this pattern so that we can generate simpler code:
7345     //
7346     //   %a = ...
7347     //   %b = and i32 %a, 2
7348     //   %c = srl i32 %b, 1
7349     //   brcond i32 %c ...
7350     //
7351     // into
7352     //
7353     //   %a = ...
7354     //   %b = and i32 %a, 2
7355     //   %c = setcc eq %b, 0
7356     //   brcond %c ...
7357     //
7358     // This applies only when the AND constant value has one bit set and the
7359     // SRL constant is equal to the log2 of the AND constant. The back-end is
7360     // smart enough to convert the result into a TEST/JMP sequence.
7361     SDValue Op0 = N1.getOperand(0);
7362     SDValue Op1 = N1.getOperand(1);
7363
7364     if (Op0.getOpcode() == ISD::AND &&
7365         Op1.getOpcode() == ISD::Constant) {
7366       SDValue AndOp1 = Op0.getOperand(1);
7367
7368       if (AndOp1.getOpcode() == ISD::Constant) {
7369         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7370
7371         if (AndConst.isPowerOf2() &&
7372             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7373           SDValue SetCC =
7374             DAG.getSetCC(SDLoc(N),
7375                          getSetCCResultType(Op0.getValueType()),
7376                          Op0, DAG.getConstant(0, Op0.getValueType()),
7377                          ISD::SETNE);
7378
7379           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7380                                           MVT::Other, Chain, SetCC, N2);
7381           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7382           // will convert it back to (X & C1) >> C2.
7383           CombineTo(N, NewBRCond, false);
7384           // Truncate is dead.
7385           if (Trunc) {
7386             removeFromWorkList(Trunc);
7387             DAG.DeleteNode(Trunc);
7388           }
7389           // Replace the uses of SRL with SETCC
7390           WorkListRemover DeadNodes(*this);
7391           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7392           removeFromWorkList(N1.getNode());
7393           DAG.DeleteNode(N1.getNode());
7394           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7395         }
7396       }
7397     }
7398
7399     if (Trunc)
7400       // Restore N1 if the above transformation doesn't match.
7401       N1 = N->getOperand(1);
7402   }
7403
7404   // Transform br(xor(x, y)) -> br(x != y)
7405   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7406   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7407     SDNode *TheXor = N1.getNode();
7408     SDValue Op0 = TheXor->getOperand(0);
7409     SDValue Op1 = TheXor->getOperand(1);
7410     if (Op0.getOpcode() == Op1.getOpcode()) {
7411       // Avoid missing important xor optimizations.
7412       SDValue Tmp = visitXOR(TheXor);
7413       if (Tmp.getNode()) {
7414         if (Tmp.getNode() != TheXor) {
7415           DEBUG(dbgs() << "\nReplacing.8 ";
7416                 TheXor->dump(&DAG);
7417                 dbgs() << "\nWith: ";
7418                 Tmp.getNode()->dump(&DAG);
7419                 dbgs() << '\n');
7420           WorkListRemover DeadNodes(*this);
7421           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7422           removeFromWorkList(TheXor);
7423           DAG.DeleteNode(TheXor);
7424           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7425                              MVT::Other, Chain, Tmp, N2);
7426         }
7427
7428         // visitXOR has changed XOR's operands or replaced the XOR completely,
7429         // bail out.
7430         return SDValue(N, 0);
7431       }
7432     }
7433
7434     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7435       bool Equal = false;
7436       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7437         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7438             Op0.getOpcode() == ISD::XOR) {
7439           TheXor = Op0.getNode();
7440           Equal = true;
7441         }
7442
7443       EVT SetCCVT = N1.getValueType();
7444       if (LegalTypes)
7445         SetCCVT = getSetCCResultType(SetCCVT);
7446       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7447                                    SetCCVT,
7448                                    Op0, Op1,
7449                                    Equal ? ISD::SETEQ : ISD::SETNE);
7450       // Replace the uses of XOR with SETCC
7451       WorkListRemover DeadNodes(*this);
7452       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7453       removeFromWorkList(N1.getNode());
7454       DAG.DeleteNode(N1.getNode());
7455       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7456                          MVT::Other, Chain, SetCC, N2);
7457     }
7458   }
7459
7460   return SDValue();
7461 }
7462
7463 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7464 //
7465 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7466   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7467   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7468
7469   // If N is a constant we could fold this into a fallthrough or unconditional
7470   // branch. However that doesn't happen very often in normal code, because
7471   // Instcombine/SimplifyCFG should have handled the available opportunities.
7472   // If we did this folding here, it would be necessary to update the
7473   // MachineBasicBlock CFG, which is awkward.
7474
7475   // Use SimplifySetCC to simplify SETCC's.
7476   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7477                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7478                                false);
7479   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7480
7481   // fold to a simpler setcc
7482   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7483     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7484                        N->getOperand(0), Simp.getOperand(2),
7485                        Simp.getOperand(0), Simp.getOperand(1),
7486                        N->getOperand(4));
7487
7488   return SDValue();
7489 }
7490
7491 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7492 /// uses N as its base pointer and that N may be folded in the load / store
7493 /// addressing mode.
7494 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7495                                     SelectionDAG &DAG,
7496                                     const TargetLowering &TLI) {
7497   EVT VT;
7498   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7499     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7500       return false;
7501     VT = Use->getValueType(0);
7502   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7503     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7504       return false;
7505     VT = ST->getValue().getValueType();
7506   } else
7507     return false;
7508
7509   TargetLowering::AddrMode AM;
7510   if (N->getOpcode() == ISD::ADD) {
7511     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7512     if (Offset)
7513       // [reg +/- imm]
7514       AM.BaseOffs = Offset->getSExtValue();
7515     else
7516       // [reg +/- reg]
7517       AM.Scale = 1;
7518   } else if (N->getOpcode() == ISD::SUB) {
7519     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7520     if (Offset)
7521       // [reg +/- imm]
7522       AM.BaseOffs = -Offset->getSExtValue();
7523     else
7524       // [reg +/- reg]
7525       AM.Scale = 1;
7526   } else
7527     return false;
7528
7529   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7530 }
7531
7532 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7533 /// pre-indexed load / store when the base pointer is an add or subtract
7534 /// and it has other uses besides the load / store. After the
7535 /// transformation, the new indexed load / store has effectively folded
7536 /// the add / subtract in and all of its other uses are redirected to the
7537 /// new load / store.
7538 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7539   if (Level < AfterLegalizeDAG)
7540     return false;
7541
7542   bool isLoad = true;
7543   SDValue Ptr;
7544   EVT VT;
7545   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7546     if (LD->isIndexed())
7547       return false;
7548     VT = LD->getMemoryVT();
7549     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7550         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7551       return false;
7552     Ptr = LD->getBasePtr();
7553   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7554     if (ST->isIndexed())
7555       return false;
7556     VT = ST->getMemoryVT();
7557     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7558         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7559       return false;
7560     Ptr = ST->getBasePtr();
7561     isLoad = false;
7562   } else {
7563     return false;
7564   }
7565
7566   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7567   // out.  There is no reason to make this a preinc/predec.
7568   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7569       Ptr.getNode()->hasOneUse())
7570     return false;
7571
7572   // Ask the target to do addressing mode selection.
7573   SDValue BasePtr;
7574   SDValue Offset;
7575   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7576   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7577     return false;
7578
7579   // Backends without true r+i pre-indexed forms may need to pass a
7580   // constant base with a variable offset so that constant coercion
7581   // will work with the patterns in canonical form.
7582   bool Swapped = false;
7583   if (isa<ConstantSDNode>(BasePtr)) {
7584     std::swap(BasePtr, Offset);
7585     Swapped = true;
7586   }
7587
7588   // Don't create a indexed load / store with zero offset.
7589   if (isa<ConstantSDNode>(Offset) &&
7590       cast<ConstantSDNode>(Offset)->isNullValue())
7591     return false;
7592
7593   // Try turning it into a pre-indexed load / store except when:
7594   // 1) The new base ptr is a frame index.
7595   // 2) If N is a store and the new base ptr is either the same as or is a
7596   //    predecessor of the value being stored.
7597   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7598   //    that would create a cycle.
7599   // 4) All uses are load / store ops that use it as old base ptr.
7600
7601   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7602   // (plus the implicit offset) to a register to preinc anyway.
7603   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7604     return false;
7605
7606   // Check #2.
7607   if (!isLoad) {
7608     SDValue Val = cast<StoreSDNode>(N)->getValue();
7609     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7610       return false;
7611   }
7612
7613   // If the offset is a constant, there may be other adds of constants that
7614   // can be folded with this one. We should do this to avoid having to keep
7615   // a copy of the original base pointer.
7616   SmallVector<SDNode *, 16> OtherUses;
7617   if (isa<ConstantSDNode>(Offset))
7618     for (SDNode *Use : BasePtr.getNode()->uses()) {
7619       if (Use == Ptr.getNode())
7620         continue;
7621
7622       if (Use->isPredecessorOf(N))
7623         continue;
7624
7625       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7626         OtherUses.clear();
7627         break;
7628       }
7629
7630       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7631       if (Op1.getNode() == BasePtr.getNode())
7632         std::swap(Op0, Op1);
7633       assert(Op0.getNode() == BasePtr.getNode() &&
7634              "Use of ADD/SUB but not an operand");
7635
7636       if (!isa<ConstantSDNode>(Op1)) {
7637         OtherUses.clear();
7638         break;
7639       }
7640
7641       // FIXME: In some cases, we can be smarter about this.
7642       if (Op1.getValueType() != Offset.getValueType()) {
7643         OtherUses.clear();
7644         break;
7645       }
7646
7647       OtherUses.push_back(Use);
7648     }
7649
7650   if (Swapped)
7651     std::swap(BasePtr, Offset);
7652
7653   // Now check for #3 and #4.
7654   bool RealUse = false;
7655
7656   // Caches for hasPredecessorHelper
7657   SmallPtrSet<const SDNode *, 32> Visited;
7658   SmallVector<const SDNode *, 16> Worklist;
7659
7660   for (SDNode *Use : Ptr.getNode()->uses()) {
7661     if (Use == N)
7662       continue;
7663     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7664       return false;
7665
7666     // If Ptr may be folded in addressing mode of other use, then it's
7667     // not profitable to do this transformation.
7668     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7669       RealUse = true;
7670   }
7671
7672   if (!RealUse)
7673     return false;
7674
7675   SDValue Result;
7676   if (isLoad)
7677     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7678                                 BasePtr, Offset, AM);
7679   else
7680     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7681                                  BasePtr, Offset, AM);
7682   ++PreIndexedNodes;
7683   ++NodesCombined;
7684   DEBUG(dbgs() << "\nReplacing.4 ";
7685         N->dump(&DAG);
7686         dbgs() << "\nWith: ";
7687         Result.getNode()->dump(&DAG);
7688         dbgs() << '\n');
7689   WorkListRemover DeadNodes(*this);
7690   if (isLoad) {
7691     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7692     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7693   } else {
7694     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7695   }
7696
7697   // Finally, since the node is now dead, remove it from the graph.
7698   DAG.DeleteNode(N);
7699
7700   if (Swapped)
7701     std::swap(BasePtr, Offset);
7702
7703   // Replace other uses of BasePtr that can be updated to use Ptr
7704   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7705     unsigned OffsetIdx = 1;
7706     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7707       OffsetIdx = 0;
7708     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7709            BasePtr.getNode() && "Expected BasePtr operand");
7710
7711     // We need to replace ptr0 in the following expression:
7712     //   x0 * offset0 + y0 * ptr0 = t0
7713     // knowing that
7714     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7715     //
7716     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7717     // indexed load/store and the expresion that needs to be re-written.
7718     //
7719     // Therefore, we have:
7720     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7721
7722     ConstantSDNode *CN =
7723       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7724     int X0, X1, Y0, Y1;
7725     APInt Offset0 = CN->getAPIntValue();
7726     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7727
7728     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7729     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7730     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7731     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7732
7733     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7734
7735     APInt CNV = Offset0;
7736     if (X0 < 0) CNV = -CNV;
7737     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7738     else CNV = CNV - Offset1;
7739
7740     // We can now generate the new expression.
7741     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7742     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7743
7744     SDValue NewUse = DAG.getNode(Opcode,
7745                                  SDLoc(OtherUses[i]),
7746                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7747     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7748     removeFromWorkList(OtherUses[i]);
7749     DAG.DeleteNode(OtherUses[i]);
7750   }
7751
7752   // Replace the uses of Ptr with uses of the updated base value.
7753   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7754   removeFromWorkList(Ptr.getNode());
7755   DAG.DeleteNode(Ptr.getNode());
7756
7757   return true;
7758 }
7759
7760 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7761 /// add / sub of the base pointer node into a post-indexed load / store.
7762 /// The transformation folded the add / subtract into the new indexed
7763 /// load / store effectively and all of its uses are redirected to the
7764 /// new load / store.
7765 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7766   if (Level < AfterLegalizeDAG)
7767     return false;
7768
7769   bool isLoad = true;
7770   SDValue Ptr;
7771   EVT VT;
7772   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7773     if (LD->isIndexed())
7774       return false;
7775     VT = LD->getMemoryVT();
7776     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7777         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7778       return false;
7779     Ptr = LD->getBasePtr();
7780   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7781     if (ST->isIndexed())
7782       return false;
7783     VT = ST->getMemoryVT();
7784     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7785         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7786       return false;
7787     Ptr = ST->getBasePtr();
7788     isLoad = false;
7789   } else {
7790     return false;
7791   }
7792
7793   if (Ptr.getNode()->hasOneUse())
7794     return false;
7795
7796   for (SDNode *Op : Ptr.getNode()->uses()) {
7797     if (Op == N ||
7798         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7799       continue;
7800
7801     SDValue BasePtr;
7802     SDValue Offset;
7803     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7804     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7805       // Don't create a indexed load / store with zero offset.
7806       if (isa<ConstantSDNode>(Offset) &&
7807           cast<ConstantSDNode>(Offset)->isNullValue())
7808         continue;
7809
7810       // Try turning it into a post-indexed load / store except when
7811       // 1) All uses are load / store ops that use it as base ptr (and
7812       //    it may be folded as addressing mmode).
7813       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7814       //    nor a successor of N. Otherwise, if Op is folded that would
7815       //    create a cycle.
7816
7817       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7818         continue;
7819
7820       // Check for #1.
7821       bool TryNext = false;
7822       for (SDNode *Use : BasePtr.getNode()->uses()) {
7823         if (Use == Ptr.getNode())
7824           continue;
7825
7826         // If all the uses are load / store addresses, then don't do the
7827         // transformation.
7828         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7829           bool RealUse = false;
7830           for (SDNode *UseUse : Use->uses()) {
7831             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7832               RealUse = true;
7833           }
7834
7835           if (!RealUse) {
7836             TryNext = true;
7837             break;
7838           }
7839         }
7840       }
7841
7842       if (TryNext)
7843         continue;
7844
7845       // Check for #2
7846       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7847         SDValue Result = isLoad
7848           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7849                                BasePtr, Offset, AM)
7850           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7851                                 BasePtr, Offset, AM);
7852         ++PostIndexedNodes;
7853         ++NodesCombined;
7854         DEBUG(dbgs() << "\nReplacing.5 ";
7855               N->dump(&DAG);
7856               dbgs() << "\nWith: ";
7857               Result.getNode()->dump(&DAG);
7858               dbgs() << '\n');
7859         WorkListRemover DeadNodes(*this);
7860         if (isLoad) {
7861           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7862           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7863         } else {
7864           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7865         }
7866
7867         // Finally, since the node is now dead, remove it from the graph.
7868         DAG.DeleteNode(N);
7869
7870         // Replace the uses of Use with uses of the updated base value.
7871         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7872                                       Result.getValue(isLoad ? 1 : 0));
7873         removeFromWorkList(Op);
7874         DAG.DeleteNode(Op);
7875         return true;
7876       }
7877     }
7878   }
7879
7880   return false;
7881 }
7882
7883 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7884   LoadSDNode *LD  = cast<LoadSDNode>(N);
7885   SDValue Chain = LD->getChain();
7886   SDValue Ptr   = LD->getBasePtr();
7887
7888   // If load is not volatile and there are no uses of the loaded value (and
7889   // the updated indexed value in case of indexed loads), change uses of the
7890   // chain value into uses of the chain input (i.e. delete the dead load).
7891   if (!LD->isVolatile()) {
7892     if (N->getValueType(1) == MVT::Other) {
7893       // Unindexed loads.
7894       if (!N->hasAnyUseOfValue(0)) {
7895         // It's not safe to use the two value CombineTo variant here. e.g.
7896         // v1, chain2 = load chain1, loc
7897         // v2, chain3 = load chain2, loc
7898         // v3         = add v2, c
7899         // Now we replace use of chain2 with chain1.  This makes the second load
7900         // isomorphic to the one we are deleting, and thus makes this load live.
7901         DEBUG(dbgs() << "\nReplacing.6 ";
7902               N->dump(&DAG);
7903               dbgs() << "\nWith chain: ";
7904               Chain.getNode()->dump(&DAG);
7905               dbgs() << "\n");
7906         WorkListRemover DeadNodes(*this);
7907         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7908
7909         if (N->use_empty()) {
7910           removeFromWorkList(N);
7911           DAG.DeleteNode(N);
7912         }
7913
7914         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7915       }
7916     } else {
7917       // Indexed loads.
7918       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7919       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7920         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7921         DEBUG(dbgs() << "\nReplacing.7 ";
7922               N->dump(&DAG);
7923               dbgs() << "\nWith: ";
7924               Undef.getNode()->dump(&DAG);
7925               dbgs() << " and 2 other values\n");
7926         WorkListRemover DeadNodes(*this);
7927         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7928         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7929                                       DAG.getUNDEF(N->getValueType(1)));
7930         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7931         removeFromWorkList(N);
7932         DAG.DeleteNode(N);
7933         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7934       }
7935     }
7936   }
7937
7938   // If this load is directly stored, replace the load value with the stored
7939   // value.
7940   // TODO: Handle store large -> read small portion.
7941   // TODO: Handle TRUNCSTORE/LOADEXT
7942   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7943     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7944       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7945       if (PrevST->getBasePtr() == Ptr &&
7946           PrevST->getValue().getValueType() == N->getValueType(0))
7947       return CombineTo(N, Chain.getOperand(1), Chain);
7948     }
7949   }
7950
7951   // Try to infer better alignment information than the load already has.
7952   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7953     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7954       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7955         SDValue NewLoad =
7956                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7957                               LD->getValueType(0),
7958                               Chain, Ptr, LD->getPointerInfo(),
7959                               LD->getMemoryVT(),
7960                               LD->isVolatile(), LD->isNonTemporal(), Align,
7961                               LD->getTBAAInfo());
7962         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7963       }
7964     }
7965   }
7966
7967   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7968     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7969 #ifndef NDEBUG
7970   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7971       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7972     UseAA = false;
7973 #endif
7974   if (UseAA && LD->isUnindexed()) {
7975     // Walk up chain skipping non-aliasing memory nodes.
7976     SDValue BetterChain = FindBetterChain(N, Chain);
7977
7978     // If there is a better chain.
7979     if (Chain != BetterChain) {
7980       SDValue ReplLoad;
7981
7982       // Replace the chain to void dependency.
7983       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7984         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7985                                BetterChain, Ptr, LD->getMemOperand());
7986       } else {
7987         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7988                                   LD->getValueType(0),
7989                                   BetterChain, Ptr, LD->getMemoryVT(),
7990                                   LD->getMemOperand());
7991       }
7992
7993       // Create token factor to keep old chain connected.
7994       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7995                                   MVT::Other, Chain, ReplLoad.getValue(1));
7996
7997       // Make sure the new and old chains are cleaned up.
7998       AddToWorkList(Token.getNode());
7999
8000       // Replace uses with load result and token factor. Don't add users
8001       // to work list.
8002       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8003     }
8004   }
8005
8006   // Try transforming N to an indexed load.
8007   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8008     return SDValue(N, 0);
8009
8010   // Try to slice up N to more direct loads if the slices are mapped to
8011   // different register banks or pairing can take place.
8012   if (SliceUpLoad(N))
8013     return SDValue(N, 0);
8014
8015   return SDValue();
8016 }
8017
8018 namespace {
8019 /// \brief Helper structure used to slice a load in smaller loads.
8020 /// Basically a slice is obtained from the following sequence:
8021 /// Origin = load Ty1, Base
8022 /// Shift = srl Ty1 Origin, CstTy Amount
8023 /// Inst = trunc Shift to Ty2
8024 ///
8025 /// Then, it will be rewriten into:
8026 /// Slice = load SliceTy, Base + SliceOffset
8027 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8028 ///
8029 /// SliceTy is deduced from the number of bits that are actually used to
8030 /// build Inst.
8031 struct LoadedSlice {
8032   /// \brief Helper structure used to compute the cost of a slice.
8033   struct Cost {
8034     /// Are we optimizing for code size.
8035     bool ForCodeSize;
8036     /// Various cost.
8037     unsigned Loads;
8038     unsigned Truncates;
8039     unsigned CrossRegisterBanksCopies;
8040     unsigned ZExts;
8041     unsigned Shift;
8042
8043     Cost(bool ForCodeSize = false)
8044         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8045           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8046
8047     /// \brief Get the cost of one isolated slice.
8048     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8049         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8050           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8051       EVT TruncType = LS.Inst->getValueType(0);
8052       EVT LoadedType = LS.getLoadedType();
8053       if (TruncType != LoadedType &&
8054           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8055         ZExts = 1;
8056     }
8057
8058     /// \brief Account for slicing gain in the current cost.
8059     /// Slicing provide a few gains like removing a shift or a
8060     /// truncate. This method allows to grow the cost of the original
8061     /// load with the gain from this slice.
8062     void addSliceGain(const LoadedSlice &LS) {
8063       // Each slice saves a truncate.
8064       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8065       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8066                               LS.Inst->getOperand(0).getValueType()))
8067         ++Truncates;
8068       // If there is a shift amount, this slice gets rid of it.
8069       if (LS.Shift)
8070         ++Shift;
8071       // If this slice can merge a cross register bank copy, account for it.
8072       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8073         ++CrossRegisterBanksCopies;
8074     }
8075
8076     Cost &operator+=(const Cost &RHS) {
8077       Loads += RHS.Loads;
8078       Truncates += RHS.Truncates;
8079       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8080       ZExts += RHS.ZExts;
8081       Shift += RHS.Shift;
8082       return *this;
8083     }
8084
8085     bool operator==(const Cost &RHS) const {
8086       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8087              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8088              ZExts == RHS.ZExts && Shift == RHS.Shift;
8089     }
8090
8091     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8092
8093     bool operator<(const Cost &RHS) const {
8094       // Assume cross register banks copies are as expensive as loads.
8095       // FIXME: Do we want some more target hooks?
8096       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8097       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8098       // Unless we are optimizing for code size, consider the
8099       // expensive operation first.
8100       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8101         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8102       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8103              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8104     }
8105
8106     bool operator>(const Cost &RHS) const { return RHS < *this; }
8107
8108     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8109
8110     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8111   };
8112   // The last instruction that represent the slice. This should be a
8113   // truncate instruction.
8114   SDNode *Inst;
8115   // The original load instruction.
8116   LoadSDNode *Origin;
8117   // The right shift amount in bits from the original load.
8118   unsigned Shift;
8119   // The DAG from which Origin came from.
8120   // This is used to get some contextual information about legal types, etc.
8121   SelectionDAG *DAG;
8122
8123   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8124               unsigned Shift = 0, SelectionDAG *DAG = NULL)
8125       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8126
8127   LoadedSlice(const LoadedSlice &LS)
8128       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8129
8130   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8131   /// \return Result is \p BitWidth and has used bits set to 1 and
8132   ///         not used bits set to 0.
8133   APInt getUsedBits() const {
8134     // Reproduce the trunc(lshr) sequence:
8135     // - Start from the truncated value.
8136     // - Zero extend to the desired bit width.
8137     // - Shift left.
8138     assert(Origin && "No original load to compare against.");
8139     unsigned BitWidth = Origin->getValueSizeInBits(0);
8140     assert(Inst && "This slice is not bound to an instruction");
8141     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8142            "Extracted slice is bigger than the whole type!");
8143     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8144     UsedBits.setAllBits();
8145     UsedBits = UsedBits.zext(BitWidth);
8146     UsedBits <<= Shift;
8147     return UsedBits;
8148   }
8149
8150   /// \brief Get the size of the slice to be loaded in bytes.
8151   unsigned getLoadedSize() const {
8152     unsigned SliceSize = getUsedBits().countPopulation();
8153     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8154     return SliceSize / 8;
8155   }
8156
8157   /// \brief Get the type that will be loaded for this slice.
8158   /// Note: This may not be the final type for the slice.
8159   EVT getLoadedType() const {
8160     assert(DAG && "Missing context");
8161     LLVMContext &Ctxt = *DAG->getContext();
8162     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8163   }
8164
8165   /// \brief Get the alignment of the load used for this slice.
8166   unsigned getAlignment() const {
8167     unsigned Alignment = Origin->getAlignment();
8168     unsigned Offset = getOffsetFromBase();
8169     if (Offset != 0)
8170       Alignment = MinAlign(Alignment, Alignment + Offset);
8171     return Alignment;
8172   }
8173
8174   /// \brief Check if this slice can be rewritten with legal operations.
8175   bool isLegal() const {
8176     // An invalid slice is not legal.
8177     if (!Origin || !Inst || !DAG)
8178       return false;
8179
8180     // Offsets are for indexed load only, we do not handle that.
8181     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8182       return false;
8183
8184     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8185
8186     // Check that the type is legal.
8187     EVT SliceType = getLoadedType();
8188     if (!TLI.isTypeLegal(SliceType))
8189       return false;
8190
8191     // Check that the load is legal for this type.
8192     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8193       return false;
8194
8195     // Check that the offset can be computed.
8196     // 1. Check its type.
8197     EVT PtrType = Origin->getBasePtr().getValueType();
8198     if (PtrType == MVT::Untyped || PtrType.isExtended())
8199       return false;
8200
8201     // 2. Check that it fits in the immediate.
8202     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8203       return false;
8204
8205     // 3. Check that the computation is legal.
8206     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8207       return false;
8208
8209     // Check that the zext is legal if it needs one.
8210     EVT TruncateType = Inst->getValueType(0);
8211     if (TruncateType != SliceType &&
8212         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8213       return false;
8214
8215     return true;
8216   }
8217
8218   /// \brief Get the offset in bytes of this slice in the original chunk of
8219   /// bits.
8220   /// \pre DAG != NULL.
8221   uint64_t getOffsetFromBase() const {
8222     assert(DAG && "Missing context.");
8223     bool IsBigEndian =
8224         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8225     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8226     uint64_t Offset = Shift / 8;
8227     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8228     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8229            "The size of the original loaded type is not a multiple of a"
8230            " byte.");
8231     // If Offset is bigger than TySizeInBytes, it means we are loading all
8232     // zeros. This should have been optimized before in the process.
8233     assert(TySizeInBytes > Offset &&
8234            "Invalid shift amount for given loaded size");
8235     if (IsBigEndian)
8236       Offset = TySizeInBytes - Offset - getLoadedSize();
8237     return Offset;
8238   }
8239
8240   /// \brief Generate the sequence of instructions to load the slice
8241   /// represented by this object and redirect the uses of this slice to
8242   /// this new sequence of instructions.
8243   /// \pre this->Inst && this->Origin are valid Instructions and this
8244   /// object passed the legal check: LoadedSlice::isLegal returned true.
8245   /// \return The last instruction of the sequence used to load the slice.
8246   SDValue loadSlice() const {
8247     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8248     const SDValue &OldBaseAddr = Origin->getBasePtr();
8249     SDValue BaseAddr = OldBaseAddr;
8250     // Get the offset in that chunk of bytes w.r.t. the endianess.
8251     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8252     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8253     if (Offset) {
8254       // BaseAddr = BaseAddr + Offset.
8255       EVT ArithType = BaseAddr.getValueType();
8256       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8257                               DAG->getConstant(Offset, ArithType));
8258     }
8259
8260     // Create the type of the loaded slice according to its size.
8261     EVT SliceType = getLoadedType();
8262
8263     // Create the load for the slice.
8264     SDValue LastInst = DAG->getLoad(
8265         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8266         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8267         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8268     // If the final type is not the same as the loaded type, this means that
8269     // we have to pad with zero. Create a zero extend for that.
8270     EVT FinalType = Inst->getValueType(0);
8271     if (SliceType != FinalType)
8272       LastInst =
8273           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8274     return LastInst;
8275   }
8276
8277   /// \brief Check if this slice can be merged with an expensive cross register
8278   /// bank copy. E.g.,
8279   /// i = load i32
8280   /// f = bitcast i32 i to float
8281   bool canMergeExpensiveCrossRegisterBankCopy() const {
8282     if (!Inst || !Inst->hasOneUse())
8283       return false;
8284     SDNode *Use = *Inst->use_begin();
8285     if (Use->getOpcode() != ISD::BITCAST)
8286       return false;
8287     assert(DAG && "Missing context");
8288     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8289     EVT ResVT = Use->getValueType(0);
8290     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8291     const TargetRegisterClass *ArgRC =
8292         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8293     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8294       return false;
8295
8296     // At this point, we know that we perform a cross-register-bank copy.
8297     // Check if it is expensive.
8298     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8299     // Assume bitcasts are cheap, unless both register classes do not
8300     // explicitly share a common sub class.
8301     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8302       return false;
8303
8304     // Check if it will be merged with the load.
8305     // 1. Check the alignment constraint.
8306     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8307         ResVT.getTypeForEVT(*DAG->getContext()));
8308
8309     if (RequiredAlignment > getAlignment())
8310       return false;
8311
8312     // 2. Check that the load is a legal operation for that type.
8313     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8314       return false;
8315
8316     // 3. Check that we do not have a zext in the way.
8317     if (Inst->getValueType(0) != getLoadedType())
8318       return false;
8319
8320     return true;
8321   }
8322 };
8323 }
8324
8325 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8326 /// \p UsedBits looks like 0..0 1..1 0..0.
8327 static bool areUsedBitsDense(const APInt &UsedBits) {
8328   // If all the bits are one, this is dense!
8329   if (UsedBits.isAllOnesValue())
8330     return true;
8331
8332   // Get rid of the unused bits on the right.
8333   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8334   // Get rid of the unused bits on the left.
8335   if (NarrowedUsedBits.countLeadingZeros())
8336     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8337   // Check that the chunk of bits is completely used.
8338   return NarrowedUsedBits.isAllOnesValue();
8339 }
8340
8341 /// \brief Check whether or not \p First and \p Second are next to each other
8342 /// in memory. This means that there is no hole between the bits loaded
8343 /// by \p First and the bits loaded by \p Second.
8344 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8345                                      const LoadedSlice &Second) {
8346   assert(First.Origin == Second.Origin && First.Origin &&
8347          "Unable to match different memory origins.");
8348   APInt UsedBits = First.getUsedBits();
8349   assert((UsedBits & Second.getUsedBits()) == 0 &&
8350          "Slices are not supposed to overlap.");
8351   UsedBits |= Second.getUsedBits();
8352   return areUsedBitsDense(UsedBits);
8353 }
8354
8355 /// \brief Adjust the \p GlobalLSCost according to the target
8356 /// paring capabilities and the layout of the slices.
8357 /// \pre \p GlobalLSCost should account for at least as many loads as
8358 /// there is in the slices in \p LoadedSlices.
8359 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8360                                  LoadedSlice::Cost &GlobalLSCost) {
8361   unsigned NumberOfSlices = LoadedSlices.size();
8362   // If there is less than 2 elements, no pairing is possible.
8363   if (NumberOfSlices < 2)
8364     return;
8365
8366   // Sort the slices so that elements that are likely to be next to each
8367   // other in memory are next to each other in the list.
8368   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8369             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8370     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8371     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8372   });
8373   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8374   // First (resp. Second) is the first (resp. Second) potentially candidate
8375   // to be placed in a paired load.
8376   const LoadedSlice *First = NULL;
8377   const LoadedSlice *Second = NULL;
8378   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8379                 // Set the beginning of the pair.
8380                                                            First = Second) {
8381
8382     Second = &LoadedSlices[CurrSlice];
8383
8384     // If First is NULL, it means we start a new pair.
8385     // Get to the next slice.
8386     if (!First)
8387       continue;
8388
8389     EVT LoadedType = First->getLoadedType();
8390
8391     // If the types of the slices are different, we cannot pair them.
8392     if (LoadedType != Second->getLoadedType())
8393       continue;
8394
8395     // Check if the target supplies paired loads for this type.
8396     unsigned RequiredAlignment = 0;
8397     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8398       // move to the next pair, this type is hopeless.
8399       Second = NULL;
8400       continue;
8401     }
8402     // Check if we meet the alignment requirement.
8403     if (RequiredAlignment > First->getAlignment())
8404       continue;
8405
8406     // Check that both loads are next to each other in memory.
8407     if (!areSlicesNextToEachOther(*First, *Second))
8408       continue;
8409
8410     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8411     --GlobalLSCost.Loads;
8412     // Move to the next pair.
8413     Second = NULL;
8414   }
8415 }
8416
8417 /// \brief Check the profitability of all involved LoadedSlice.
8418 /// Currently, it is considered profitable if there is exactly two
8419 /// involved slices (1) which are (2) next to each other in memory, and
8420 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8421 ///
8422 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8423 /// the elements themselves.
8424 ///
8425 /// FIXME: When the cost model will be mature enough, we can relax
8426 /// constraints (1) and (2).
8427 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8428                                 const APInt &UsedBits, bool ForCodeSize) {
8429   unsigned NumberOfSlices = LoadedSlices.size();
8430   if (StressLoadSlicing)
8431     return NumberOfSlices > 1;
8432
8433   // Check (1).
8434   if (NumberOfSlices != 2)
8435     return false;
8436
8437   // Check (2).
8438   if (!areUsedBitsDense(UsedBits))
8439     return false;
8440
8441   // Check (3).
8442   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8443   // The original code has one big load.
8444   OrigCost.Loads = 1;
8445   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8446     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8447     // Accumulate the cost of all the slices.
8448     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8449     GlobalSlicingCost += SliceCost;
8450
8451     // Account as cost in the original configuration the gain obtained
8452     // with the current slices.
8453     OrigCost.addSliceGain(LS);
8454   }
8455
8456   // If the target supports paired load, adjust the cost accordingly.
8457   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8458   return OrigCost > GlobalSlicingCost;
8459 }
8460
8461 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8462 /// operations, split it in the various pieces being extracted.
8463 ///
8464 /// This sort of thing is introduced by SROA.
8465 /// This slicing takes care not to insert overlapping loads.
8466 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8467 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8468   if (Level < AfterLegalizeDAG)
8469     return false;
8470
8471   LoadSDNode *LD = cast<LoadSDNode>(N);
8472   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8473       !LD->getValueType(0).isInteger())
8474     return false;
8475
8476   // Keep track of already used bits to detect overlapping values.
8477   // In that case, we will just abort the transformation.
8478   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8479
8480   SmallVector<LoadedSlice, 4> LoadedSlices;
8481
8482   // Check if this load is used as several smaller chunks of bits.
8483   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8484   // of computation for each trunc.
8485   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8486        UI != UIEnd; ++UI) {
8487     // Skip the uses of the chain.
8488     if (UI.getUse().getResNo() != 0)
8489       continue;
8490
8491     SDNode *User = *UI;
8492     unsigned Shift = 0;
8493
8494     // Check if this is a trunc(lshr).
8495     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8496         isa<ConstantSDNode>(User->getOperand(1))) {
8497       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8498       User = *User->use_begin();
8499     }
8500
8501     // At this point, User is a Truncate, iff we encountered, trunc or
8502     // trunc(lshr).
8503     if (User->getOpcode() != ISD::TRUNCATE)
8504       return false;
8505
8506     // The width of the type must be a power of 2 and greater than 8-bits.
8507     // Otherwise the load cannot be represented in LLVM IR.
8508     // Moreover, if we shifted with a non-8-bits multiple, the slice
8509     // will be across several bytes. We do not support that.
8510     unsigned Width = User->getValueSizeInBits(0);
8511     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8512       return 0;
8513
8514     // Build the slice for this chain of computations.
8515     LoadedSlice LS(User, LD, Shift, &DAG);
8516     APInt CurrentUsedBits = LS.getUsedBits();
8517
8518     // Check if this slice overlaps with another.
8519     if ((CurrentUsedBits & UsedBits) != 0)
8520       return false;
8521     // Update the bits used globally.
8522     UsedBits |= CurrentUsedBits;
8523
8524     // Check if the new slice would be legal.
8525     if (!LS.isLegal())
8526       return false;
8527
8528     // Record the slice.
8529     LoadedSlices.push_back(LS);
8530   }
8531
8532   // Abort slicing if it does not seem to be profitable.
8533   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8534     return false;
8535
8536   ++SlicedLoads;
8537
8538   // Rewrite each chain to use an independent load.
8539   // By construction, each chain can be represented by a unique load.
8540
8541   // Prepare the argument for the new token factor for all the slices.
8542   SmallVector<SDValue, 8> ArgChains;
8543   for (SmallVectorImpl<LoadedSlice>::const_iterator
8544            LSIt = LoadedSlices.begin(),
8545            LSItEnd = LoadedSlices.end();
8546        LSIt != LSItEnd; ++LSIt) {
8547     SDValue SliceInst = LSIt->loadSlice();
8548     CombineTo(LSIt->Inst, SliceInst, true);
8549     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8550       SliceInst = SliceInst.getOperand(0);
8551     assert(SliceInst->getOpcode() == ISD::LOAD &&
8552            "It takes more than a zext to get to the loaded slice!!");
8553     ArgChains.push_back(SliceInst.getValue(1));
8554   }
8555
8556   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8557                               &ArgChains[0], ArgChains.size());
8558   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8559   return true;
8560 }
8561
8562 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8563 /// load is having specific bytes cleared out.  If so, return the byte size
8564 /// being masked out and the shift amount.
8565 static std::pair<unsigned, unsigned>
8566 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8567   std::pair<unsigned, unsigned> Result(0, 0);
8568
8569   // Check for the structure we're looking for.
8570   if (V->getOpcode() != ISD::AND ||
8571       !isa<ConstantSDNode>(V->getOperand(1)) ||
8572       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8573     return Result;
8574
8575   // Check the chain and pointer.
8576   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8577   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8578
8579   // The store should be chained directly to the load or be an operand of a
8580   // tokenfactor.
8581   if (LD == Chain.getNode())
8582     ; // ok.
8583   else if (Chain->getOpcode() != ISD::TokenFactor)
8584     return Result; // Fail.
8585   else {
8586     bool isOk = false;
8587     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8588       if (Chain->getOperand(i).getNode() == LD) {
8589         isOk = true;
8590         break;
8591       }
8592     if (!isOk) return Result;
8593   }
8594
8595   // This only handles simple types.
8596   if (V.getValueType() != MVT::i16 &&
8597       V.getValueType() != MVT::i32 &&
8598       V.getValueType() != MVT::i64)
8599     return Result;
8600
8601   // Check the constant mask.  Invert it so that the bits being masked out are
8602   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8603   // follow the sign bit for uniformity.
8604   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8605   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8606   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8607   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8608   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8609   if (NotMaskLZ == 64) return Result;  // All zero mask.
8610
8611   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8612   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8613     return Result;
8614
8615   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8616   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8617     NotMaskLZ -= 64-V.getValueSizeInBits();
8618
8619   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8620   switch (MaskedBytes) {
8621   case 1:
8622   case 2:
8623   case 4: break;
8624   default: return Result; // All one mask, or 5-byte mask.
8625   }
8626
8627   // Verify that the first bit starts at a multiple of mask so that the access
8628   // is aligned the same as the access width.
8629   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8630
8631   Result.first = MaskedBytes;
8632   Result.second = NotMaskTZ/8;
8633   return Result;
8634 }
8635
8636
8637 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8638 /// provides a value as specified by MaskInfo.  If so, replace the specified
8639 /// store with a narrower store of truncated IVal.
8640 static SDNode *
8641 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8642                                 SDValue IVal, StoreSDNode *St,
8643                                 DAGCombiner *DC) {
8644   unsigned NumBytes = MaskInfo.first;
8645   unsigned ByteShift = MaskInfo.second;
8646   SelectionDAG &DAG = DC->getDAG();
8647
8648   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8649   // that uses this.  If not, this is not a replacement.
8650   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8651                                   ByteShift*8, (ByteShift+NumBytes)*8);
8652   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8653
8654   // Check that it is legal on the target to do this.  It is legal if the new
8655   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8656   // legalization.
8657   MVT VT = MVT::getIntegerVT(NumBytes*8);
8658   if (!DC->isTypeLegal(VT))
8659     return 0;
8660
8661   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8662   // shifted by ByteShift and truncated down to NumBytes.
8663   if (ByteShift)
8664     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8665                        DAG.getConstant(ByteShift*8,
8666                                     DC->getShiftAmountTy(IVal.getValueType())));
8667
8668   // Figure out the offset for the store and the alignment of the access.
8669   unsigned StOffset;
8670   unsigned NewAlign = St->getAlignment();
8671
8672   if (DAG.getTargetLoweringInfo().isLittleEndian())
8673     StOffset = ByteShift;
8674   else
8675     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8676
8677   SDValue Ptr = St->getBasePtr();
8678   if (StOffset) {
8679     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8680                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8681     NewAlign = MinAlign(NewAlign, StOffset);
8682   }
8683
8684   // Truncate down to the new size.
8685   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8686
8687   ++OpsNarrowed;
8688   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8689                       St->getPointerInfo().getWithOffset(StOffset),
8690                       false, false, NewAlign).getNode();
8691 }
8692
8693
8694 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8695 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8696 /// of the loaded bits, try narrowing the load and store if it would end up
8697 /// being a win for performance or code size.
8698 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8699   StoreSDNode *ST  = cast<StoreSDNode>(N);
8700   if (ST->isVolatile())
8701     return SDValue();
8702
8703   SDValue Chain = ST->getChain();
8704   SDValue Value = ST->getValue();
8705   SDValue Ptr   = ST->getBasePtr();
8706   EVT VT = Value.getValueType();
8707
8708   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8709     return SDValue();
8710
8711   unsigned Opc = Value.getOpcode();
8712
8713   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8714   // is a byte mask indicating a consecutive number of bytes, check to see if
8715   // Y is known to provide just those bytes.  If so, we try to replace the
8716   // load + replace + store sequence with a single (narrower) store, which makes
8717   // the load dead.
8718   if (Opc == ISD::OR) {
8719     std::pair<unsigned, unsigned> MaskedLoad;
8720     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8721     if (MaskedLoad.first)
8722       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8723                                                   Value.getOperand(1), ST,this))
8724         return SDValue(NewST, 0);
8725
8726     // Or is commutative, so try swapping X and Y.
8727     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8728     if (MaskedLoad.first)
8729       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8730                                                   Value.getOperand(0), ST,this))
8731         return SDValue(NewST, 0);
8732   }
8733
8734   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8735       Value.getOperand(1).getOpcode() != ISD::Constant)
8736     return SDValue();
8737
8738   SDValue N0 = Value.getOperand(0);
8739   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8740       Chain == SDValue(N0.getNode(), 1)) {
8741     LoadSDNode *LD = cast<LoadSDNode>(N0);
8742     if (LD->getBasePtr() != Ptr ||
8743         LD->getPointerInfo().getAddrSpace() !=
8744         ST->getPointerInfo().getAddrSpace())
8745       return SDValue();
8746
8747     // Find the type to narrow it the load / op / store to.
8748     SDValue N1 = Value.getOperand(1);
8749     unsigned BitWidth = N1.getValueSizeInBits();
8750     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8751     if (Opc == ISD::AND)
8752       Imm ^= APInt::getAllOnesValue(BitWidth);
8753     if (Imm == 0 || Imm.isAllOnesValue())
8754       return SDValue();
8755     unsigned ShAmt = Imm.countTrailingZeros();
8756     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8757     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8758     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8759     while (NewBW < BitWidth &&
8760            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8761              TLI.isNarrowingProfitable(VT, NewVT))) {
8762       NewBW = NextPowerOf2(NewBW);
8763       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8764     }
8765     if (NewBW >= BitWidth)
8766       return SDValue();
8767
8768     // If the lsb changed does not start at the type bitwidth boundary,
8769     // start at the previous one.
8770     if (ShAmt % NewBW)
8771       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8772     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8773                                    std::min(BitWidth, ShAmt + NewBW));
8774     if ((Imm & Mask) == Imm) {
8775       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8776       if (Opc == ISD::AND)
8777         NewImm ^= APInt::getAllOnesValue(NewBW);
8778       uint64_t PtrOff = ShAmt / 8;
8779       // For big endian targets, we need to adjust the offset to the pointer to
8780       // load the correct bytes.
8781       if (TLI.isBigEndian())
8782         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8783
8784       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8785       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8786       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8787         return SDValue();
8788
8789       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8790                                    Ptr.getValueType(), Ptr,
8791                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8792       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8793                                   LD->getChain(), NewPtr,
8794                                   LD->getPointerInfo().getWithOffset(PtrOff),
8795                                   LD->isVolatile(), LD->isNonTemporal(),
8796                                   LD->isInvariant(), NewAlign,
8797                                   LD->getTBAAInfo());
8798       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8799                                    DAG.getConstant(NewImm, NewVT));
8800       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8801                                    NewVal, NewPtr,
8802                                    ST->getPointerInfo().getWithOffset(PtrOff),
8803                                    false, false, NewAlign);
8804
8805       AddToWorkList(NewPtr.getNode());
8806       AddToWorkList(NewLD.getNode());
8807       AddToWorkList(NewVal.getNode());
8808       WorkListRemover DeadNodes(*this);
8809       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8810       ++OpsNarrowed;
8811       return NewST;
8812     }
8813   }
8814
8815   return SDValue();
8816 }
8817
8818 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8819 /// if the load value isn't used by any other operations, then consider
8820 /// transforming the pair to integer load / store operations if the target
8821 /// deems the transformation profitable.
8822 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8823   StoreSDNode *ST  = cast<StoreSDNode>(N);
8824   SDValue Chain = ST->getChain();
8825   SDValue Value = ST->getValue();
8826   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8827       Value.hasOneUse() &&
8828       Chain == SDValue(Value.getNode(), 1)) {
8829     LoadSDNode *LD = cast<LoadSDNode>(Value);
8830     EVT VT = LD->getMemoryVT();
8831     if (!VT.isFloatingPoint() ||
8832         VT != ST->getMemoryVT() ||
8833         LD->isNonTemporal() ||
8834         ST->isNonTemporal() ||
8835         LD->getPointerInfo().getAddrSpace() != 0 ||
8836         ST->getPointerInfo().getAddrSpace() != 0)
8837       return SDValue();
8838
8839     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8840     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8841         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8842         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8843         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8844       return SDValue();
8845
8846     unsigned LDAlign = LD->getAlignment();
8847     unsigned STAlign = ST->getAlignment();
8848     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8849     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8850     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8851       return SDValue();
8852
8853     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8854                                 LD->getChain(), LD->getBasePtr(),
8855                                 LD->getPointerInfo(),
8856                                 false, false, false, LDAlign);
8857
8858     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8859                                  NewLD, ST->getBasePtr(),
8860                                  ST->getPointerInfo(),
8861                                  false, false, STAlign);
8862
8863     AddToWorkList(NewLD.getNode());
8864     AddToWorkList(NewST.getNode());
8865     WorkListRemover DeadNodes(*this);
8866     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8867     ++LdStFP2Int;
8868     return NewST;
8869   }
8870
8871   return SDValue();
8872 }
8873
8874 /// Helper struct to parse and store a memory address as base + index + offset.
8875 /// We ignore sign extensions when it is safe to do so.
8876 /// The following two expressions are not equivalent. To differentiate we need
8877 /// to store whether there was a sign extension involved in the index
8878 /// computation.
8879 ///  (load (i64 add (i64 copyfromreg %c)
8880 ///                 (i64 signextend (add (i8 load %index)
8881 ///                                      (i8 1))))
8882 /// vs
8883 ///
8884 /// (load (i64 add (i64 copyfromreg %c)
8885 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8886 ///                                         (i32 1)))))
8887 struct BaseIndexOffset {
8888   SDValue Base;
8889   SDValue Index;
8890   int64_t Offset;
8891   bool IsIndexSignExt;
8892
8893   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8894
8895   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8896                   bool IsIndexSignExt) :
8897     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8898
8899   bool equalBaseIndex(const BaseIndexOffset &Other) {
8900     return Other.Base == Base && Other.Index == Index &&
8901       Other.IsIndexSignExt == IsIndexSignExt;
8902   }
8903
8904   /// Parses tree in Ptr for base, index, offset addresses.
8905   static BaseIndexOffset match(SDValue Ptr) {
8906     bool IsIndexSignExt = false;
8907
8908     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8909     // instruction, then it could be just the BASE or everything else we don't
8910     // know how to handle. Just use Ptr as BASE and give up.
8911     if (Ptr->getOpcode() != ISD::ADD)
8912       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8913
8914     // We know that we have at least an ADD instruction. Try to pattern match
8915     // the simple case of BASE + OFFSET.
8916     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8917       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8918       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8919                               IsIndexSignExt);
8920     }
8921
8922     // Inside a loop the current BASE pointer is calculated using an ADD and a
8923     // MUL instruction. In this case Ptr is the actual BASE pointer.
8924     // (i64 add (i64 %array_ptr)
8925     //          (i64 mul (i64 %induction_var)
8926     //                   (i64 %element_size)))
8927     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8928       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8929
8930     // Look at Base + Index + Offset cases.
8931     SDValue Base = Ptr->getOperand(0);
8932     SDValue IndexOffset = Ptr->getOperand(1);
8933
8934     // Skip signextends.
8935     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8936       IndexOffset = IndexOffset->getOperand(0);
8937       IsIndexSignExt = true;
8938     }
8939
8940     // Either the case of Base + Index (no offset) or something else.
8941     if (IndexOffset->getOpcode() != ISD::ADD)
8942       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8943
8944     // Now we have the case of Base + Index + offset.
8945     SDValue Index = IndexOffset->getOperand(0);
8946     SDValue Offset = IndexOffset->getOperand(1);
8947
8948     if (!isa<ConstantSDNode>(Offset))
8949       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8950
8951     // Ignore signextends.
8952     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8953       Index = Index->getOperand(0);
8954       IsIndexSignExt = true;
8955     } else IsIndexSignExt = false;
8956
8957     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8958     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8959   }
8960 };
8961
8962 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8963 /// is located in a sequence of memory operations connected by a chain.
8964 struct MemOpLink {
8965   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8966     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8967   // Ptr to the mem node.
8968   LSBaseSDNode *MemNode;
8969   // Offset from the base ptr.
8970   int64_t OffsetFromBase;
8971   // What is the sequence number of this mem node.
8972   // Lowest mem operand in the DAG starts at zero.
8973   unsigned SequenceNum;
8974 };
8975
8976 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8977   EVT MemVT = St->getMemoryVT();
8978   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8979   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8980     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8981
8982   // Don't merge vectors into wider inputs.
8983   if (MemVT.isVector() || !MemVT.isSimple())
8984     return false;
8985
8986   // Perform an early exit check. Do not bother looking at stored values that
8987   // are not constants or loads.
8988   SDValue StoredVal = St->getValue();
8989   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8990   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8991       !IsLoadSrc)
8992     return false;
8993
8994   // Only look at ends of store sequences.
8995   SDValue Chain = SDValue(St, 1);
8996   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8997     return false;
8998
8999   // This holds the base pointer, index, and the offset in bytes from the base
9000   // pointer.
9001   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9002
9003   // We must have a base and an offset.
9004   if (!BasePtr.Base.getNode())
9005     return false;
9006
9007   // Do not handle stores to undef base pointers.
9008   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9009     return false;
9010
9011   // Save the LoadSDNodes that we find in the chain.
9012   // We need to make sure that these nodes do not interfere with
9013   // any of the store nodes.
9014   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9015
9016   // Save the StoreSDNodes that we find in the chain.
9017   SmallVector<MemOpLink, 8> StoreNodes;
9018
9019   // Walk up the chain and look for nodes with offsets from the same
9020   // base pointer. Stop when reaching an instruction with a different kind
9021   // or instruction which has a different base pointer.
9022   unsigned Seq = 0;
9023   StoreSDNode *Index = St;
9024   while (Index) {
9025     // If the chain has more than one use, then we can't reorder the mem ops.
9026     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9027       break;
9028
9029     // Find the base pointer and offset for this memory node.
9030     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9031
9032     // Check that the base pointer is the same as the original one.
9033     if (!Ptr.equalBaseIndex(BasePtr))
9034       break;
9035
9036     // Check that the alignment is the same.
9037     if (Index->getAlignment() != St->getAlignment())
9038       break;
9039
9040     // The memory operands must not be volatile.
9041     if (Index->isVolatile() || Index->isIndexed())
9042       break;
9043
9044     // No truncation.
9045     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9046       if (St->isTruncatingStore())
9047         break;
9048
9049     // The stored memory type must be the same.
9050     if (Index->getMemoryVT() != MemVT)
9051       break;
9052
9053     // We do not allow unaligned stores because we want to prevent overriding
9054     // stores.
9055     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9056       break;
9057
9058     // We found a potential memory operand to merge.
9059     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9060
9061     // Find the next memory operand in the chain. If the next operand in the
9062     // chain is a store then move up and continue the scan with the next
9063     // memory operand. If the next operand is a load save it and use alias
9064     // information to check if it interferes with anything.
9065     SDNode *NextInChain = Index->getChain().getNode();
9066     while (1) {
9067       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9068         // We found a store node. Use it for the next iteration.
9069         Index = STn;
9070         break;
9071       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9072         if (Ldn->isVolatile()) {
9073           Index = NULL;
9074           break;
9075         }
9076
9077         // Save the load node for later. Continue the scan.
9078         AliasLoadNodes.push_back(Ldn);
9079         NextInChain = Ldn->getChain().getNode();
9080         continue;
9081       } else {
9082         Index = NULL;
9083         break;
9084       }
9085     }
9086   }
9087
9088   // Check if there is anything to merge.
9089   if (StoreNodes.size() < 2)
9090     return false;
9091
9092   // Sort the memory operands according to their distance from the base pointer.
9093   std::sort(StoreNodes.begin(), StoreNodes.end(),
9094             [](MemOpLink LHS, MemOpLink RHS) {
9095     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9096            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9097             LHS.SequenceNum > RHS.SequenceNum);
9098   });
9099
9100   // Scan the memory operations on the chain and find the first non-consecutive
9101   // store memory address.
9102   unsigned LastConsecutiveStore = 0;
9103   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9104   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9105
9106     // Check that the addresses are consecutive starting from the second
9107     // element in the list of stores.
9108     if (i > 0) {
9109       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9110       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9111         break;
9112     }
9113
9114     bool Alias = false;
9115     // Check if this store interferes with any of the loads that we found.
9116     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9117       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9118         Alias = true;
9119         break;
9120       }
9121     // We found a load that alias with this store. Stop the sequence.
9122     if (Alias)
9123       break;
9124
9125     // Mark this node as useful.
9126     LastConsecutiveStore = i;
9127   }
9128
9129   // The node with the lowest store address.
9130   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9131
9132   // Store the constants into memory as one consecutive store.
9133   if (!IsLoadSrc) {
9134     unsigned LastLegalType = 0;
9135     unsigned LastLegalVectorType = 0;
9136     bool NonZero = false;
9137     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9138       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9139       SDValue StoredVal = St->getValue();
9140
9141       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9142         NonZero |= !C->isNullValue();
9143       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9144         NonZero |= !C->getConstantFPValue()->isNullValue();
9145       } else {
9146         // Non-constant.
9147         break;
9148       }
9149
9150       // Find a legal type for the constant store.
9151       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9152       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9153       if (TLI.isTypeLegal(StoreTy))
9154         LastLegalType = i+1;
9155       // Or check whether a truncstore is legal.
9156       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9157                TargetLowering::TypePromoteInteger) {
9158         EVT LegalizedStoredValueTy =
9159           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9160         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9161           LastLegalType = i+1;
9162       }
9163
9164       // Find a legal type for the vector store.
9165       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9166       if (TLI.isTypeLegal(Ty))
9167         LastLegalVectorType = i + 1;
9168     }
9169
9170     // We only use vectors if the constant is known to be zero and the
9171     // function is not marked with the noimplicitfloat attribute.
9172     if (NonZero || NoVectors)
9173       LastLegalVectorType = 0;
9174
9175     // Check if we found a legal integer type to store.
9176     if (LastLegalType == 0 && LastLegalVectorType == 0)
9177       return false;
9178
9179     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9180     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9181
9182     // Make sure we have something to merge.
9183     if (NumElem < 2)
9184       return false;
9185
9186     unsigned EarliestNodeUsed = 0;
9187     for (unsigned i=0; i < NumElem; ++i) {
9188       // Find a chain for the new wide-store operand. Notice that some
9189       // of the store nodes that we found may not be selected for inclusion
9190       // in the wide store. The chain we use needs to be the chain of the
9191       // earliest store node which is *used* and replaced by the wide store.
9192       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9193         EarliestNodeUsed = i;
9194     }
9195
9196     // The earliest Node in the DAG.
9197     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9198     SDLoc DL(StoreNodes[0].MemNode);
9199
9200     SDValue StoredVal;
9201     if (UseVector) {
9202       // Find a legal type for the vector store.
9203       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9204       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9205       StoredVal = DAG.getConstant(0, Ty);
9206     } else {
9207       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9208       APInt StoreInt(StoreBW, 0);
9209
9210       // Construct a single integer constant which is made of the smaller
9211       // constant inputs.
9212       bool IsLE = TLI.isLittleEndian();
9213       for (unsigned i = 0; i < NumElem ; ++i) {
9214         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9215         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9216         SDValue Val = St->getValue();
9217         StoreInt<<=ElementSizeBytes*8;
9218         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9219           StoreInt|=C->getAPIntValue().zext(StoreBW);
9220         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9221           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9222         } else {
9223           assert(false && "Invalid constant element type");
9224         }
9225       }
9226
9227       // Create the new Load and Store operations.
9228       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9229       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9230     }
9231
9232     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9233                                     FirstInChain->getBasePtr(),
9234                                     FirstInChain->getPointerInfo(),
9235                                     false, false,
9236                                     FirstInChain->getAlignment());
9237
9238     // Replace the first store with the new store
9239     CombineTo(EarliestOp, NewStore);
9240     // Erase all other stores.
9241     for (unsigned i = 0; i < NumElem ; ++i) {
9242       if (StoreNodes[i].MemNode == EarliestOp)
9243         continue;
9244       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9245       // ReplaceAllUsesWith will replace all uses that existed when it was
9246       // called, but graph optimizations may cause new ones to appear. For
9247       // example, the case in pr14333 looks like
9248       //
9249       //  St's chain -> St -> another store -> X
9250       //
9251       // And the only difference from St to the other store is the chain.
9252       // When we change it's chain to be St's chain they become identical,
9253       // get CSEed and the net result is that X is now a use of St.
9254       // Since we know that St is redundant, just iterate.
9255       while (!St->use_empty())
9256         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9257       removeFromWorkList(St);
9258       DAG.DeleteNode(St);
9259     }
9260
9261     return true;
9262   }
9263
9264   // Below we handle the case of multiple consecutive stores that
9265   // come from multiple consecutive loads. We merge them into a single
9266   // wide load and a single wide store.
9267
9268   // Look for load nodes which are used by the stored values.
9269   SmallVector<MemOpLink, 8> LoadNodes;
9270
9271   // Find acceptable loads. Loads need to have the same chain (token factor),
9272   // must not be zext, volatile, indexed, and they must be consecutive.
9273   BaseIndexOffset LdBasePtr;
9274   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9275     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9276     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9277     if (!Ld) break;
9278
9279     // Loads must only have one use.
9280     if (!Ld->hasNUsesOfValue(1, 0))
9281       break;
9282
9283     // Check that the alignment is the same as the stores.
9284     if (Ld->getAlignment() != St->getAlignment())
9285       break;
9286
9287     // The memory operands must not be volatile.
9288     if (Ld->isVolatile() || Ld->isIndexed())
9289       break;
9290
9291     // We do not accept ext loads.
9292     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9293       break;
9294
9295     // The stored memory type must be the same.
9296     if (Ld->getMemoryVT() != MemVT)
9297       break;
9298
9299     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9300     // If this is not the first ptr that we check.
9301     if (LdBasePtr.Base.getNode()) {
9302       // The base ptr must be the same.
9303       if (!LdPtr.equalBaseIndex(LdBasePtr))
9304         break;
9305     } else {
9306       // Check that all other base pointers are the same as this one.
9307       LdBasePtr = LdPtr;
9308     }
9309
9310     // We found a potential memory operand to merge.
9311     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9312   }
9313
9314   if (LoadNodes.size() < 2)
9315     return false;
9316
9317   // Scan the memory operations on the chain and find the first non-consecutive
9318   // load memory address. These variables hold the index in the store node
9319   // array.
9320   unsigned LastConsecutiveLoad = 0;
9321   // This variable refers to the size and not index in the array.
9322   unsigned LastLegalVectorType = 0;
9323   unsigned LastLegalIntegerType = 0;
9324   StartAddress = LoadNodes[0].OffsetFromBase;
9325   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9326   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9327     // All loads much share the same chain.
9328     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9329       break;
9330
9331     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9332     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9333       break;
9334     LastConsecutiveLoad = i;
9335
9336     // Find a legal type for the vector store.
9337     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9338     if (TLI.isTypeLegal(StoreTy))
9339       LastLegalVectorType = i + 1;
9340
9341     // Find a legal type for the integer store.
9342     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9343     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9344     if (TLI.isTypeLegal(StoreTy))
9345       LastLegalIntegerType = i + 1;
9346     // Or check whether a truncstore and extload is legal.
9347     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9348              TargetLowering::TypePromoteInteger) {
9349       EVT LegalizedStoredValueTy =
9350         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9351       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9352           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9353           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9354           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9355         LastLegalIntegerType = i+1;
9356     }
9357   }
9358
9359   // Only use vector types if the vector type is larger than the integer type.
9360   // If they are the same, use integers.
9361   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9362   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9363
9364   // We add +1 here because the LastXXX variables refer to location while
9365   // the NumElem refers to array/index size.
9366   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9367   NumElem = std::min(LastLegalType, NumElem);
9368
9369   if (NumElem < 2)
9370     return false;
9371
9372   // The earliest Node in the DAG.
9373   unsigned EarliestNodeUsed = 0;
9374   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9375   for (unsigned i=1; i<NumElem; ++i) {
9376     // Find a chain for the new wide-store operand. Notice that some
9377     // of the store nodes that we found may not be selected for inclusion
9378     // in the wide store. The chain we use needs to be the chain of the
9379     // earliest store node which is *used* and replaced by the wide store.
9380     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9381       EarliestNodeUsed = i;
9382   }
9383
9384   // Find if it is better to use vectors or integers to load and store
9385   // to memory.
9386   EVT JointMemOpVT;
9387   if (UseVectorTy) {
9388     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9389   } else {
9390     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9391     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9392   }
9393
9394   SDLoc LoadDL(LoadNodes[0].MemNode);
9395   SDLoc StoreDL(StoreNodes[0].MemNode);
9396
9397   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9398   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9399                                 FirstLoad->getChain(),
9400                                 FirstLoad->getBasePtr(),
9401                                 FirstLoad->getPointerInfo(),
9402                                 false, false, false,
9403                                 FirstLoad->getAlignment());
9404
9405   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9406                                   FirstInChain->getBasePtr(),
9407                                   FirstInChain->getPointerInfo(), false, false,
9408                                   FirstInChain->getAlignment());
9409
9410   // Replace one of the loads with the new load.
9411   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9412   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9413                                 SDValue(NewLoad.getNode(), 1));
9414
9415   // Remove the rest of the load chains.
9416   for (unsigned i = 1; i < NumElem ; ++i) {
9417     // Replace all chain users of the old load nodes with the chain of the new
9418     // load node.
9419     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9420     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9421   }
9422
9423   // Replace the first store with the new store.
9424   CombineTo(EarliestOp, NewStore);
9425   // Erase all other stores.
9426   for (unsigned i = 0; i < NumElem ; ++i) {
9427     // Remove all Store nodes.
9428     if (StoreNodes[i].MemNode == EarliestOp)
9429       continue;
9430     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9431     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9432     removeFromWorkList(St);
9433     DAG.DeleteNode(St);
9434   }
9435
9436   return true;
9437 }
9438
9439 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9440   StoreSDNode *ST  = cast<StoreSDNode>(N);
9441   SDValue Chain = ST->getChain();
9442   SDValue Value = ST->getValue();
9443   SDValue Ptr   = ST->getBasePtr();
9444
9445   // If this is a store of a bit convert, store the input value if the
9446   // resultant store does not need a higher alignment than the original.
9447   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9448       ST->isUnindexed()) {
9449     unsigned OrigAlign = ST->getAlignment();
9450     EVT SVT = Value.getOperand(0).getValueType();
9451     unsigned Align = TLI.getDataLayout()->
9452       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9453     if (Align <= OrigAlign &&
9454         ((!LegalOperations && !ST->isVolatile()) ||
9455          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9456       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9457                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9458                           ST->isNonTemporal(), OrigAlign,
9459                           ST->getTBAAInfo());
9460   }
9461
9462   // Turn 'store undef, Ptr' -> nothing.
9463   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9464     return Chain;
9465
9466   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9467   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9468     // NOTE: If the original store is volatile, this transform must not increase
9469     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9470     // processor operation but an i64 (which is not legal) requires two.  So the
9471     // transform should not be done in this case.
9472     if (Value.getOpcode() != ISD::TargetConstantFP) {
9473       SDValue Tmp;
9474       switch (CFP->getSimpleValueType(0).SimpleTy) {
9475       default: llvm_unreachable("Unknown FP type");
9476       case MVT::f16:    // We don't do this for these yet.
9477       case MVT::f80:
9478       case MVT::f128:
9479       case MVT::ppcf128:
9480         break;
9481       case MVT::f32:
9482         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9483             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9484           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9485                               bitcastToAPInt().getZExtValue(), MVT::i32);
9486           return DAG.getStore(Chain, SDLoc(N), Tmp,
9487                               Ptr, ST->getMemOperand());
9488         }
9489         break;
9490       case MVT::f64:
9491         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9492              !ST->isVolatile()) ||
9493             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9494           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9495                                 getZExtValue(), MVT::i64);
9496           return DAG.getStore(Chain, SDLoc(N), Tmp,
9497                               Ptr, ST->getMemOperand());
9498         }
9499
9500         if (!ST->isVolatile() &&
9501             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9502           // Many FP stores are not made apparent until after legalize, e.g. for
9503           // argument passing.  Since this is so common, custom legalize the
9504           // 64-bit integer store into two 32-bit stores.
9505           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9506           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9507           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9508           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9509
9510           unsigned Alignment = ST->getAlignment();
9511           bool isVolatile = ST->isVolatile();
9512           bool isNonTemporal = ST->isNonTemporal();
9513           const MDNode *TBAAInfo = ST->getTBAAInfo();
9514
9515           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9516                                      Ptr, ST->getPointerInfo(),
9517                                      isVolatile, isNonTemporal,
9518                                      ST->getAlignment(), TBAAInfo);
9519           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9520                             DAG.getConstant(4, Ptr.getValueType()));
9521           Alignment = MinAlign(Alignment, 4U);
9522           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9523                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9524                                      isVolatile, isNonTemporal,
9525                                      Alignment, TBAAInfo);
9526           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9527                              St0, St1);
9528         }
9529
9530         break;
9531       }
9532     }
9533   }
9534
9535   // Try to infer better alignment information than the store already has.
9536   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9537     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9538       if (Align > ST->getAlignment())
9539         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9540                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9541                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9542                                  ST->getTBAAInfo());
9543     }
9544   }
9545
9546   // Try transforming a pair floating point load / store ops to integer
9547   // load / store ops.
9548   SDValue NewST = TransformFPLoadStorePair(N);
9549   if (NewST.getNode())
9550     return NewST;
9551
9552   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9553     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9554 #ifndef NDEBUG
9555   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9556       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9557     UseAA = false;
9558 #endif
9559   if (UseAA && ST->isUnindexed()) {
9560     // Walk up chain skipping non-aliasing memory nodes.
9561     SDValue BetterChain = FindBetterChain(N, Chain);
9562
9563     // If there is a better chain.
9564     if (Chain != BetterChain) {
9565       SDValue ReplStore;
9566
9567       // Replace the chain to avoid dependency.
9568       if (ST->isTruncatingStore()) {
9569         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9570                                       ST->getMemoryVT(), ST->getMemOperand());
9571       } else {
9572         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9573                                  ST->getMemOperand());
9574       }
9575
9576       // Create token to keep both nodes around.
9577       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9578                                   MVT::Other, Chain, ReplStore);
9579
9580       // Make sure the new and old chains are cleaned up.
9581       AddToWorkList(Token.getNode());
9582
9583       // Don't add users to work list.
9584       return CombineTo(N, Token, false);
9585     }
9586   }
9587
9588   // Try transforming N to an indexed store.
9589   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9590     return SDValue(N, 0);
9591
9592   // FIXME: is there such a thing as a truncating indexed store?
9593   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9594       Value.getValueType().isInteger()) {
9595     // See if we can simplify the input to this truncstore with knowledge that
9596     // only the low bits are being used.  For example:
9597     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9598     SDValue Shorter =
9599       GetDemandedBits(Value,
9600                       APInt::getLowBitsSet(
9601                         Value.getValueType().getScalarType().getSizeInBits(),
9602                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9603     AddToWorkList(Value.getNode());
9604     if (Shorter.getNode())
9605       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9606                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9607
9608     // Otherwise, see if we can simplify the operation with
9609     // SimplifyDemandedBits, which only works if the value has a single use.
9610     if (SimplifyDemandedBits(Value,
9611                         APInt::getLowBitsSet(
9612                           Value.getValueType().getScalarType().getSizeInBits(),
9613                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9614       return SDValue(N, 0);
9615   }
9616
9617   // If this is a load followed by a store to the same location, then the store
9618   // is dead/noop.
9619   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9620     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9621         ST->isUnindexed() && !ST->isVolatile() &&
9622         // There can't be any side effects between the load and store, such as
9623         // a call or store.
9624         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9625       // The store is dead, remove it.
9626       return Chain;
9627     }
9628   }
9629
9630   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9631   // truncating store.  We can do this even if this is already a truncstore.
9632   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9633       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9634       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9635                             ST->getMemoryVT())) {
9636     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9637                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9638   }
9639
9640   // Only perform this optimization before the types are legal, because we
9641   // don't want to perform this optimization on every DAGCombine invocation.
9642   if (!LegalTypes) {
9643     bool EverChanged = false;
9644
9645     do {
9646       // There can be multiple store sequences on the same chain.
9647       // Keep trying to merge store sequences until we are unable to do so
9648       // or until we merge the last store on the chain.
9649       bool Changed = MergeConsecutiveStores(ST);
9650       EverChanged |= Changed;
9651       if (!Changed) break;
9652     } while (ST->getOpcode() != ISD::DELETED_NODE);
9653
9654     if (EverChanged)
9655       return SDValue(N, 0);
9656   }
9657
9658   return ReduceLoadOpStoreWidth(N);
9659 }
9660
9661 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9662   SDValue InVec = N->getOperand(0);
9663   SDValue InVal = N->getOperand(1);
9664   SDValue EltNo = N->getOperand(2);
9665   SDLoc dl(N);
9666
9667   // If the inserted element is an UNDEF, just use the input vector.
9668   if (InVal.getOpcode() == ISD::UNDEF)
9669     return InVec;
9670
9671   EVT VT = InVec.getValueType();
9672
9673   // If we can't generate a legal BUILD_VECTOR, exit
9674   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9675     return SDValue();
9676
9677   // Check that we know which element is being inserted
9678   if (!isa<ConstantSDNode>(EltNo))
9679     return SDValue();
9680   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9681
9682   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9683   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9684   // vector elements.
9685   SmallVector<SDValue, 8> Ops;
9686   // Do not combine these two vectors if the output vector will not replace
9687   // the input vector.
9688   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9689     Ops.append(InVec.getNode()->op_begin(),
9690                InVec.getNode()->op_end());
9691   } else if (InVec.getOpcode() == ISD::UNDEF) {
9692     unsigned NElts = VT.getVectorNumElements();
9693     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9694   } else {
9695     return SDValue();
9696   }
9697
9698   // Insert the element
9699   if (Elt < Ops.size()) {
9700     // All the operands of BUILD_VECTOR must have the same type;
9701     // we enforce that here.
9702     EVT OpVT = Ops[0].getValueType();
9703     if (InVal.getValueType() != OpVT)
9704       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9705                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9706                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9707     Ops[Elt] = InVal;
9708   }
9709
9710   // Return the new vector
9711   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9712                      VT, &Ops[0], Ops.size());
9713 }
9714
9715 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9716   // (vextract (scalar_to_vector val, 0) -> val
9717   SDValue InVec = N->getOperand(0);
9718   EVT VT = InVec.getValueType();
9719   EVT NVT = N->getValueType(0);
9720
9721   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9722     // Check if the result type doesn't match the inserted element type. A
9723     // SCALAR_TO_VECTOR may truncate the inserted element and the
9724     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9725     SDValue InOp = InVec.getOperand(0);
9726     if (InOp.getValueType() != NVT) {
9727       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9728       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9729     }
9730     return InOp;
9731   }
9732
9733   SDValue EltNo = N->getOperand(1);
9734   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9735
9736   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9737   // We only perform this optimization before the op legalization phase because
9738   // we may introduce new vector instructions which are not backed by TD
9739   // patterns. For example on AVX, extracting elements from a wide vector
9740   // without using extract_subvector. However, if we can find an underlying
9741   // scalar value, then we can always use that.
9742   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9743       && ConstEltNo) {
9744     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9745     int NumElem = VT.getVectorNumElements();
9746     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9747     // Find the new index to extract from.
9748     int OrigElt = SVOp->getMaskElt(Elt);
9749
9750     // Extracting an undef index is undef.
9751     if (OrigElt == -1)
9752       return DAG.getUNDEF(NVT);
9753
9754     // Select the right vector half to extract from.
9755     SDValue SVInVec;
9756     if (OrigElt < NumElem) {
9757       SVInVec = InVec->getOperand(0);
9758     } else {
9759       SVInVec = InVec->getOperand(1);
9760       OrigElt -= NumElem;
9761     }
9762
9763     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9764       SDValue InOp = SVInVec.getOperand(OrigElt);
9765       if (InOp.getValueType() != NVT) {
9766         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9767         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9768       }
9769
9770       return InOp;
9771     }
9772
9773     // FIXME: We should handle recursing on other vector shuffles and
9774     // scalar_to_vector here as well.
9775
9776     if (!LegalOperations) {
9777       EVT IndexTy = TLI.getVectorIdxTy();
9778       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9779                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9780     }
9781   }
9782
9783   // Perform only after legalization to ensure build_vector / vector_shuffle
9784   // optimizations have already been done.
9785   if (!LegalOperations) return SDValue();
9786
9787   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9788   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9789   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9790
9791   if (ConstEltNo) {
9792     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9793     bool NewLoad = false;
9794     bool BCNumEltsChanged = false;
9795     EVT ExtVT = VT.getVectorElementType();
9796     EVT LVT = ExtVT;
9797
9798     // If the result of load has to be truncated, then it's not necessarily
9799     // profitable.
9800     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9801       return SDValue();
9802
9803     if (InVec.getOpcode() == ISD::BITCAST) {
9804       // Don't duplicate a load with other uses.
9805       if (!InVec.hasOneUse())
9806         return SDValue();
9807
9808       EVT BCVT = InVec.getOperand(0).getValueType();
9809       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9810         return SDValue();
9811       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9812         BCNumEltsChanged = true;
9813       InVec = InVec.getOperand(0);
9814       ExtVT = BCVT.getVectorElementType();
9815       NewLoad = true;
9816     }
9817
9818     LoadSDNode *LN0 = NULL;
9819     const ShuffleVectorSDNode *SVN = NULL;
9820     if (ISD::isNormalLoad(InVec.getNode())) {
9821       LN0 = cast<LoadSDNode>(InVec);
9822     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9823                InVec.getOperand(0).getValueType() == ExtVT &&
9824                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9825       // Don't duplicate a load with other uses.
9826       if (!InVec.hasOneUse())
9827         return SDValue();
9828
9829       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9830     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9831       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9832       // =>
9833       // (load $addr+1*size)
9834
9835       // Don't duplicate a load with other uses.
9836       if (!InVec.hasOneUse())
9837         return SDValue();
9838
9839       // If the bit convert changed the number of elements, it is unsafe
9840       // to examine the mask.
9841       if (BCNumEltsChanged)
9842         return SDValue();
9843
9844       // Select the input vector, guarding against out of range extract vector.
9845       unsigned NumElems = VT.getVectorNumElements();
9846       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9847       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9848
9849       if (InVec.getOpcode() == ISD::BITCAST) {
9850         // Don't duplicate a load with other uses.
9851         if (!InVec.hasOneUse())
9852           return SDValue();
9853
9854         InVec = InVec.getOperand(0);
9855       }
9856       if (ISD::isNormalLoad(InVec.getNode())) {
9857         LN0 = cast<LoadSDNode>(InVec);
9858         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9859       }
9860     }
9861
9862     // Make sure we found a non-volatile load and the extractelement is
9863     // the only use.
9864     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9865       return SDValue();
9866
9867     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9868     if (Elt == -1)
9869       return DAG.getUNDEF(LVT);
9870
9871     unsigned Align = LN0->getAlignment();
9872     if (NewLoad) {
9873       // Check the resultant load doesn't need a higher alignment than the
9874       // original load.
9875       unsigned NewAlign =
9876         TLI.getDataLayout()
9877             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9878
9879       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9880         return SDValue();
9881
9882       Align = NewAlign;
9883     }
9884
9885     SDValue NewPtr = LN0->getBasePtr();
9886     unsigned PtrOff = 0;
9887
9888     if (Elt) {
9889       PtrOff = LVT.getSizeInBits() * Elt / 8;
9890       EVT PtrType = NewPtr.getValueType();
9891       if (TLI.isBigEndian())
9892         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9893       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9894                            DAG.getConstant(PtrOff, PtrType));
9895     }
9896
9897     // The replacement we need to do here is a little tricky: we need to
9898     // replace an extractelement of a load with a load.
9899     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9900     // Note that this replacement assumes that the extractvalue is the only
9901     // use of the load; that's okay because we don't want to perform this
9902     // transformation in other cases anyway.
9903     SDValue Load;
9904     SDValue Chain;
9905     if (NVT.bitsGT(LVT)) {
9906       // If the result type of vextract is wider than the load, then issue an
9907       // extending load instead.
9908       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9909         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9910       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9911                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9912                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9913                             Align, LN0->getTBAAInfo());
9914       Chain = Load.getValue(1);
9915     } else {
9916       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9917                          LN0->getPointerInfo().getWithOffset(PtrOff),
9918                          LN0->isVolatile(), LN0->isNonTemporal(),
9919                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9920       Chain = Load.getValue(1);
9921       if (NVT.bitsLT(LVT))
9922         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9923       else
9924         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9925     }
9926     WorkListRemover DeadNodes(*this);
9927     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9928     SDValue To[] = { Load, Chain };
9929     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9930     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9931     // worklist explicitly as well.
9932     AddToWorkList(Load.getNode());
9933     AddUsersToWorkList(Load.getNode()); // Add users too
9934     // Make sure to revisit this node to clean it up; it will usually be dead.
9935     AddToWorkList(N);
9936     return SDValue(N, 0);
9937   }
9938
9939   return SDValue();
9940 }
9941
9942 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9943 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9944   // We perform this optimization post type-legalization because
9945   // the type-legalizer often scalarizes integer-promoted vectors.
9946   // Performing this optimization before may create bit-casts which
9947   // will be type-legalized to complex code sequences.
9948   // We perform this optimization only before the operation legalizer because we
9949   // may introduce illegal operations.
9950   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9951     return SDValue();
9952
9953   unsigned NumInScalars = N->getNumOperands();
9954   SDLoc dl(N);
9955   EVT VT = N->getValueType(0);
9956
9957   // Check to see if this is a BUILD_VECTOR of a bunch of values
9958   // which come from any_extend or zero_extend nodes. If so, we can create
9959   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9960   // optimizations. We do not handle sign-extend because we can't fill the sign
9961   // using shuffles.
9962   EVT SourceType = MVT::Other;
9963   bool AllAnyExt = true;
9964
9965   for (unsigned i = 0; i != NumInScalars; ++i) {
9966     SDValue In = N->getOperand(i);
9967     // Ignore undef inputs.
9968     if (In.getOpcode() == ISD::UNDEF) continue;
9969
9970     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9971     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9972
9973     // Abort if the element is not an extension.
9974     if (!ZeroExt && !AnyExt) {
9975       SourceType = MVT::Other;
9976       break;
9977     }
9978
9979     // The input is a ZeroExt or AnyExt. Check the original type.
9980     EVT InTy = In.getOperand(0).getValueType();
9981
9982     // Check that all of the widened source types are the same.
9983     if (SourceType == MVT::Other)
9984       // First time.
9985       SourceType = InTy;
9986     else if (InTy != SourceType) {
9987       // Multiple income types. Abort.
9988       SourceType = MVT::Other;
9989       break;
9990     }
9991
9992     // Check if all of the extends are ANY_EXTENDs.
9993     AllAnyExt &= AnyExt;
9994   }
9995
9996   // In order to have valid types, all of the inputs must be extended from the
9997   // same source type and all of the inputs must be any or zero extend.
9998   // Scalar sizes must be a power of two.
9999   EVT OutScalarTy = VT.getScalarType();
10000   bool ValidTypes = SourceType != MVT::Other &&
10001                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10002                  isPowerOf2_32(SourceType.getSizeInBits());
10003
10004   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10005   // turn into a single shuffle instruction.
10006   if (!ValidTypes)
10007     return SDValue();
10008
10009   bool isLE = TLI.isLittleEndian();
10010   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10011   assert(ElemRatio > 1 && "Invalid element size ratio");
10012   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10013                                DAG.getConstant(0, SourceType);
10014
10015   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10016   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10017
10018   // Populate the new build_vector
10019   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10020     SDValue Cast = N->getOperand(i);
10021     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10022             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10023             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10024     SDValue In;
10025     if (Cast.getOpcode() == ISD::UNDEF)
10026       In = DAG.getUNDEF(SourceType);
10027     else
10028       In = Cast->getOperand(0);
10029     unsigned Index = isLE ? (i * ElemRatio) :
10030                             (i * ElemRatio + (ElemRatio - 1));
10031
10032     assert(Index < Ops.size() && "Invalid index");
10033     Ops[Index] = In;
10034   }
10035
10036   // The type of the new BUILD_VECTOR node.
10037   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10038   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10039          "Invalid vector size");
10040   // Check if the new vector type is legal.
10041   if (!isTypeLegal(VecVT)) return SDValue();
10042
10043   // Make the new BUILD_VECTOR.
10044   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10045
10046   // The new BUILD_VECTOR node has the potential to be further optimized.
10047   AddToWorkList(BV.getNode());
10048   // Bitcast to the desired type.
10049   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10050 }
10051
10052 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10053   EVT VT = N->getValueType(0);
10054
10055   unsigned NumInScalars = N->getNumOperands();
10056   SDLoc dl(N);
10057
10058   EVT SrcVT = MVT::Other;
10059   unsigned Opcode = ISD::DELETED_NODE;
10060   unsigned NumDefs = 0;
10061
10062   for (unsigned i = 0; i != NumInScalars; ++i) {
10063     SDValue In = N->getOperand(i);
10064     unsigned Opc = In.getOpcode();
10065
10066     if (Opc == ISD::UNDEF)
10067       continue;
10068
10069     // If all scalar values are floats and converted from integers.
10070     if (Opcode == ISD::DELETED_NODE &&
10071         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10072       Opcode = Opc;
10073     }
10074
10075     if (Opc != Opcode)
10076       return SDValue();
10077
10078     EVT InVT = In.getOperand(0).getValueType();
10079
10080     // If all scalar values are typed differently, bail out. It's chosen to
10081     // simplify BUILD_VECTOR of integer types.
10082     if (SrcVT == MVT::Other)
10083       SrcVT = InVT;
10084     if (SrcVT != InVT)
10085       return SDValue();
10086     NumDefs++;
10087   }
10088
10089   // If the vector has just one element defined, it's not worth to fold it into
10090   // a vectorized one.
10091   if (NumDefs < 2)
10092     return SDValue();
10093
10094   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10095          && "Should only handle conversion from integer to float.");
10096   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10097
10098   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10099
10100   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10101     return SDValue();
10102
10103   SmallVector<SDValue, 8> Opnds;
10104   for (unsigned i = 0; i != NumInScalars; ++i) {
10105     SDValue In = N->getOperand(i);
10106
10107     if (In.getOpcode() == ISD::UNDEF)
10108       Opnds.push_back(DAG.getUNDEF(SrcVT));
10109     else
10110       Opnds.push_back(In.getOperand(0));
10111   }
10112   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10113                            &Opnds[0], Opnds.size());
10114   AddToWorkList(BV.getNode());
10115
10116   return DAG.getNode(Opcode, dl, VT, BV);
10117 }
10118
10119 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10120   unsigned NumInScalars = N->getNumOperands();
10121   SDLoc dl(N);
10122   EVT VT = N->getValueType(0);
10123
10124   // A vector built entirely of undefs is undef.
10125   if (ISD::allOperandsUndef(N))
10126     return DAG.getUNDEF(VT);
10127
10128   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10129   if (V.getNode())
10130     return V;
10131
10132   V = reduceBuildVecConvertToConvertBuildVec(N);
10133   if (V.getNode())
10134     return V;
10135
10136   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10137   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10138   // at most two distinct vectors, turn this into a shuffle node.
10139
10140   // May only combine to shuffle after legalize if shuffle is legal.
10141   if (LegalOperations &&
10142       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10143     return SDValue();
10144
10145   SDValue VecIn1, VecIn2;
10146   for (unsigned i = 0; i != NumInScalars; ++i) {
10147     // Ignore undef inputs.
10148     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10149
10150     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10151     // constant index, bail out.
10152     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10153         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10154       VecIn1 = VecIn2 = SDValue(0, 0);
10155       break;
10156     }
10157
10158     // We allow up to two distinct input vectors.
10159     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10160     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10161       continue;
10162
10163     if (VecIn1.getNode() == 0) {
10164       VecIn1 = ExtractedFromVec;
10165     } else if (VecIn2.getNode() == 0) {
10166       VecIn2 = ExtractedFromVec;
10167     } else {
10168       // Too many inputs.
10169       VecIn1 = VecIn2 = SDValue(0, 0);
10170       break;
10171     }
10172   }
10173
10174     // If everything is good, we can make a shuffle operation.
10175   if (VecIn1.getNode()) {
10176     SmallVector<int, 8> Mask;
10177     for (unsigned i = 0; i != NumInScalars; ++i) {
10178       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10179         Mask.push_back(-1);
10180         continue;
10181       }
10182
10183       // If extracting from the first vector, just use the index directly.
10184       SDValue Extract = N->getOperand(i);
10185       SDValue ExtVal = Extract.getOperand(1);
10186       if (Extract.getOperand(0) == VecIn1) {
10187         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10188         if (ExtIndex > VT.getVectorNumElements())
10189           return SDValue();
10190
10191         Mask.push_back(ExtIndex);
10192         continue;
10193       }
10194
10195       // Otherwise, use InIdx + VecSize
10196       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10197       Mask.push_back(Idx+NumInScalars);
10198     }
10199
10200     // We can't generate a shuffle node with mismatched input and output types.
10201     // Attempt to transform a single input vector to the correct type.
10202     if ((VT != VecIn1.getValueType())) {
10203       // We don't support shuffeling between TWO values of different types.
10204       if (VecIn2.getNode() != 0)
10205         return SDValue();
10206
10207       // We only support widening of vectors which are half the size of the
10208       // output registers. For example XMM->YMM widening on X86 with AVX.
10209       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10210         return SDValue();
10211
10212       // If the input vector type has a different base type to the output
10213       // vector type, bail out.
10214       if (VecIn1.getValueType().getVectorElementType() !=
10215           VT.getVectorElementType())
10216         return SDValue();
10217
10218       // Widen the input vector by adding undef values.
10219       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10220                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10221     }
10222
10223     // If VecIn2 is unused then change it to undef.
10224     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10225
10226     // Check that we were able to transform all incoming values to the same
10227     // type.
10228     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10229         VecIn1.getValueType() != VT)
10230           return SDValue();
10231
10232     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10233     if (!isTypeLegal(VT))
10234       return SDValue();
10235
10236     // Return the new VECTOR_SHUFFLE node.
10237     SDValue Ops[2];
10238     Ops[0] = VecIn1;
10239     Ops[1] = VecIn2;
10240     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10241   }
10242
10243   return SDValue();
10244 }
10245
10246 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10247   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10248   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10249   // inputs come from at most two distinct vectors, turn this into a shuffle
10250   // node.
10251
10252   // If we only have one input vector, we don't need to do any concatenation.
10253   if (N->getNumOperands() == 1)
10254     return N->getOperand(0);
10255
10256   // Check if all of the operands are undefs.
10257   EVT VT = N->getValueType(0);
10258   if (ISD::allOperandsUndef(N))
10259     return DAG.getUNDEF(VT);
10260
10261   // Optimize concat_vectors where one of the vectors is undef.
10262   if (N->getNumOperands() == 2 &&
10263       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10264     SDValue In = N->getOperand(0);
10265     assert(In.getValueType().isVector() && "Must concat vectors");
10266
10267     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10268     if (In->getOpcode() == ISD::BITCAST &&
10269         !In->getOperand(0)->getValueType(0).isVector()) {
10270       SDValue Scalar = In->getOperand(0);
10271       EVT SclTy = Scalar->getValueType(0);
10272
10273       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10274         return SDValue();
10275
10276       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10277                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10278       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10279         return SDValue();
10280
10281       SDLoc dl = SDLoc(N);
10282       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10283       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10284     }
10285   }
10286
10287   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10288   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10289   if (N->getNumOperands() == 2 &&
10290       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10291       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10292     EVT VT = N->getValueType(0);
10293     SDValue N0 = N->getOperand(0);
10294     SDValue N1 = N->getOperand(1);
10295     SmallVector<SDValue, 8> Opnds;
10296     unsigned BuildVecNumElts =  N0.getNumOperands();
10297
10298     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10299       Opnds.push_back(N0.getOperand(i));
10300     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10301       Opnds.push_back(N1.getOperand(i));
10302
10303     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10304                        Opnds.size());
10305   }
10306
10307   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10308   // nodes often generate nop CONCAT_VECTOR nodes.
10309   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10310   // place the incoming vectors at the exact same location.
10311   SDValue SingleSource = SDValue();
10312   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10313
10314   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10315     SDValue Op = N->getOperand(i);
10316
10317     if (Op.getOpcode() == ISD::UNDEF)
10318       continue;
10319
10320     // Check if this is the identity extract:
10321     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10322       return SDValue();
10323
10324     // Find the single incoming vector for the extract_subvector.
10325     if (SingleSource.getNode()) {
10326       if (Op.getOperand(0) != SingleSource)
10327         return SDValue();
10328     } else {
10329       SingleSource = Op.getOperand(0);
10330
10331       // Check the source type is the same as the type of the result.
10332       // If not, this concat may extend the vector, so we can not
10333       // optimize it away.
10334       if (SingleSource.getValueType() != N->getValueType(0))
10335         return SDValue();
10336     }
10337
10338     unsigned IdentityIndex = i * PartNumElem;
10339     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10340     // The extract index must be constant.
10341     if (!CS)
10342       return SDValue();
10343
10344     // Check that we are reading from the identity index.
10345     if (CS->getZExtValue() != IdentityIndex)
10346       return SDValue();
10347   }
10348
10349   if (SingleSource.getNode())
10350     return SingleSource;
10351
10352   return SDValue();
10353 }
10354
10355 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10356   EVT NVT = N->getValueType(0);
10357   SDValue V = N->getOperand(0);
10358
10359   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10360     // Combine:
10361     //    (extract_subvec (concat V1, V2, ...), i)
10362     // Into:
10363     //    Vi if possible
10364     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10365     // type.
10366     if (V->getOperand(0).getValueType() != NVT)
10367       return SDValue();
10368     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10369     unsigned NumElems = NVT.getVectorNumElements();
10370     assert((Idx % NumElems) == 0 &&
10371            "IDX in concat is not a multiple of the result vector length.");
10372     return V->getOperand(Idx / NumElems);
10373   }
10374
10375   // Skip bitcasting
10376   if (V->getOpcode() == ISD::BITCAST)
10377     V = V.getOperand(0);
10378
10379   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10380     SDLoc dl(N);
10381     // Handle only simple case where vector being inserted and vector
10382     // being extracted are of same type, and are half size of larger vectors.
10383     EVT BigVT = V->getOperand(0).getValueType();
10384     EVT SmallVT = V->getOperand(1).getValueType();
10385     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10386       return SDValue();
10387
10388     // Only handle cases where both indexes are constants with the same type.
10389     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10390     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10391
10392     if (InsIdx && ExtIdx &&
10393         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10394         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10395       // Combine:
10396       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10397       // Into:
10398       //    indices are equal or bit offsets are equal => V1
10399       //    otherwise => (extract_subvec V1, ExtIdx)
10400       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10401           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10402         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10403       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10404                          DAG.getNode(ISD::BITCAST, dl,
10405                                      N->getOperand(0).getValueType(),
10406                                      V->getOperand(0)), N->getOperand(1));
10407     }
10408   }
10409
10410   return SDValue();
10411 }
10412
10413 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10414 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10415   EVT VT = N->getValueType(0);
10416   unsigned NumElts = VT.getVectorNumElements();
10417
10418   SDValue N0 = N->getOperand(0);
10419   SDValue N1 = N->getOperand(1);
10420   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10421
10422   SmallVector<SDValue, 4> Ops;
10423   EVT ConcatVT = N0.getOperand(0).getValueType();
10424   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10425   unsigned NumConcats = NumElts / NumElemsPerConcat;
10426
10427   // Look at every vector that's inserted. We're looking for exact
10428   // subvector-sized copies from a concatenated vector
10429   for (unsigned I = 0; I != NumConcats; ++I) {
10430     // Make sure we're dealing with a copy.
10431     unsigned Begin = I * NumElemsPerConcat;
10432     bool AllUndef = true, NoUndef = true;
10433     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10434       if (SVN->getMaskElt(J) >= 0)
10435         AllUndef = false;
10436       else
10437         NoUndef = false;
10438     }
10439
10440     if (NoUndef) {
10441       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10442         return SDValue();
10443
10444       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10445         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10446           return SDValue();
10447
10448       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10449       if (FirstElt < N0.getNumOperands())
10450         Ops.push_back(N0.getOperand(FirstElt));
10451       else
10452         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10453
10454     } else if (AllUndef) {
10455       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10456     } else { // Mixed with general masks and undefs, can't do optimization.
10457       return SDValue();
10458     }
10459   }
10460
10461   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10462                      Ops.size());
10463 }
10464
10465 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10466   EVT VT = N->getValueType(0);
10467   unsigned NumElts = VT.getVectorNumElements();
10468
10469   SDValue N0 = N->getOperand(0);
10470   SDValue N1 = N->getOperand(1);
10471
10472   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10473
10474   // Canonicalize shuffle undef, undef -> undef
10475   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10476     return DAG.getUNDEF(VT);
10477
10478   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10479
10480   // Canonicalize shuffle v, v -> v, undef
10481   if (N0 == N1) {
10482     SmallVector<int, 8> NewMask;
10483     for (unsigned i = 0; i != NumElts; ++i) {
10484       int Idx = SVN->getMaskElt(i);
10485       if (Idx >= (int)NumElts) Idx -= NumElts;
10486       NewMask.push_back(Idx);
10487     }
10488     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10489                                 &NewMask[0]);
10490   }
10491
10492   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10493   if (N0.getOpcode() == ISD::UNDEF) {
10494     SmallVector<int, 8> NewMask;
10495     for (unsigned i = 0; i != NumElts; ++i) {
10496       int Idx = SVN->getMaskElt(i);
10497       if (Idx >= 0) {
10498         if (Idx >= (int)NumElts)
10499           Idx -= NumElts;
10500         else
10501           Idx = -1; // remove reference to lhs
10502       }
10503       NewMask.push_back(Idx);
10504     }
10505     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10506                                 &NewMask[0]);
10507   }
10508
10509   // Remove references to rhs if it is undef
10510   if (N1.getOpcode() == ISD::UNDEF) {
10511     bool Changed = false;
10512     SmallVector<int, 8> NewMask;
10513     for (unsigned i = 0; i != NumElts; ++i) {
10514       int Idx = SVN->getMaskElt(i);
10515       if (Idx >= (int)NumElts) {
10516         Idx = -1;
10517         Changed = true;
10518       }
10519       NewMask.push_back(Idx);
10520     }
10521     if (Changed)
10522       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10523   }
10524
10525   // If it is a splat, check if the argument vector is another splat or a
10526   // build_vector with all scalar elements the same.
10527   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10528     SDNode *V = N0.getNode();
10529
10530     // If this is a bit convert that changes the element type of the vector but
10531     // not the number of vector elements, look through it.  Be careful not to
10532     // look though conversions that change things like v4f32 to v2f64.
10533     if (V->getOpcode() == ISD::BITCAST) {
10534       SDValue ConvInput = V->getOperand(0);
10535       if (ConvInput.getValueType().isVector() &&
10536           ConvInput.getValueType().getVectorNumElements() == NumElts)
10537         V = ConvInput.getNode();
10538     }
10539
10540     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10541       assert(V->getNumOperands() == NumElts &&
10542              "BUILD_VECTOR has wrong number of operands");
10543       SDValue Base;
10544       bool AllSame = true;
10545       for (unsigned i = 0; i != NumElts; ++i) {
10546         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10547           Base = V->getOperand(i);
10548           break;
10549         }
10550       }
10551       // Splat of <u, u, u, u>, return <u, u, u, u>
10552       if (!Base.getNode())
10553         return N0;
10554       for (unsigned i = 0; i != NumElts; ++i) {
10555         if (V->getOperand(i) != Base) {
10556           AllSame = false;
10557           break;
10558         }
10559       }
10560       // Splat of <x, x, x, x>, return <x, x, x, x>
10561       if (AllSame)
10562         return N0;
10563     }
10564   }
10565
10566   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10567       Level < AfterLegalizeVectorOps &&
10568       (N1.getOpcode() == ISD::UNDEF ||
10569       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10570        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10571     SDValue V = partitionShuffleOfConcats(N, DAG);
10572
10573     if (V.getNode())
10574       return V;
10575   }
10576
10577   // If this shuffle node is simply a swizzle of another shuffle node,
10578   // and it reverses the swizzle of the previous shuffle then we can
10579   // optimize shuffle(shuffle(x, undef), undef) -> x.
10580   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10581       N1.getOpcode() == ISD::UNDEF) {
10582
10583     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10584
10585     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10586     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10587       return SDValue();
10588
10589     // The incoming shuffle must be of the same type as the result of the
10590     // current shuffle.
10591     assert(OtherSV->getOperand(0).getValueType() == VT &&
10592            "Shuffle types don't match");
10593
10594     for (unsigned i = 0; i != NumElts; ++i) {
10595       int Idx = SVN->getMaskElt(i);
10596       assert(Idx < (int)NumElts && "Index references undef operand");
10597       // Next, this index comes from the first value, which is the incoming
10598       // shuffle. Adopt the incoming index.
10599       if (Idx >= 0)
10600         Idx = OtherSV->getMaskElt(Idx);
10601
10602       // The combined shuffle must map each index to itself.
10603       if (Idx >= 0 && (unsigned)Idx != i)
10604         return SDValue();
10605     }
10606
10607     return OtherSV->getOperand(0);
10608   }
10609
10610   return SDValue();
10611 }
10612
10613 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10614   SDValue N0 = N->getOperand(0);
10615   SDValue N2 = N->getOperand(2);
10616
10617   // If the input vector is a concatenation, and the insert replaces
10618   // one of the halves, we can optimize into a single concat_vectors.
10619   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10620       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10621     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10622     EVT VT = N->getValueType(0);
10623
10624     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10625     // (concat_vectors Z, Y)
10626     if (InsIdx == 0)
10627       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10628                          N->getOperand(1), N0.getOperand(1));
10629
10630     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10631     // (concat_vectors X, Z)
10632     if (InsIdx == VT.getVectorNumElements()/2)
10633       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10634                          N0.getOperand(0), N->getOperand(1));
10635   }
10636
10637   return SDValue();
10638 }
10639
10640 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10641 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10642 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10643 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10644 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10645   EVT VT = N->getValueType(0);
10646   SDLoc dl(N);
10647   SDValue LHS = N->getOperand(0);
10648   SDValue RHS = N->getOperand(1);
10649   if (N->getOpcode() == ISD::AND) {
10650     if (RHS.getOpcode() == ISD::BITCAST)
10651       RHS = RHS.getOperand(0);
10652     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10653       SmallVector<int, 8> Indices;
10654       unsigned NumElts = RHS.getNumOperands();
10655       for (unsigned i = 0; i != NumElts; ++i) {
10656         SDValue Elt = RHS.getOperand(i);
10657         if (!isa<ConstantSDNode>(Elt))
10658           return SDValue();
10659
10660         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10661           Indices.push_back(i);
10662         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10663           Indices.push_back(NumElts);
10664         else
10665           return SDValue();
10666       }
10667
10668       // Let's see if the target supports this vector_shuffle.
10669       EVT RVT = RHS.getValueType();
10670       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10671         return SDValue();
10672
10673       // Return the new VECTOR_SHUFFLE node.
10674       EVT EltVT = RVT.getVectorElementType();
10675       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10676                                      DAG.getConstant(0, EltVT));
10677       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10678                                  RVT, &ZeroOps[0], ZeroOps.size());
10679       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10680       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10681       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10682     }
10683   }
10684
10685   return SDValue();
10686 }
10687
10688 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10689 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10690   assert(N->getValueType(0).isVector() &&
10691          "SimplifyVBinOp only works on vectors!");
10692
10693   SDValue LHS = N->getOperand(0);
10694   SDValue RHS = N->getOperand(1);
10695   SDValue Shuffle = XformToShuffleWithZero(N);
10696   if (Shuffle.getNode()) return Shuffle;
10697
10698   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10699   // this operation.
10700   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10701       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10702     // Check if both vectors are constants. If not bail out.
10703     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10704           cast<BuildVectorSDNode>(RHS)->isConstant()))
10705       return SDValue();
10706
10707     SmallVector<SDValue, 8> Ops;
10708     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10709       SDValue LHSOp = LHS.getOperand(i);
10710       SDValue RHSOp = RHS.getOperand(i);
10711
10712       // Can't fold divide by zero.
10713       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10714           N->getOpcode() == ISD::FDIV) {
10715         if ((RHSOp.getOpcode() == ISD::Constant &&
10716              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10717             (RHSOp.getOpcode() == ISD::ConstantFP &&
10718              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10719           break;
10720       }
10721
10722       EVT VT = LHSOp.getValueType();
10723       EVT RVT = RHSOp.getValueType();
10724       if (RVT != VT) {
10725         // Integer BUILD_VECTOR operands may have types larger than the element
10726         // size (e.g., when the element type is not legal).  Prior to type
10727         // legalization, the types may not match between the two BUILD_VECTORS.
10728         // Truncate one of the operands to make them match.
10729         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10730           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10731         } else {
10732           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10733           VT = RVT;
10734         }
10735       }
10736       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10737                                    LHSOp, RHSOp);
10738       if (FoldOp.getOpcode() != ISD::UNDEF &&
10739           FoldOp.getOpcode() != ISD::Constant &&
10740           FoldOp.getOpcode() != ISD::ConstantFP)
10741         break;
10742       Ops.push_back(FoldOp);
10743       AddToWorkList(FoldOp.getNode());
10744     }
10745
10746     if (Ops.size() == LHS.getNumOperands())
10747       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10748                          LHS.getValueType(), &Ops[0], Ops.size());
10749   }
10750
10751   return SDValue();
10752 }
10753
10754 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10755 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10756   assert(N->getValueType(0).isVector() &&
10757          "SimplifyVUnaryOp only works on vectors!");
10758
10759   SDValue N0 = N->getOperand(0);
10760
10761   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10762     return SDValue();
10763
10764   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10765   SmallVector<SDValue, 8> Ops;
10766   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10767     SDValue Op = N0.getOperand(i);
10768     if (Op.getOpcode() != ISD::UNDEF &&
10769         Op.getOpcode() != ISD::ConstantFP)
10770       break;
10771     EVT EltVT = Op.getValueType();
10772     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10773     if (FoldOp.getOpcode() != ISD::UNDEF &&
10774         FoldOp.getOpcode() != ISD::ConstantFP)
10775       break;
10776     Ops.push_back(FoldOp);
10777     AddToWorkList(FoldOp.getNode());
10778   }
10779
10780   if (Ops.size() != N0.getNumOperands())
10781     return SDValue();
10782
10783   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10784                      N0.getValueType(), &Ops[0], Ops.size());
10785 }
10786
10787 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10788                                     SDValue N1, SDValue N2){
10789   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10790
10791   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10792                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10793
10794   // If we got a simplified select_cc node back from SimplifySelectCC, then
10795   // break it down into a new SETCC node, and a new SELECT node, and then return
10796   // the SELECT node, since we were called with a SELECT node.
10797   if (SCC.getNode()) {
10798     // Check to see if we got a select_cc back (to turn into setcc/select).
10799     // Otherwise, just return whatever node we got back, like fabs.
10800     if (SCC.getOpcode() == ISD::SELECT_CC) {
10801       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10802                                   N0.getValueType(),
10803                                   SCC.getOperand(0), SCC.getOperand(1),
10804                                   SCC.getOperand(4));
10805       AddToWorkList(SETCC.getNode());
10806       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10807                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10808     }
10809
10810     return SCC;
10811   }
10812   return SDValue();
10813 }
10814
10815 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10816 /// are the two values being selected between, see if we can simplify the
10817 /// select.  Callers of this should assume that TheSelect is deleted if this
10818 /// returns true.  As such, they should return the appropriate thing (e.g. the
10819 /// node) back to the top-level of the DAG combiner loop to avoid it being
10820 /// looked at.
10821 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10822                                     SDValue RHS) {
10823
10824   // Cannot simplify select with vector condition
10825   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10826
10827   // If this is a select from two identical things, try to pull the operation
10828   // through the select.
10829   if (LHS.getOpcode() != RHS.getOpcode() ||
10830       !LHS.hasOneUse() || !RHS.hasOneUse())
10831     return false;
10832
10833   // If this is a load and the token chain is identical, replace the select
10834   // of two loads with a load through a select of the address to load from.
10835   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10836   // constants have been dropped into the constant pool.
10837   if (LHS.getOpcode() == ISD::LOAD) {
10838     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10839     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10840
10841     // Token chains must be identical.
10842     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10843         // Do not let this transformation reduce the number of volatile loads.
10844         LLD->isVolatile() || RLD->isVolatile() ||
10845         // If this is an EXTLOAD, the VT's must match.
10846         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10847         // If this is an EXTLOAD, the kind of extension must match.
10848         (LLD->getExtensionType() != RLD->getExtensionType() &&
10849          // The only exception is if one of the extensions is anyext.
10850          LLD->getExtensionType() != ISD::EXTLOAD &&
10851          RLD->getExtensionType() != ISD::EXTLOAD) ||
10852         // FIXME: this discards src value information.  This is
10853         // over-conservative. It would be beneficial to be able to remember
10854         // both potential memory locations.  Since we are discarding
10855         // src value info, don't do the transformation if the memory
10856         // locations are not in the default address space.
10857         LLD->getPointerInfo().getAddrSpace() != 0 ||
10858         RLD->getPointerInfo().getAddrSpace() != 0 ||
10859         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10860                                       LLD->getBasePtr().getValueType()))
10861       return false;
10862
10863     // Check that the select condition doesn't reach either load.  If so,
10864     // folding this will induce a cycle into the DAG.  If not, this is safe to
10865     // xform, so create a select of the addresses.
10866     SDValue Addr;
10867     if (TheSelect->getOpcode() == ISD::SELECT) {
10868       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10869       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10870           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10871         return false;
10872       // The loads must not depend on one another.
10873       if (LLD->isPredecessorOf(RLD) ||
10874           RLD->isPredecessorOf(LLD))
10875         return false;
10876       Addr = DAG.getSelect(SDLoc(TheSelect),
10877                            LLD->getBasePtr().getValueType(),
10878                            TheSelect->getOperand(0), LLD->getBasePtr(),
10879                            RLD->getBasePtr());
10880     } else {  // Otherwise SELECT_CC
10881       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10882       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10883
10884       if ((LLD->hasAnyUseOfValue(1) &&
10885            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10886           (RLD->hasAnyUseOfValue(1) &&
10887            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10888         return false;
10889
10890       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10891                          LLD->getBasePtr().getValueType(),
10892                          TheSelect->getOperand(0),
10893                          TheSelect->getOperand(1),
10894                          LLD->getBasePtr(), RLD->getBasePtr(),
10895                          TheSelect->getOperand(4));
10896     }
10897
10898     SDValue Load;
10899     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10900       Load = DAG.getLoad(TheSelect->getValueType(0),
10901                          SDLoc(TheSelect),
10902                          // FIXME: Discards pointer and TBAA info.
10903                          LLD->getChain(), Addr, MachinePointerInfo(),
10904                          LLD->isVolatile(), LLD->isNonTemporal(),
10905                          LLD->isInvariant(), LLD->getAlignment());
10906     } else {
10907       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10908                             RLD->getExtensionType() : LLD->getExtensionType(),
10909                             SDLoc(TheSelect),
10910                             TheSelect->getValueType(0),
10911                             // FIXME: Discards pointer and TBAA info.
10912                             LLD->getChain(), Addr, MachinePointerInfo(),
10913                             LLD->getMemoryVT(), LLD->isVolatile(),
10914                             LLD->isNonTemporal(), LLD->getAlignment());
10915     }
10916
10917     // Users of the select now use the result of the load.
10918     CombineTo(TheSelect, Load);
10919
10920     // Users of the old loads now use the new load's chain.  We know the
10921     // old-load value is dead now.
10922     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10923     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10924     return true;
10925   }
10926
10927   return false;
10928 }
10929
10930 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10931 /// where 'cond' is the comparison specified by CC.
10932 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10933                                       SDValue N2, SDValue N3,
10934                                       ISD::CondCode CC, bool NotExtCompare) {
10935   // (x ? y : y) -> y.
10936   if (N2 == N3) return N2;
10937
10938   EVT VT = N2.getValueType();
10939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10940   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10941   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10942
10943   // Determine if the condition we're dealing with is constant
10944   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10945                               N0, N1, CC, DL, false);
10946   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10947   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10948
10949   // fold select_cc true, x, y -> x
10950   if (SCCC && !SCCC->isNullValue())
10951     return N2;
10952   // fold select_cc false, x, y -> y
10953   if (SCCC && SCCC->isNullValue())
10954     return N3;
10955
10956   // Check to see if we can simplify the select into an fabs node
10957   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10958     // Allow either -0.0 or 0.0
10959     if (CFP->getValueAPF().isZero()) {
10960       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10961       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10962           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10963           N2 == N3.getOperand(0))
10964         return DAG.getNode(ISD::FABS, DL, VT, N0);
10965
10966       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10967       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10968           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10969           N2.getOperand(0) == N3)
10970         return DAG.getNode(ISD::FABS, DL, VT, N3);
10971     }
10972   }
10973
10974   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10975   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10976   // in it.  This is a win when the constant is not otherwise available because
10977   // it replaces two constant pool loads with one.  We only do this if the FP
10978   // type is known to be legal, because if it isn't, then we are before legalize
10979   // types an we want the other legalization to happen first (e.g. to avoid
10980   // messing with soft float) and if the ConstantFP is not legal, because if
10981   // it is legal, we may not need to store the FP constant in a constant pool.
10982   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10983     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10984       if (TLI.isTypeLegal(N2.getValueType()) &&
10985           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10986            TargetLowering::Legal) &&
10987           // If both constants have multiple uses, then we won't need to do an
10988           // extra load, they are likely around in registers for other users.
10989           (TV->hasOneUse() || FV->hasOneUse())) {
10990         Constant *Elts[] = {
10991           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10992           const_cast<ConstantFP*>(TV->getConstantFPValue())
10993         };
10994         Type *FPTy = Elts[0]->getType();
10995         const DataLayout &TD = *TLI.getDataLayout();
10996
10997         // Create a ConstantArray of the two constants.
10998         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10999         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11000                                             TD.getPrefTypeAlignment(FPTy));
11001         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11002
11003         // Get the offsets to the 0 and 1 element of the array so that we can
11004         // select between them.
11005         SDValue Zero = DAG.getIntPtrConstant(0);
11006         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11007         SDValue One = DAG.getIntPtrConstant(EltSize);
11008
11009         SDValue Cond = DAG.getSetCC(DL,
11010                                     getSetCCResultType(N0.getValueType()),
11011                                     N0, N1, CC);
11012         AddToWorkList(Cond.getNode());
11013         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11014                                           Cond, One, Zero);
11015         AddToWorkList(CstOffset.getNode());
11016         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11017                             CstOffset);
11018         AddToWorkList(CPIdx.getNode());
11019         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11020                            MachinePointerInfo::getConstantPool(), false,
11021                            false, false, Alignment);
11022
11023       }
11024     }
11025
11026   // Check to see if we can perform the "gzip trick", transforming
11027   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11028   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11029       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11030        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11031     EVT XType = N0.getValueType();
11032     EVT AType = N2.getValueType();
11033     if (XType.bitsGE(AType)) {
11034       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11035       // single-bit constant.
11036       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11037         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11038         ShCtV = XType.getSizeInBits()-ShCtV-1;
11039         SDValue ShCt = DAG.getConstant(ShCtV,
11040                                        getShiftAmountTy(N0.getValueType()));
11041         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11042                                     XType, N0, ShCt);
11043         AddToWorkList(Shift.getNode());
11044
11045         if (XType.bitsGT(AType)) {
11046           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11047           AddToWorkList(Shift.getNode());
11048         }
11049
11050         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11051       }
11052
11053       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11054                                   XType, N0,
11055                                   DAG.getConstant(XType.getSizeInBits()-1,
11056                                          getShiftAmountTy(N0.getValueType())));
11057       AddToWorkList(Shift.getNode());
11058
11059       if (XType.bitsGT(AType)) {
11060         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11061         AddToWorkList(Shift.getNode());
11062       }
11063
11064       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11065     }
11066   }
11067
11068   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11069   // where y is has a single bit set.
11070   // A plaintext description would be, we can turn the SELECT_CC into an AND
11071   // when the condition can be materialized as an all-ones register.  Any
11072   // single bit-test can be materialized as an all-ones register with
11073   // shift-left and shift-right-arith.
11074   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11075       N0->getValueType(0) == VT &&
11076       N1C && N1C->isNullValue() &&
11077       N2C && N2C->isNullValue()) {
11078     SDValue AndLHS = N0->getOperand(0);
11079     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11080     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11081       // Shift the tested bit over the sign bit.
11082       APInt AndMask = ConstAndRHS->getAPIntValue();
11083       SDValue ShlAmt =
11084         DAG.getConstant(AndMask.countLeadingZeros(),
11085                         getShiftAmountTy(AndLHS.getValueType()));
11086       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11087
11088       // Now arithmetic right shift it all the way over, so the result is either
11089       // all-ones, or zero.
11090       SDValue ShrAmt =
11091         DAG.getConstant(AndMask.getBitWidth()-1,
11092                         getShiftAmountTy(Shl.getValueType()));
11093       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11094
11095       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11096     }
11097   }
11098
11099   // fold select C, 16, 0 -> shl C, 4
11100   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11101     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11102       TargetLowering::ZeroOrOneBooleanContent) {
11103
11104     // If the caller doesn't want us to simplify this into a zext of a compare,
11105     // don't do it.
11106     if (NotExtCompare && N2C->getAPIntValue() == 1)
11107       return SDValue();
11108
11109     // Get a SetCC of the condition
11110     // NOTE: Don't create a SETCC if it's not legal on this target.
11111     if (!LegalOperations ||
11112         TLI.isOperationLegal(ISD::SETCC,
11113           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11114       SDValue Temp, SCC;
11115       // cast from setcc result type to select result type
11116       if (LegalTypes) {
11117         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11118                             N0, N1, CC);
11119         if (N2.getValueType().bitsLT(SCC.getValueType()))
11120           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11121                                         N2.getValueType());
11122         else
11123           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11124                              N2.getValueType(), SCC);
11125       } else {
11126         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11127         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11128                            N2.getValueType(), SCC);
11129       }
11130
11131       AddToWorkList(SCC.getNode());
11132       AddToWorkList(Temp.getNode());
11133
11134       if (N2C->getAPIntValue() == 1)
11135         return Temp;
11136
11137       // shl setcc result by log2 n2c
11138       return DAG.getNode(
11139           ISD::SHL, DL, N2.getValueType(), Temp,
11140           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11141                           getShiftAmountTy(Temp.getValueType())));
11142     }
11143   }
11144
11145   // Check to see if this is the equivalent of setcc
11146   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11147   // otherwise, go ahead with the folds.
11148   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11149     EVT XType = N0.getValueType();
11150     if (!LegalOperations ||
11151         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11152       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11153       if (Res.getValueType() != VT)
11154         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11155       return Res;
11156     }
11157
11158     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11159     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11160         (!LegalOperations ||
11161          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11162       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11163       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11164                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11165                                        getShiftAmountTy(Ctlz.getValueType())));
11166     }
11167     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11168     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11169       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11170                                   XType, DAG.getConstant(0, XType), N0);
11171       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11172       return DAG.getNode(ISD::SRL, DL, XType,
11173                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11174                          DAG.getConstant(XType.getSizeInBits()-1,
11175                                          getShiftAmountTy(XType)));
11176     }
11177     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11178     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11179       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11180                                  DAG.getConstant(XType.getSizeInBits()-1,
11181                                          getShiftAmountTy(N0.getValueType())));
11182       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11183     }
11184   }
11185
11186   // Check to see if this is an integer abs.
11187   // select_cc setg[te] X,  0,  X, -X ->
11188   // select_cc setgt    X, -1,  X, -X ->
11189   // select_cc setl[te] X,  0, -X,  X ->
11190   // select_cc setlt    X,  1, -X,  X ->
11191   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11192   if (N1C) {
11193     ConstantSDNode *SubC = NULL;
11194     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11195          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11196         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11197       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11198     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11199               (N1C->isOne() && CC == ISD::SETLT)) &&
11200              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11201       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11202
11203     EVT XType = N0.getValueType();
11204     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11205       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11206                                   N0,
11207                                   DAG.getConstant(XType.getSizeInBits()-1,
11208                                          getShiftAmountTy(N0.getValueType())));
11209       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11210                                 XType, N0, Shift);
11211       AddToWorkList(Shift.getNode());
11212       AddToWorkList(Add.getNode());
11213       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11214     }
11215   }
11216
11217   return SDValue();
11218 }
11219
11220 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11221 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11222                                    SDValue N1, ISD::CondCode Cond,
11223                                    SDLoc DL, bool foldBooleans) {
11224   TargetLowering::DAGCombinerInfo
11225     DagCombineInfo(DAG, Level, false, this);
11226   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11227 }
11228
11229 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11230 /// return a DAG expression to select that will generate the same value by
11231 /// multiplying by a magic number.  See:
11232 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11233 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11234   std::vector<SDNode*> Built;
11235   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11236
11237   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11238        ii != ee; ++ii)
11239     AddToWorkList(*ii);
11240   return S;
11241 }
11242
11243 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11244 /// return a DAG expression to select that will generate the same value by
11245 /// multiplying by a magic number.  See:
11246 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11247 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11248   std::vector<SDNode*> Built;
11249   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11250
11251   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11252        ii != ee; ++ii)
11253     AddToWorkList(*ii);
11254   return S;
11255 }
11256
11257 /// FindBaseOffset - Return true if base is a frame index, which is known not
11258 // to alias with anything but itself.  Provides base object and offset as
11259 // results.
11260 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11261                            const GlobalValue *&GV, const void *&CV) {
11262   // Assume it is a primitive operation.
11263   Base = Ptr; Offset = 0; GV = 0; CV = 0;
11264
11265   // If it's an adding a simple constant then integrate the offset.
11266   if (Base.getOpcode() == ISD::ADD) {
11267     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11268       Base = Base.getOperand(0);
11269       Offset += C->getZExtValue();
11270     }
11271   }
11272
11273   // Return the underlying GlobalValue, and update the Offset.  Return false
11274   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11275   // by multiple nodes with different offsets.
11276   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11277     GV = G->getGlobal();
11278     Offset += G->getOffset();
11279     return false;
11280   }
11281
11282   // Return the underlying Constant value, and update the Offset.  Return false
11283   // for ConstantSDNodes since the same constant pool entry may be represented
11284   // by multiple nodes with different offsets.
11285   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11286     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11287                                          : (const void *)C->getConstVal();
11288     Offset += C->getOffset();
11289     return false;
11290   }
11291   // If it's any of the following then it can't alias with anything but itself.
11292   return isa<FrameIndexSDNode>(Base);
11293 }
11294
11295 /// isAlias - Return true if there is any possibility that the two addresses
11296 /// overlap.
11297 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11298                           const Value *SrcValue1, int SrcValueOffset1,
11299                           unsigned SrcValueAlign1,
11300                           const MDNode *TBAAInfo1,
11301                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11302                           const Value *SrcValue2, int SrcValueOffset2,
11303                           unsigned SrcValueAlign2,
11304                           const MDNode *TBAAInfo2) const {
11305   // If they are the same then they must be aliases.
11306   if (Ptr1 == Ptr2) return true;
11307
11308   // If they are both volatile then they cannot be reordered.
11309   if (IsVolatile1 && IsVolatile2) return true;
11310
11311   // Gather base node and offset information.
11312   SDValue Base1, Base2;
11313   int64_t Offset1, Offset2;
11314   const GlobalValue *GV1, *GV2;
11315   const void *CV1, *CV2;
11316   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11317   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11318
11319   // If they have a same base address then check to see if they overlap.
11320   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11321     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11322
11323   // It is possible for different frame indices to alias each other, mostly
11324   // when tail call optimization reuses return address slots for arguments.
11325   // To catch this case, look up the actual index of frame indices to compute
11326   // the real alias relationship.
11327   if (isFrameIndex1 && isFrameIndex2) {
11328     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11329     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11330     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11331     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11332   }
11333
11334   // Otherwise, if we know what the bases are, and they aren't identical, then
11335   // we know they cannot alias.
11336   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11337     return false;
11338
11339   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11340   // compared to the size and offset of the access, we may be able to prove they
11341   // do not alias.  This check is conservative for now to catch cases created by
11342   // splitting vector types.
11343   if ((SrcValueAlign1 == SrcValueAlign2) &&
11344       (SrcValueOffset1 != SrcValueOffset2) &&
11345       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11346     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11347     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11348
11349     // There is no overlap between these relatively aligned accesses of similar
11350     // size, return no alias.
11351     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11352       return false;
11353   }
11354
11355   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11356     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11357 #ifndef NDEBUG
11358   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11359       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11360     UseAA = false;
11361 #endif
11362   if (UseAA && SrcValue1 && SrcValue2) {
11363     // Use alias analysis information.
11364     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11365     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11366     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11367     AliasAnalysis::AliasResult AAResult =
11368       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11369                                        UseTBAA ? TBAAInfo1 : 0),
11370                AliasAnalysis::Location(SrcValue2, Overlap2,
11371                                        UseTBAA ? TBAAInfo2 : 0));
11372     if (AAResult == AliasAnalysis::NoAlias)
11373       return false;
11374   }
11375
11376   // Otherwise we have to assume they alias.
11377   return true;
11378 }
11379
11380 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11381   SDValue Ptr0, Ptr1;
11382   int64_t Size0, Size1;
11383   bool IsVolatile0, IsVolatile1;
11384   const Value *SrcValue0, *SrcValue1;
11385   int SrcValueOffset0, SrcValueOffset1;
11386   unsigned SrcValueAlign0, SrcValueAlign1;
11387   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11388   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11389                 SrcValueAlign0, SrcTBAAInfo0);
11390   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11391                 SrcValueAlign1, SrcTBAAInfo1);
11392   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11393                  SrcValueAlign0, SrcTBAAInfo0,
11394                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11395                  SrcValueAlign1, SrcTBAAInfo1);
11396 }
11397
11398 /// FindAliasInfo - Extracts the relevant alias information from the memory
11399 /// node.  Returns true if the operand was a nonvolatile load.
11400 bool DAGCombiner::FindAliasInfo(SDNode *N,
11401                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11402                                 const Value *&SrcValue,
11403                                 int &SrcValueOffset,
11404                                 unsigned &SrcValueAlign,
11405                                 const MDNode *&TBAAInfo) const {
11406   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11407
11408   Ptr = LS->getBasePtr();
11409   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11410   IsVolatile = LS->isVolatile();
11411   SrcValue = LS->getSrcValue();
11412   SrcValueOffset = LS->getSrcValueOffset();
11413   SrcValueAlign = LS->getOriginalAlignment();
11414   TBAAInfo = LS->getTBAAInfo();
11415   return isa<LoadSDNode>(LS) && !IsVolatile;
11416 }
11417
11418 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11419 /// looking for aliasing nodes and adding them to the Aliases vector.
11420 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11421                                    SmallVectorImpl<SDValue> &Aliases) {
11422   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11423   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11424
11425   // Get alias information for node.
11426   SDValue Ptr;
11427   int64_t Size;
11428   bool IsVolatile;
11429   const Value *SrcValue;
11430   int SrcValueOffset;
11431   unsigned SrcValueAlign;
11432   const MDNode *SrcTBAAInfo;
11433   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11434                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11435
11436   // Starting off.
11437   Chains.push_back(OriginalChain);
11438   unsigned Depth = 0;
11439
11440   // Look at each chain and determine if it is an alias.  If so, add it to the
11441   // aliases list.  If not, then continue up the chain looking for the next
11442   // candidate.
11443   while (!Chains.empty()) {
11444     SDValue Chain = Chains.back();
11445     Chains.pop_back();
11446
11447     // For TokenFactor nodes, look at each operand and only continue up the
11448     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11449     // find more and revert to original chain since the xform is unlikely to be
11450     // profitable.
11451     //
11452     // FIXME: The depth check could be made to return the last non-aliasing
11453     // chain we found before we hit a tokenfactor rather than the original
11454     // chain.
11455     if (Depth > 6 || Aliases.size() == 2) {
11456       Aliases.clear();
11457       Aliases.push_back(OriginalChain);
11458       return;
11459     }
11460
11461     // Don't bother if we've been before.
11462     if (!Visited.insert(Chain.getNode()))
11463       continue;
11464
11465     switch (Chain.getOpcode()) {
11466     case ISD::EntryToken:
11467       // Entry token is ideal chain operand, but handled in FindBetterChain.
11468       break;
11469
11470     case ISD::LOAD:
11471     case ISD::STORE: {
11472       // Get alias information for Chain.
11473       SDValue OpPtr;
11474       int64_t OpSize;
11475       bool OpIsVolatile;
11476       const Value *OpSrcValue;
11477       int OpSrcValueOffset;
11478       unsigned OpSrcValueAlign;
11479       const MDNode *OpSrcTBAAInfo;
11480       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11481                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11482                                     OpSrcValueAlign,
11483                                     OpSrcTBAAInfo);
11484
11485       // If chain is alias then stop here.
11486       if (!(IsLoad && IsOpLoad) &&
11487           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11488                   SrcValueAlign, SrcTBAAInfo,
11489                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11490                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11491         Aliases.push_back(Chain);
11492       } else {
11493         // Look further up the chain.
11494         Chains.push_back(Chain.getOperand(0));
11495         ++Depth;
11496       }
11497       break;
11498     }
11499
11500     case ISD::TokenFactor:
11501       // We have to check each of the operands of the token factor for "small"
11502       // token factors, so we queue them up.  Adding the operands to the queue
11503       // (stack) in reverse order maintains the original order and increases the
11504       // likelihood that getNode will find a matching token factor (CSE.)
11505       if (Chain.getNumOperands() > 16) {
11506         Aliases.push_back(Chain);
11507         break;
11508       }
11509       for (unsigned n = Chain.getNumOperands(); n;)
11510         Chains.push_back(Chain.getOperand(--n));
11511       ++Depth;
11512       break;
11513
11514     default:
11515       // For all other instructions we will just have to take what we can get.
11516       Aliases.push_back(Chain);
11517       break;
11518     }
11519   }
11520
11521   // We need to be careful here to also search for aliases through the
11522   // value operand of a store, etc. Consider the following situation:
11523   //   Token1 = ...
11524   //   L1 = load Token1, %52
11525   //   S1 = store Token1, L1, %51
11526   //   L2 = load Token1, %52+8
11527   //   S2 = store Token1, L2, %51+8
11528   //   Token2 = Token(S1, S2)
11529   //   L3 = load Token2, %53
11530   //   S3 = store Token2, L3, %52
11531   //   L4 = load Token2, %53+8
11532   //   S4 = store Token2, L4, %52+8
11533   // If we search for aliases of S3 (which loads address %52), and we look
11534   // only through the chain, then we'll miss the trivial dependence on L1
11535   // (which also loads from %52). We then might change all loads and
11536   // stores to use Token1 as their chain operand, which could result in
11537   // copying %53 into %52 before copying %52 into %51 (which should
11538   // happen first).
11539   //
11540   // The problem is, however, that searching for such data dependencies
11541   // can become expensive, and the cost is not directly related to the
11542   // chain depth. Instead, we'll rule out such configurations here by
11543   // insisting that we've visited all chain users (except for users
11544   // of the original chain, which is not necessary). When doing this,
11545   // we need to look through nodes we don't care about (otherwise, things
11546   // like register copies will interfere with trivial cases).
11547
11548   SmallVector<const SDNode *, 16> Worklist;
11549   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11550        IE = Visited.end(); I != IE; ++I)
11551     if (*I != OriginalChain.getNode())
11552       Worklist.push_back(*I);
11553
11554   while (!Worklist.empty()) {
11555     const SDNode *M = Worklist.pop_back_val();
11556
11557     // We have already visited M, and want to make sure we've visited any uses
11558     // of M that we care about. For uses that we've not visisted, and don't
11559     // care about, queue them to the worklist.
11560
11561     for (SDNode::use_iterator UI = M->use_begin(),
11562          UIE = M->use_end(); UI != UIE; ++UI)
11563       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11564         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11565           // We've not visited this use, and we care about it (it could have an
11566           // ordering dependency with the original node).
11567           Aliases.clear();
11568           Aliases.push_back(OriginalChain);
11569           return;
11570         }
11571
11572         // We've not visited this use, but we don't care about it. Mark it as
11573         // visited and enqueue it to the worklist.
11574         Worklist.push_back(*UI);
11575       }
11576   }
11577 }
11578
11579 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11580 /// for a better chain (aliasing node.)
11581 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11582   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11583
11584   // Accumulate all the aliases to this node.
11585   GatherAllAliases(N, OldChain, Aliases);
11586
11587   // If no operands then chain to entry token.
11588   if (Aliases.size() == 0)
11589     return DAG.getEntryNode();
11590
11591   // If a single operand then chain to it.  We don't need to revisit it.
11592   if (Aliases.size() == 1)
11593     return Aliases[0];
11594
11595   // Construct a custom tailored token factor.
11596   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11597                      &Aliases[0], Aliases.size());
11598 }
11599
11600 // SelectionDAG::Combine - This is the entry point for the file.
11601 //
11602 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11603                            CodeGenOpt::Level OptLevel) {
11604   /// run - This is the main entry point to this class.
11605   ///
11606   DAGCombiner(*this, AA, OptLevel).Run(Level);
11607 }