2e2bfee2bc284a9766a0b42a9fe3e94ffdb529df
[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 nullptr;
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())
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())
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())
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())
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())
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())
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()) {
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()) {
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() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1325       N->getNumValues() == 1) {
1326     SDValue N0 = N->getOperand(0);
1327     SDValue N1 = N->getOperand(1);
1328
1329     // Constant operands are canonicalized to RHS.
1330     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1331       SDValue Ops[] = { N1, N0 };
1332       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1333                                             Ops, 2);
1334       if (CSENode)
1335         return SDValue(CSENode, 0);
1336     }
1337   }
1338
1339   return RV;
1340 }
1341
1342 /// getInputChainForNode - Given a node, return its input chain if it has one,
1343 /// otherwise return a null sd operand.
1344 static SDValue getInputChainForNode(SDNode *N) {
1345   if (unsigned NumOps = N->getNumOperands()) {
1346     if (N->getOperand(0).getValueType() == MVT::Other)
1347       return N->getOperand(0);
1348     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1349       return N->getOperand(NumOps-1);
1350     for (unsigned i = 1; i < NumOps-1; ++i)
1351       if (N->getOperand(i).getValueType() == MVT::Other)
1352         return N->getOperand(i);
1353   }
1354   return SDValue();
1355 }
1356
1357 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1358   // If N has two operands, where one has an input chain equal to the other,
1359   // the 'other' chain is redundant.
1360   if (N->getNumOperands() == 2) {
1361     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1362       return N->getOperand(0);
1363     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1364       return N->getOperand(1);
1365   }
1366
1367   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1368   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1369   SmallPtrSet<SDNode*, 16> SeenOps;
1370   bool Changed = false;             // If we should replace this token factor.
1371
1372   // Start out with this token factor.
1373   TFs.push_back(N);
1374
1375   // Iterate through token factors.  The TFs grows when new token factors are
1376   // encountered.
1377   for (unsigned i = 0; i < TFs.size(); ++i) {
1378     SDNode *TF = TFs[i];
1379
1380     // Check each of the operands.
1381     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1382       SDValue Op = TF->getOperand(i);
1383
1384       switch (Op.getOpcode()) {
1385       case ISD::EntryToken:
1386         // Entry tokens don't need to be added to the list. They are
1387         // rededundant.
1388         Changed = true;
1389         break;
1390
1391       case ISD::TokenFactor:
1392         if (Op.hasOneUse() &&
1393             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1394           // Queue up for processing.
1395           TFs.push_back(Op.getNode());
1396           // Clean up in case the token factor is removed.
1397           AddToWorkList(Op.getNode());
1398           Changed = true;
1399           break;
1400         }
1401         // Fall thru
1402
1403       default:
1404         // Only add if it isn't already in the list.
1405         if (SeenOps.insert(Op.getNode()))
1406           Ops.push_back(Op);
1407         else
1408           Changed = true;
1409         break;
1410       }
1411     }
1412   }
1413
1414   SDValue Result;
1415
1416   // If we've change things around then replace token factor.
1417   if (Changed) {
1418     if (Ops.empty()) {
1419       // The entry token is the only possible outcome.
1420       Result = DAG.getEntryNode();
1421     } else {
1422       // New and improved token factor.
1423       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1424                            MVT::Other, &Ops[0], Ops.size());
1425     }
1426
1427     // Don't add users to work list.
1428     return CombineTo(N, Result, false);
1429   }
1430
1431   return Result;
1432 }
1433
1434 /// MERGE_VALUES can always be eliminated.
1435 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1436   WorkListRemover DeadNodes(*this);
1437   // Replacing results may cause a different MERGE_VALUES to suddenly
1438   // be CSE'd with N, and carry its uses with it. Iterate until no
1439   // uses remain, to ensure that the node can be safely deleted.
1440   // First add the users of this node to the work list so that they
1441   // can be tried again once they have new operands.
1442   AddUsersToWorkList(N);
1443   do {
1444     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1445       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1446   } while (!N->use_empty());
1447   removeFromWorkList(N);
1448   DAG.DeleteNode(N);
1449   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1450 }
1451
1452 static
1453 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1454                               SelectionDAG &DAG) {
1455   EVT VT = N0.getValueType();
1456   SDValue N00 = N0.getOperand(0);
1457   SDValue N01 = N0.getOperand(1);
1458   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1459
1460   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1461       isa<ConstantSDNode>(N00.getOperand(1))) {
1462     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1463     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1464                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1465                                  N00.getOperand(0), N01),
1466                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1467                                  N00.getOperand(1), N01));
1468     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1469   }
1470
1471   return SDValue();
1472 }
1473
1474 SDValue DAGCombiner::visitADD(SDNode *N) {
1475   SDValue N0 = N->getOperand(0);
1476   SDValue N1 = N->getOperand(1);
1477   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1478   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1479   EVT VT = N0.getValueType();
1480
1481   // fold vector ops
1482   if (VT.isVector()) {
1483     SDValue FoldedVOp = SimplifyVBinOp(N);
1484     if (FoldedVOp.getNode()) return FoldedVOp;
1485
1486     // fold (add x, 0) -> x, vector edition
1487     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1488       return N0;
1489     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1490       return N1;
1491   }
1492
1493   // fold (add x, undef) -> undef
1494   if (N0.getOpcode() == ISD::UNDEF)
1495     return N0;
1496   if (N1.getOpcode() == ISD::UNDEF)
1497     return N1;
1498   // fold (add c1, c2) -> c1+c2
1499   if (N0C && N1C)
1500     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1501   // canonicalize constant to RHS
1502   if (N0C && !N1C)
1503     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1504   // fold (add x, 0) -> x
1505   if (N1C && N1C->isNullValue())
1506     return N0;
1507   // fold (add Sym, c) -> Sym+c
1508   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1509     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1510         GA->getOpcode() == ISD::GlobalAddress)
1511       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1512                                   GA->getOffset() +
1513                                     (uint64_t)N1C->getSExtValue());
1514   // fold ((c1-A)+c2) -> (c1+c2)-A
1515   if (N1C && N0.getOpcode() == ISD::SUB)
1516     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1517       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1518                          DAG.getConstant(N1C->getAPIntValue()+
1519                                          N0C->getAPIntValue(), VT),
1520                          N0.getOperand(1));
1521   // reassociate add
1522   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1523   if (RADD.getNode())
1524     return RADD;
1525   // fold ((0-A) + B) -> B-A
1526   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1527       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1528     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1529   // fold (A + (0-B)) -> A-B
1530   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1531       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1532     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1533   // fold (A+(B-A)) -> B
1534   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1535     return N1.getOperand(0);
1536   // fold ((B-A)+A) -> B
1537   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1538     return N0.getOperand(0);
1539   // fold (A+(B-(A+C))) to (B-C)
1540   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1541       N0 == N1.getOperand(1).getOperand(0))
1542     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1543                        N1.getOperand(1).getOperand(1));
1544   // fold (A+(B-(C+A))) to (B-C)
1545   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1546       N0 == N1.getOperand(1).getOperand(1))
1547     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1548                        N1.getOperand(1).getOperand(0));
1549   // fold (A+((B-A)+or-C)) to (B+or-C)
1550   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1551       N1.getOperand(0).getOpcode() == ISD::SUB &&
1552       N0 == N1.getOperand(0).getOperand(1))
1553     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1554                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1555
1556   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1557   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1558     SDValue N00 = N0.getOperand(0);
1559     SDValue N01 = N0.getOperand(1);
1560     SDValue N10 = N1.getOperand(0);
1561     SDValue N11 = N1.getOperand(1);
1562
1563     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1564       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1565                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1566                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1567   }
1568
1569   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1570     return SDValue(N, 0);
1571
1572   // fold (a+b) -> (a|b) iff a and b share no bits.
1573   if (VT.isInteger() && !VT.isVector()) {
1574     APInt LHSZero, LHSOne;
1575     APInt RHSZero, RHSOne;
1576     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1577
1578     if (LHSZero.getBoolValue()) {
1579       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1580
1581       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1582       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1583       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1584         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1585           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1586       }
1587     }
1588   }
1589
1590   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1591   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1592     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1593     if (Result.getNode()) return Result;
1594   }
1595   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1596     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1597     if (Result.getNode()) return Result;
1598   }
1599
1600   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1601   if (N1.getOpcode() == ISD::SHL &&
1602       N1.getOperand(0).getOpcode() == ISD::SUB)
1603     if (ConstantSDNode *C =
1604           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1605       if (C->getAPIntValue() == 0)
1606         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1607                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1608                                        N1.getOperand(0).getOperand(1),
1609                                        N1.getOperand(1)));
1610   if (N0.getOpcode() == ISD::SHL &&
1611       N0.getOperand(0).getOpcode() == ISD::SUB)
1612     if (ConstantSDNode *C =
1613           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1614       if (C->getAPIntValue() == 0)
1615         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1616                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1617                                        N0.getOperand(0).getOperand(1),
1618                                        N0.getOperand(1)));
1619
1620   if (N1.getOpcode() == ISD::AND) {
1621     SDValue AndOp0 = N1.getOperand(0);
1622     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1623     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1624     unsigned DestBits = VT.getScalarType().getSizeInBits();
1625
1626     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1627     // and similar xforms where the inner op is either ~0 or 0.
1628     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1629       SDLoc DL(N);
1630       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1631     }
1632   }
1633
1634   // add (sext i1), X -> sub X, (zext i1)
1635   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1636       N0.getOperand(0).getValueType() == MVT::i1 &&
1637       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1638     SDLoc DL(N);
1639     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1640     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1641   }
1642
1643   return SDValue();
1644 }
1645
1646 SDValue DAGCombiner::visitADDC(SDNode *N) {
1647   SDValue N0 = N->getOperand(0);
1648   SDValue N1 = N->getOperand(1);
1649   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1650   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1651   EVT VT = N0.getValueType();
1652
1653   // If the flag result is dead, turn this into an ADD.
1654   if (!N->hasAnyUseOfValue(1))
1655     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1656                      DAG.getNode(ISD::CARRY_FALSE,
1657                                  SDLoc(N), MVT::Glue));
1658
1659   // canonicalize constant to RHS.
1660   if (N0C && !N1C)
1661     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1662
1663   // fold (addc x, 0) -> x + no carry out
1664   if (N1C && N1C->isNullValue())
1665     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1666                                         SDLoc(N), MVT::Glue));
1667
1668   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1669   APInt LHSZero, LHSOne;
1670   APInt RHSZero, RHSOne;
1671   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1672
1673   if (LHSZero.getBoolValue()) {
1674     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1675
1676     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1677     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1678     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1679       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1680                        DAG.getNode(ISD::CARRY_FALSE,
1681                                    SDLoc(N), MVT::Glue));
1682   }
1683
1684   return SDValue();
1685 }
1686
1687 SDValue DAGCombiner::visitADDE(SDNode *N) {
1688   SDValue N0 = N->getOperand(0);
1689   SDValue N1 = N->getOperand(1);
1690   SDValue CarryIn = N->getOperand(2);
1691   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1692   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1693
1694   // canonicalize constant to RHS
1695   if (N0C && !N1C)
1696     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1697                        N1, N0, CarryIn);
1698
1699   // fold (adde x, y, false) -> (addc x, y)
1700   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1701     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1702
1703   return SDValue();
1704 }
1705
1706 // Since it may not be valid to emit a fold to zero for vector initializers
1707 // check if we can before folding.
1708 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1709                              SelectionDAG &DAG,
1710                              bool LegalOperations, bool LegalTypes) {
1711   if (!VT.isVector())
1712     return DAG.getConstant(0, VT);
1713   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1714     return DAG.getConstant(0, VT);
1715   return SDValue();
1716 }
1717
1718 SDValue DAGCombiner::visitSUB(SDNode *N) {
1719   SDValue N0 = N->getOperand(0);
1720   SDValue N1 = N->getOperand(1);
1721   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1723   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1724     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1725   EVT VT = N0.getValueType();
1726
1727   // fold vector ops
1728   if (VT.isVector()) {
1729     SDValue FoldedVOp = SimplifyVBinOp(N);
1730     if (FoldedVOp.getNode()) return FoldedVOp;
1731
1732     // fold (sub x, 0) -> x, vector edition
1733     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1734       return N0;
1735   }
1736
1737   // fold (sub x, x) -> 0
1738   // FIXME: Refactor this and xor and other similar operations together.
1739   if (N0 == N1)
1740     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1741   // fold (sub c1, c2) -> c1-c2
1742   if (N0C && N1C)
1743     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1744   // fold (sub x, c) -> (add x, -c)
1745   if (N1C)
1746     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1747                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1748   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1749   if (N0C && N0C->isAllOnesValue())
1750     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1751   // fold A-(A-B) -> B
1752   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1753     return N1.getOperand(1);
1754   // fold (A+B)-A -> B
1755   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1756     return N0.getOperand(1);
1757   // fold (A+B)-B -> A
1758   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1759     return N0.getOperand(0);
1760   // fold C2-(A+C1) -> (C2-C1)-A
1761   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1762     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1763                                    VT);
1764     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1765                        N1.getOperand(0));
1766   }
1767   // fold ((A+(B+or-C))-B) -> A+or-C
1768   if (N0.getOpcode() == ISD::ADD &&
1769       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1770        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1771       N0.getOperand(1).getOperand(0) == N1)
1772     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1773                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1774   // fold ((A+(C+B))-B) -> A+C
1775   if (N0.getOpcode() == ISD::ADD &&
1776       N0.getOperand(1).getOpcode() == ISD::ADD &&
1777       N0.getOperand(1).getOperand(1) == N1)
1778     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1779                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1780   // fold ((A-(B-C))-C) -> A-B
1781   if (N0.getOpcode() == ISD::SUB &&
1782       N0.getOperand(1).getOpcode() == ISD::SUB &&
1783       N0.getOperand(1).getOperand(1) == N1)
1784     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1785                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1786
1787   // If either operand of a sub is undef, the result is undef
1788   if (N0.getOpcode() == ISD::UNDEF)
1789     return N0;
1790   if (N1.getOpcode() == ISD::UNDEF)
1791     return N1;
1792
1793   // If the relocation model supports it, consider symbol offsets.
1794   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1795     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1796       // fold (sub Sym, c) -> Sym-c
1797       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1798         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1799                                     GA->getOffset() -
1800                                       (uint64_t)N1C->getSExtValue());
1801       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1802       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1803         if (GA->getGlobal() == GB->getGlobal())
1804           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1805                                  VT);
1806     }
1807
1808   return SDValue();
1809 }
1810
1811 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1812   SDValue N0 = N->getOperand(0);
1813   SDValue N1 = N->getOperand(1);
1814   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1815   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1816   EVT VT = N0.getValueType();
1817
1818   // If the flag result is dead, turn this into an SUB.
1819   if (!N->hasAnyUseOfValue(1))
1820     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1821                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1822                                  MVT::Glue));
1823
1824   // fold (subc x, x) -> 0 + no borrow
1825   if (N0 == N1)
1826     return CombineTo(N, DAG.getConstant(0, VT),
1827                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1828                                  MVT::Glue));
1829
1830   // fold (subc x, 0) -> x + no borrow
1831   if (N1C && N1C->isNullValue())
1832     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1833                                         MVT::Glue));
1834
1835   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1836   if (N0C && N0C->isAllOnesValue())
1837     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1838                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1839                                  MVT::Glue));
1840
1841   return SDValue();
1842 }
1843
1844 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1845   SDValue N0 = N->getOperand(0);
1846   SDValue N1 = N->getOperand(1);
1847   SDValue CarryIn = N->getOperand(2);
1848
1849   // fold (sube x, y, false) -> (subc x, y)
1850   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1851     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1852
1853   return SDValue();
1854 }
1855
1856 SDValue DAGCombiner::visitMUL(SDNode *N) {
1857   SDValue N0 = N->getOperand(0);
1858   SDValue N1 = N->getOperand(1);
1859   EVT VT = N0.getValueType();
1860
1861   // fold (mul x, undef) -> 0
1862   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1863     return DAG.getConstant(0, VT);
1864
1865   bool N0IsConst = false;
1866   bool N1IsConst = false;
1867   APInt ConstValue0, ConstValue1;
1868   // fold vector ops
1869   if (VT.isVector()) {
1870     SDValue FoldedVOp = SimplifyVBinOp(N);
1871     if (FoldedVOp.getNode()) return FoldedVOp;
1872
1873     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1874     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1875   } else {
1876     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1877     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1878                             : APInt();
1879     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1880     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1881                             : APInt();
1882   }
1883
1884   // fold (mul c1, c2) -> c1*c2
1885   if (N0IsConst && N1IsConst)
1886     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1887
1888   // canonicalize constant to RHS
1889   if (N0IsConst && !N1IsConst)
1890     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1891   // fold (mul x, 0) -> 0
1892   if (N1IsConst && ConstValue1 == 0)
1893     return N1;
1894   // We require a splat of the entire scalar bit width for non-contiguous
1895   // bit patterns.
1896   bool IsFullSplat =
1897     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1898   // fold (mul x, 1) -> x
1899   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1900     return N0;
1901   // fold (mul x, -1) -> 0-x
1902   if (N1IsConst && ConstValue1.isAllOnesValue())
1903     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1904                        DAG.getConstant(0, VT), N0);
1905   // fold (mul x, (1 << c)) -> x << c
1906   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1907     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1908                        DAG.getConstant(ConstValue1.logBase2(),
1909                                        getShiftAmountTy(N0.getValueType())));
1910   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1911   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1912     unsigned Log2Val = (-ConstValue1).logBase2();
1913     // FIXME: If the input is something that is easily negated (e.g. a
1914     // single-use add), we should put the negate there.
1915     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1916                        DAG.getConstant(0, VT),
1917                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1918                             DAG.getConstant(Log2Val,
1919                                       getShiftAmountTy(N0.getValueType()))));
1920   }
1921
1922   APInt Val;
1923   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1924   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1925       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1926                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1927     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1928                              N1, N0.getOperand(1));
1929     AddToWorkList(C3.getNode());
1930     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1931                        N0.getOperand(0), C3);
1932   }
1933
1934   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1935   // use.
1936   {
1937     SDValue Sh(nullptr,0), Y(nullptr,0);
1938     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1939     if (N0.getOpcode() == ISD::SHL &&
1940         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1941                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1942         N0.getNode()->hasOneUse()) {
1943       Sh = N0; Y = N1;
1944     } else if (N1.getOpcode() == ISD::SHL &&
1945                isa<ConstantSDNode>(N1.getOperand(1)) &&
1946                N1.getNode()->hasOneUse()) {
1947       Sh = N1; Y = N0;
1948     }
1949
1950     if (Sh.getNode()) {
1951       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1952                                 Sh.getOperand(0), Y);
1953       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1954                          Mul, Sh.getOperand(1));
1955     }
1956   }
1957
1958   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1959   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1960       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1961                      isa<ConstantSDNode>(N0.getOperand(1))))
1962     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1963                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1964                                    N0.getOperand(0), N1),
1965                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1966                                    N0.getOperand(1), N1));
1967
1968   // reassociate mul
1969   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1970   if (RMUL.getNode())
1971     return RMUL;
1972
1973   return SDValue();
1974 }
1975
1976 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1977   SDValue N0 = N->getOperand(0);
1978   SDValue N1 = N->getOperand(1);
1979   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1980   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1981   EVT VT = N->getValueType(0);
1982
1983   // fold vector ops
1984   if (VT.isVector()) {
1985     SDValue FoldedVOp = SimplifyVBinOp(N);
1986     if (FoldedVOp.getNode()) return FoldedVOp;
1987   }
1988
1989   // fold (sdiv c1, c2) -> c1/c2
1990   if (N0C && N1C && !N1C->isNullValue())
1991     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1992   // fold (sdiv X, 1) -> X
1993   if (N1C && N1C->getAPIntValue() == 1LL)
1994     return N0;
1995   // fold (sdiv X, -1) -> 0-X
1996   if (N1C && N1C->isAllOnesValue())
1997     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1998                        DAG.getConstant(0, VT), N0);
1999   // If we know the sign bits of both operands are zero, strength reduce to a
2000   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2001   if (!VT.isVector()) {
2002     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2003       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2004                          N0, N1);
2005   }
2006   // fold (sdiv X, pow2) -> simple ops after legalize
2007   if (N1C && !N1C->isNullValue() &&
2008       (N1C->getAPIntValue().isPowerOf2() ||
2009        (-N1C->getAPIntValue()).isPowerOf2())) {
2010     // If dividing by powers of two is cheap, then don't perform the following
2011     // fold.
2012     if (TLI.isPow2DivCheap())
2013       return SDValue();
2014
2015     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2016
2017     // Splat the sign bit into the register
2018     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2019                               DAG.getConstant(VT.getSizeInBits()-1,
2020                                        getShiftAmountTy(N0.getValueType())));
2021     AddToWorkList(SGN.getNode());
2022
2023     // Add (N0 < 0) ? abs2 - 1 : 0;
2024     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2025                               DAG.getConstant(VT.getSizeInBits() - lg2,
2026                                        getShiftAmountTy(SGN.getValueType())));
2027     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2028     AddToWorkList(SRL.getNode());
2029     AddToWorkList(ADD.getNode());    // Divide by pow2
2030     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2031                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2032
2033     // If we're dividing by a positive value, we're done.  Otherwise, we must
2034     // negate the result.
2035     if (N1C->getAPIntValue().isNonNegative())
2036       return SRA;
2037
2038     AddToWorkList(SRA.getNode());
2039     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2040                        DAG.getConstant(0, VT), SRA);
2041   }
2042
2043   // if integer divide is expensive and we satisfy the requirements, emit an
2044   // alternate sequence.
2045   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2046     SDValue Op = BuildSDIV(N);
2047     if (Op.getNode()) return Op;
2048   }
2049
2050   // undef / X -> 0
2051   if (N0.getOpcode() == ISD::UNDEF)
2052     return DAG.getConstant(0, VT);
2053   // X / undef -> undef
2054   if (N1.getOpcode() == ISD::UNDEF)
2055     return N1;
2056
2057   return SDValue();
2058 }
2059
2060 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2061   SDValue N0 = N->getOperand(0);
2062   SDValue N1 = N->getOperand(1);
2063   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2064   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2065   EVT VT = N->getValueType(0);
2066
2067   // fold vector ops
2068   if (VT.isVector()) {
2069     SDValue FoldedVOp = SimplifyVBinOp(N);
2070     if (FoldedVOp.getNode()) return FoldedVOp;
2071   }
2072
2073   // fold (udiv c1, c2) -> c1/c2
2074   if (N0C && N1C && !N1C->isNullValue())
2075     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2076   // fold (udiv x, (1 << c)) -> x >>u c
2077   if (N1C && N1C->getAPIntValue().isPowerOf2())
2078     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2079                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2080                                        getShiftAmountTy(N0.getValueType())));
2081   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2082   if (N1.getOpcode() == ISD::SHL) {
2083     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2084       if (SHC->getAPIntValue().isPowerOf2()) {
2085         EVT ADDVT = N1.getOperand(1).getValueType();
2086         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2087                                   N1.getOperand(1),
2088                                   DAG.getConstant(SHC->getAPIntValue()
2089                                                                   .logBase2(),
2090                                                   ADDVT));
2091         AddToWorkList(Add.getNode());
2092         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2093       }
2094     }
2095   }
2096   // fold (udiv x, c) -> alternate
2097   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2098     SDValue Op = BuildUDIV(N);
2099     if (Op.getNode()) return Op;
2100   }
2101
2102   // undef / X -> 0
2103   if (N0.getOpcode() == ISD::UNDEF)
2104     return DAG.getConstant(0, VT);
2105   // X / undef -> undef
2106   if (N1.getOpcode() == ISD::UNDEF)
2107     return N1;
2108
2109   return SDValue();
2110 }
2111
2112 SDValue DAGCombiner::visitSREM(SDNode *N) {
2113   SDValue N0 = N->getOperand(0);
2114   SDValue N1 = N->getOperand(1);
2115   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2116   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2117   EVT VT = N->getValueType(0);
2118
2119   // fold (srem c1, c2) -> c1%c2
2120   if (N0C && N1C && !N1C->isNullValue())
2121     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2122   // If we know the sign bits of both operands are zero, strength reduce to a
2123   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2124   if (!VT.isVector()) {
2125     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2126       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2127   }
2128
2129   // If X/C can be simplified by the division-by-constant logic, lower
2130   // X%C to the equivalent of X-X/C*C.
2131   if (N1C && !N1C->isNullValue()) {
2132     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2133     AddToWorkList(Div.getNode());
2134     SDValue OptimizedDiv = combine(Div.getNode());
2135     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2136       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2137                                 OptimizedDiv, N1);
2138       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2139       AddToWorkList(Mul.getNode());
2140       return Sub;
2141     }
2142   }
2143
2144   // undef % X -> 0
2145   if (N0.getOpcode() == ISD::UNDEF)
2146     return DAG.getConstant(0, VT);
2147   // X % undef -> undef
2148   if (N1.getOpcode() == ISD::UNDEF)
2149     return N1;
2150
2151   return SDValue();
2152 }
2153
2154 SDValue DAGCombiner::visitUREM(SDNode *N) {
2155   SDValue N0 = N->getOperand(0);
2156   SDValue N1 = N->getOperand(1);
2157   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2158   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2159   EVT VT = N->getValueType(0);
2160
2161   // fold (urem c1, c2) -> c1%c2
2162   if (N0C && N1C && !N1C->isNullValue())
2163     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2164   // fold (urem x, pow2) -> (and x, pow2-1)
2165   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2166     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2167                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2168   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2169   if (N1.getOpcode() == ISD::SHL) {
2170     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2171       if (SHC->getAPIntValue().isPowerOf2()) {
2172         SDValue Add =
2173           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2174                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2175                                  VT));
2176         AddToWorkList(Add.getNode());
2177         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2178       }
2179     }
2180   }
2181
2182   // If X/C can be simplified by the division-by-constant logic, lower
2183   // X%C to the equivalent of X-X/C*C.
2184   if (N1C && !N1C->isNullValue()) {
2185     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2186     AddToWorkList(Div.getNode());
2187     SDValue OptimizedDiv = combine(Div.getNode());
2188     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2189       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2190                                 OptimizedDiv, N1);
2191       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2192       AddToWorkList(Mul.getNode());
2193       return Sub;
2194     }
2195   }
2196
2197   // undef % X -> 0
2198   if (N0.getOpcode() == ISD::UNDEF)
2199     return DAG.getConstant(0, VT);
2200   // X % undef -> undef
2201   if (N1.getOpcode() == ISD::UNDEF)
2202     return N1;
2203
2204   return SDValue();
2205 }
2206
2207 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2208   SDValue N0 = N->getOperand(0);
2209   SDValue N1 = N->getOperand(1);
2210   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2211   EVT VT = N->getValueType(0);
2212   SDLoc DL(N);
2213
2214   // fold (mulhs x, 0) -> 0
2215   if (N1C && N1C->isNullValue())
2216     return N1;
2217   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2218   if (N1C && N1C->getAPIntValue() == 1)
2219     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2220                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2221                                        getShiftAmountTy(N0.getValueType())));
2222   // fold (mulhs x, undef) -> 0
2223   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2224     return DAG.getConstant(0, VT);
2225
2226   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2227   // plus a shift.
2228   if (VT.isSimple() && !VT.isVector()) {
2229     MVT Simple = VT.getSimpleVT();
2230     unsigned SimpleSize = Simple.getSizeInBits();
2231     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2232     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2233       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2234       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2235       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2236       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2237             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2238       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2239     }
2240   }
2241
2242   return SDValue();
2243 }
2244
2245 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2246   SDValue N0 = N->getOperand(0);
2247   SDValue N1 = N->getOperand(1);
2248   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2249   EVT VT = N->getValueType(0);
2250   SDLoc DL(N);
2251
2252   // fold (mulhu x, 0) -> 0
2253   if (N1C && N1C->isNullValue())
2254     return N1;
2255   // fold (mulhu x, 1) -> 0
2256   if (N1C && N1C->getAPIntValue() == 1)
2257     return DAG.getConstant(0, N0.getValueType());
2258   // fold (mulhu x, undef) -> 0
2259   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2260     return DAG.getConstant(0, VT);
2261
2262   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2263   // plus a shift.
2264   if (VT.isSimple() && !VT.isVector()) {
2265     MVT Simple = VT.getSimpleVT();
2266     unsigned SimpleSize = Simple.getSizeInBits();
2267     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2268     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2269       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2270       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2271       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2272       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2273             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2274       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2275     }
2276   }
2277
2278   return SDValue();
2279 }
2280
2281 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2282 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2283 /// that are being performed. Return true if a simplification was made.
2284 ///
2285 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2286                                                 unsigned HiOp) {
2287   // If the high half is not needed, just compute the low half.
2288   bool HiExists = N->hasAnyUseOfValue(1);
2289   if (!HiExists &&
2290       (!LegalOperations ||
2291        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2292     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2293                               N->op_begin(), N->getNumOperands());
2294     return CombineTo(N, Res, Res);
2295   }
2296
2297   // If the low half is not needed, just compute the high half.
2298   bool LoExists = N->hasAnyUseOfValue(0);
2299   if (!LoExists &&
2300       (!LegalOperations ||
2301        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2302     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2303                               N->op_begin(), N->getNumOperands());
2304     return CombineTo(N, Res, Res);
2305   }
2306
2307   // If both halves are used, return as it is.
2308   if (LoExists && HiExists)
2309     return SDValue();
2310
2311   // If the two computed results can be simplified separately, separate them.
2312   if (LoExists) {
2313     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2314                              N->op_begin(), N->getNumOperands());
2315     AddToWorkList(Lo.getNode());
2316     SDValue LoOpt = combine(Lo.getNode());
2317     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2318         (!LegalOperations ||
2319          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2320       return CombineTo(N, LoOpt, LoOpt);
2321   }
2322
2323   if (HiExists) {
2324     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2325                              N->op_begin(), N->getNumOperands());
2326     AddToWorkList(Hi.getNode());
2327     SDValue HiOpt = combine(Hi.getNode());
2328     if (HiOpt.getNode() && HiOpt != Hi &&
2329         (!LegalOperations ||
2330          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2331       return CombineTo(N, HiOpt, HiOpt);
2332   }
2333
2334   return SDValue();
2335 }
2336
2337 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2338   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2339   if (Res.getNode()) return Res;
2340
2341   EVT VT = N->getValueType(0);
2342   SDLoc DL(N);
2343
2344   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2345   // plus a shift.
2346   if (VT.isSimple() && !VT.isVector()) {
2347     MVT Simple = VT.getSimpleVT();
2348     unsigned SimpleSize = Simple.getSizeInBits();
2349     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2350     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2351       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2352       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2353       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2354       // Compute the high part as N1.
2355       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2356             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2357       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2358       // Compute the low part as N0.
2359       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2360       return CombineTo(N, Lo, Hi);
2361     }
2362   }
2363
2364   return SDValue();
2365 }
2366
2367 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2368   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2369   if (Res.getNode()) return Res;
2370
2371   EVT VT = N->getValueType(0);
2372   SDLoc DL(N);
2373
2374   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2375   // plus a shift.
2376   if (VT.isSimple() && !VT.isVector()) {
2377     MVT Simple = VT.getSimpleVT();
2378     unsigned SimpleSize = Simple.getSizeInBits();
2379     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2380     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2381       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2382       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2383       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2384       // Compute the high part as N1.
2385       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2386             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2387       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2388       // Compute the low part as N0.
2389       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2390       return CombineTo(N, Lo, Hi);
2391     }
2392   }
2393
2394   return SDValue();
2395 }
2396
2397 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2398   // (smulo x, 2) -> (saddo x, x)
2399   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400     if (C2->getAPIntValue() == 2)
2401       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2402                          N->getOperand(0), N->getOperand(0));
2403
2404   return SDValue();
2405 }
2406
2407 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2408   // (umulo x, 2) -> (uaddo x, x)
2409   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2410     if (C2->getAPIntValue() == 2)
2411       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2412                          N->getOperand(0), N->getOperand(0));
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2418   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2419   if (Res.getNode()) return Res;
2420
2421   return SDValue();
2422 }
2423
2424 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2425   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2426   if (Res.getNode()) return Res;
2427
2428   return SDValue();
2429 }
2430
2431 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2432 /// two operands of the same opcode, try to simplify it.
2433 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2434   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2435   EVT VT = N0.getValueType();
2436   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2437
2438   // Bail early if none of these transforms apply.
2439   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2440
2441   // For each of OP in AND/OR/XOR:
2442   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2443   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2444   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2445   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2446   //
2447   // do not sink logical op inside of a vector extend, since it may combine
2448   // into a vsetcc.
2449   EVT Op0VT = N0.getOperand(0).getValueType();
2450   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2451        N0.getOpcode() == ISD::SIGN_EXTEND ||
2452        // Avoid infinite looping with PromoteIntBinOp.
2453        (N0.getOpcode() == ISD::ANY_EXTEND &&
2454         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2455        (N0.getOpcode() == ISD::TRUNCATE &&
2456         (!TLI.isZExtFree(VT, Op0VT) ||
2457          !TLI.isTruncateFree(Op0VT, VT)) &&
2458         TLI.isTypeLegal(Op0VT))) &&
2459       !VT.isVector() &&
2460       Op0VT == N1.getOperand(0).getValueType() &&
2461       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2462     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2463                                  N0.getOperand(0).getValueType(),
2464                                  N0.getOperand(0), N1.getOperand(0));
2465     AddToWorkList(ORNode.getNode());
2466     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2467   }
2468
2469   // For each of OP in SHL/SRL/SRA/AND...
2470   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2471   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2472   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2473   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2474        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2475       N0.getOperand(1) == N1.getOperand(1)) {
2476     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2477                                  N0.getOperand(0).getValueType(),
2478                                  N0.getOperand(0), N1.getOperand(0));
2479     AddToWorkList(ORNode.getNode());
2480     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2481                        ORNode, N0.getOperand(1));
2482   }
2483
2484   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2485   // Only perform this optimization after type legalization and before
2486   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2487   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2488   // we don't want to undo this promotion.
2489   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2490   // on scalars.
2491   if ((N0.getOpcode() == ISD::BITCAST ||
2492        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2493       Level == AfterLegalizeTypes) {
2494     SDValue In0 = N0.getOperand(0);
2495     SDValue In1 = N1.getOperand(0);
2496     EVT In0Ty = In0.getValueType();
2497     EVT In1Ty = In1.getValueType();
2498     SDLoc DL(N);
2499     // If both incoming values are integers, and the original types are the
2500     // same.
2501     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2502       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2503       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2504       AddToWorkList(Op.getNode());
2505       return BC;
2506     }
2507   }
2508
2509   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2510   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2511   // If both shuffles use the same mask, and both shuffle within a single
2512   // vector, then it is worthwhile to move the swizzle after the operation.
2513   // The type-legalizer generates this pattern when loading illegal
2514   // vector types from memory. In many cases this allows additional shuffle
2515   // optimizations.
2516   // There are other cases where moving the shuffle after the xor/and/or
2517   // is profitable even if shuffles don't perform a swizzle.
2518   // If both shuffles use the same mask, and both shuffles have the same first
2519   // or second operand, then it might still be profitable to move the shuffle
2520   // after the xor/and/or operation.
2521   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2522     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2523     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2524
2525     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2526            "Inputs to shuffles are not the same type");
2527  
2528     // Check that both shuffles use the same mask. The masks are known to be of
2529     // the same length because the result vector type is the same.
2530     // Check also that shuffles have only one use to avoid introducing extra
2531     // instructions.
2532     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2533         SVN0->getMask().equals(SVN1->getMask())) {
2534       SDValue ShOp = N0->getOperand(1);
2535
2536       // Don't try to fold this node if it requires introducing a
2537       // build vector of all zeros that might be illegal at this stage.
2538       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2539         if (!LegalTypes)
2540           ShOp = DAG.getConstant(0, VT);
2541         else
2542           ShOp = SDValue();
2543       }
2544
2545       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2546       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2547       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2548       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2549         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2550                                       N0->getOperand(0), N1->getOperand(0));
2551         AddToWorkList(NewNode.getNode());
2552         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2553                                     &SVN0->getMask()[0]);
2554       }
2555
2556       // Don't try to fold this node if it requires introducing a
2557       // build vector of all zeros that might be illegal at this stage.
2558       ShOp = N0->getOperand(0);
2559       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2560         if (!LegalTypes)
2561           ShOp = DAG.getConstant(0, VT);
2562         else
2563           ShOp = SDValue();
2564       }
2565
2566       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2567       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2568       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2569       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2570         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2571                                       N0->getOperand(1), N1->getOperand(1));
2572         AddToWorkList(NewNode.getNode());
2573         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2574                                     &SVN0->getMask()[0]);
2575       }
2576     }
2577   }
2578
2579   return SDValue();
2580 }
2581
2582 SDValue DAGCombiner::visitAND(SDNode *N) {
2583   SDValue N0 = N->getOperand(0);
2584   SDValue N1 = N->getOperand(1);
2585   SDValue LL, LR, RL, RR, CC0, CC1;
2586   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2587   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2588   EVT VT = N1.getValueType();
2589   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2590
2591   // fold vector ops
2592   if (VT.isVector()) {
2593     SDValue FoldedVOp = SimplifyVBinOp(N);
2594     if (FoldedVOp.getNode()) return FoldedVOp;
2595
2596     // fold (and x, 0) -> 0, vector edition
2597     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2598       return N0;
2599     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2600       return N1;
2601
2602     // fold (and x, -1) -> x, vector edition
2603     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2604       return N1;
2605     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2606       return N0;
2607   }
2608
2609   // fold (and x, undef) -> 0
2610   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2611     return DAG.getConstant(0, VT);
2612   // fold (and c1, c2) -> c1&c2
2613   if (N0C && N1C)
2614     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2615   // canonicalize constant to RHS
2616   if (N0C && !N1C)
2617     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2618   // fold (and x, -1) -> x
2619   if (N1C && N1C->isAllOnesValue())
2620     return N0;
2621   // if (and x, c) is known to be zero, return 0
2622   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2623                                    APInt::getAllOnesValue(BitWidth)))
2624     return DAG.getConstant(0, VT);
2625   // reassociate and
2626   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2627   if (RAND.getNode())
2628     return RAND;
2629   // fold (and (or x, C), D) -> D if (C & D) == D
2630   if (N1C && N0.getOpcode() == ISD::OR)
2631     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2632       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2633         return N1;
2634   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2635   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2636     SDValue N0Op0 = N0.getOperand(0);
2637     APInt Mask = ~N1C->getAPIntValue();
2638     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2639     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2640       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2641                                  N0.getValueType(), N0Op0);
2642
2643       // Replace uses of the AND with uses of the Zero extend node.
2644       CombineTo(N, Zext);
2645
2646       // We actually want to replace all uses of the any_extend with the
2647       // zero_extend, to avoid duplicating things.  This will later cause this
2648       // AND to be folded.
2649       CombineTo(N0.getNode(), Zext);
2650       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2651     }
2652   }
2653   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2654   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2655   // already be zero by virtue of the width of the base type of the load.
2656   //
2657   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2658   // more cases.
2659   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2660        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2661       N0.getOpcode() == ISD::LOAD) {
2662     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2663                                          N0 : N0.getOperand(0) );
2664
2665     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2666     // This can be a pure constant or a vector splat, in which case we treat the
2667     // vector as a scalar and use the splat value.
2668     APInt Constant = APInt::getNullValue(1);
2669     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2670       Constant = C->getAPIntValue();
2671     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2672       APInt SplatValue, SplatUndef;
2673       unsigned SplatBitSize;
2674       bool HasAnyUndefs;
2675       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2676                                              SplatBitSize, HasAnyUndefs);
2677       if (IsSplat) {
2678         // Undef bits can contribute to a possible optimisation if set, so
2679         // set them.
2680         SplatValue |= SplatUndef;
2681
2682         // The splat value may be something like "0x00FFFFFF", which means 0 for
2683         // the first vector value and FF for the rest, repeating. We need a mask
2684         // that will apply equally to all members of the vector, so AND all the
2685         // lanes of the constant together.
2686         EVT VT = Vector->getValueType(0);
2687         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2688
2689         // If the splat value has been compressed to a bitlength lower
2690         // than the size of the vector lane, we need to re-expand it to
2691         // the lane size.
2692         if (BitWidth > SplatBitSize)
2693           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2694                SplatBitSize < BitWidth;
2695                SplatBitSize = SplatBitSize * 2)
2696             SplatValue |= SplatValue.shl(SplatBitSize);
2697
2698         Constant = APInt::getAllOnesValue(BitWidth);
2699         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2700           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2701       }
2702     }
2703
2704     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2705     // actually legal and isn't going to get expanded, else this is a false
2706     // optimisation.
2707     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2708                                                     Load->getMemoryVT());
2709
2710     // Resize the constant to the same size as the original memory access before
2711     // extension. If it is still the AllOnesValue then this AND is completely
2712     // unneeded.
2713     Constant =
2714       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2715
2716     bool B;
2717     switch (Load->getExtensionType()) {
2718     default: B = false; break;
2719     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2720     case ISD::ZEXTLOAD:
2721     case ISD::NON_EXTLOAD: B = true; break;
2722     }
2723
2724     if (B && Constant.isAllOnesValue()) {
2725       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2726       // preserve semantics once we get rid of the AND.
2727       SDValue NewLoad(Load, 0);
2728       if (Load->getExtensionType() == ISD::EXTLOAD) {
2729         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2730                               Load->getValueType(0), SDLoc(Load),
2731                               Load->getChain(), Load->getBasePtr(),
2732                               Load->getOffset(), Load->getMemoryVT(),
2733                               Load->getMemOperand());
2734         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2735         if (Load->getNumValues() == 3) {
2736           // PRE/POST_INC loads have 3 values.
2737           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2738                            NewLoad.getValue(2) };
2739           CombineTo(Load, To, 3, true);
2740         } else {
2741           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2742         }
2743       }
2744
2745       // Fold the AND away, taking care not to fold to the old load node if we
2746       // replaced it.
2747       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2748
2749       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2750     }
2751   }
2752   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2753   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2754     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2755     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2756
2757     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2758         LL.getValueType().isInteger()) {
2759       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2760       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2761         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2762                                      LR.getValueType(), LL, RL);
2763         AddToWorkList(ORNode.getNode());
2764         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2765       }
2766       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2767       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2768         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2769                                       LR.getValueType(), LL, RL);
2770         AddToWorkList(ANDNode.getNode());
2771         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2772       }
2773       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2774       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2775         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2776                                      LR.getValueType(), LL, RL);
2777         AddToWorkList(ORNode.getNode());
2778         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2779       }
2780     }
2781     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2782     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2783         Op0 == Op1 && LL.getValueType().isInteger() &&
2784       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2785                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2786                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2787                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2788       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2789                                     LL, DAG.getConstant(1, LL.getValueType()));
2790       AddToWorkList(ADDNode.getNode());
2791       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2792                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2793     }
2794     // canonicalize equivalent to ll == rl
2795     if (LL == RR && LR == RL) {
2796       Op1 = ISD::getSetCCSwappedOperands(Op1);
2797       std::swap(RL, RR);
2798     }
2799     if (LL == RL && LR == RR) {
2800       bool isInteger = LL.getValueType().isInteger();
2801       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2802       if (Result != ISD::SETCC_INVALID &&
2803           (!LegalOperations ||
2804            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2805             TLI.isOperationLegal(ISD::SETCC,
2806                             getSetCCResultType(N0.getSimpleValueType())))))
2807         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2808                             LL, LR, Result);
2809     }
2810   }
2811
2812   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2813   if (N0.getOpcode() == N1.getOpcode()) {
2814     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2815     if (Tmp.getNode()) return Tmp;
2816   }
2817
2818   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2819   // fold (and (sra)) -> (and (srl)) when possible.
2820   if (!VT.isVector() &&
2821       SimplifyDemandedBits(SDValue(N, 0)))
2822     return SDValue(N, 0);
2823
2824   // fold (zext_inreg (extload x)) -> (zextload x)
2825   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2826     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2827     EVT MemVT = LN0->getMemoryVT();
2828     // If we zero all the possible extended bits, then we can turn this into
2829     // a zextload if we are running before legalize or the operation is legal.
2830     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2831     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2832                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2833         ((!LegalOperations && !LN0->isVolatile()) ||
2834          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2835       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2836                                        LN0->getChain(), LN0->getBasePtr(),
2837                                        MemVT, LN0->getMemOperand());
2838       AddToWorkList(N);
2839       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2841     }
2842   }
2843   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2844   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2845       N0.hasOneUse()) {
2846     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2847     EVT MemVT = LN0->getMemoryVT();
2848     // If we zero all the possible extended bits, then we can turn this into
2849     // a zextload if we are running before legalize or the operation is legal.
2850     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2851     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2852                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2853         ((!LegalOperations && !LN0->isVolatile()) ||
2854          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2855       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2856                                        LN0->getChain(), LN0->getBasePtr(),
2857                                        MemVT, LN0->getMemOperand());
2858       AddToWorkList(N);
2859       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2860       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2861     }
2862   }
2863
2864   // fold (and (load x), 255) -> (zextload x, i8)
2865   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2866   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2867   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2868               (N0.getOpcode() == ISD::ANY_EXTEND &&
2869                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2870     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2871     LoadSDNode *LN0 = HasAnyExt
2872       ? cast<LoadSDNode>(N0.getOperand(0))
2873       : cast<LoadSDNode>(N0);
2874     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2875         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2876       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2877       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2878         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2879         EVT LoadedVT = LN0->getMemoryVT();
2880
2881         if (ExtVT == LoadedVT &&
2882             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2883           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2884
2885           SDValue NewLoad =
2886             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2887                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2888                            LN0->getMemOperand());
2889           AddToWorkList(N);
2890           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2891           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2892         }
2893
2894         // Do not change the width of a volatile load.
2895         // Do not generate loads of non-round integer types since these can
2896         // be expensive (and would be wrong if the type is not byte sized).
2897         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2898             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2899           EVT PtrType = LN0->getOperand(1).getValueType();
2900
2901           unsigned Alignment = LN0->getAlignment();
2902           SDValue NewPtr = LN0->getBasePtr();
2903
2904           // For big endian targets, we need to add an offset to the pointer
2905           // to load the correct bytes.  For little endian systems, we merely
2906           // need to read fewer bytes from the same pointer.
2907           if (TLI.isBigEndian()) {
2908             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2909             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2910             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2911             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2912                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2913             Alignment = MinAlign(Alignment, PtrOff);
2914           }
2915
2916           AddToWorkList(NewPtr.getNode());
2917
2918           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2919           SDValue Load =
2920             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2921                            LN0->getChain(), NewPtr,
2922                            LN0->getPointerInfo(),
2923                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2924                            Alignment, LN0->getTBAAInfo());
2925           AddToWorkList(N);
2926           CombineTo(LN0, Load, Load.getValue(1));
2927           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2928         }
2929       }
2930     }
2931   }
2932
2933   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2934       VT.getSizeInBits() <= 64) {
2935     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2936       APInt ADDC = ADDI->getAPIntValue();
2937       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2938         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2939         // immediate for an add, but it is legal if its top c2 bits are set,
2940         // transform the ADD so the immediate doesn't need to be materialized
2941         // in a register.
2942         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2943           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2944                                              SRLI->getZExtValue());
2945           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2946             ADDC |= Mask;
2947             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2948               SDValue NewAdd =
2949                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2950                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2951               CombineTo(N0.getNode(), NewAdd);
2952               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2953             }
2954           }
2955         }
2956       }
2957     }
2958   }
2959
2960   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2961   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2962     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2963                                        N0.getOperand(1), false);
2964     if (BSwap.getNode())
2965       return BSwap;
2966   }
2967
2968   return SDValue();
2969 }
2970
2971 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2972 ///
2973 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2974                                         bool DemandHighBits) {
2975   if (!LegalOperations)
2976     return SDValue();
2977
2978   EVT VT = N->getValueType(0);
2979   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2980     return SDValue();
2981   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2982     return SDValue();
2983
2984   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2985   bool LookPassAnd0 = false;
2986   bool LookPassAnd1 = false;
2987   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2988       std::swap(N0, N1);
2989   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2990       std::swap(N0, N1);
2991   if (N0.getOpcode() == ISD::AND) {
2992     if (!N0.getNode()->hasOneUse())
2993       return SDValue();
2994     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2995     if (!N01C || N01C->getZExtValue() != 0xFF00)
2996       return SDValue();
2997     N0 = N0.getOperand(0);
2998     LookPassAnd0 = true;
2999   }
3000
3001   if (N1.getOpcode() == ISD::AND) {
3002     if (!N1.getNode()->hasOneUse())
3003       return SDValue();
3004     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3005     if (!N11C || N11C->getZExtValue() != 0xFF)
3006       return SDValue();
3007     N1 = N1.getOperand(0);
3008     LookPassAnd1 = true;
3009   }
3010
3011   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3012     std::swap(N0, N1);
3013   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3014     return SDValue();
3015   if (!N0.getNode()->hasOneUse() ||
3016       !N1.getNode()->hasOneUse())
3017     return SDValue();
3018
3019   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3021   if (!N01C || !N11C)
3022     return SDValue();
3023   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3024     return SDValue();
3025
3026   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3027   SDValue N00 = N0->getOperand(0);
3028   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3029     if (!N00.getNode()->hasOneUse())
3030       return SDValue();
3031     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3032     if (!N001C || N001C->getZExtValue() != 0xFF)
3033       return SDValue();
3034     N00 = N00.getOperand(0);
3035     LookPassAnd0 = true;
3036   }
3037
3038   SDValue N10 = N1->getOperand(0);
3039   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3040     if (!N10.getNode()->hasOneUse())
3041       return SDValue();
3042     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3043     if (!N101C || N101C->getZExtValue() != 0xFF00)
3044       return SDValue();
3045     N10 = N10.getOperand(0);
3046     LookPassAnd1 = true;
3047   }
3048
3049   if (N00 != N10)
3050     return SDValue();
3051
3052   // Make sure everything beyond the low halfword gets set to zero since the SRL
3053   // 16 will clear the top bits.
3054   unsigned OpSizeInBits = VT.getSizeInBits();
3055   if (DemandHighBits && OpSizeInBits > 16) {
3056     // If the left-shift isn't masked out then the only way this is a bswap is
3057     // if all bits beyond the low 8 are 0. In that case the entire pattern
3058     // reduces to a left shift anyway: leave it for other parts of the combiner.
3059     if (!LookPassAnd0)
3060       return SDValue();
3061
3062     // However, if the right shift isn't masked out then it might be because
3063     // it's not needed. See if we can spot that too.
3064     if (!LookPassAnd1 &&
3065         !DAG.MaskedValueIsZero(
3066             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3067       return SDValue();
3068   }
3069
3070   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3071   if (OpSizeInBits > 16)
3072     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3073                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3074   return Res;
3075 }
3076
3077 /// isBSwapHWordElement - Return true if the specified node is an element
3078 /// that makes up a 32-bit packed halfword byteswap. i.e.
3079 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3080 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3081   if (!N.getNode()->hasOneUse())
3082     return false;
3083
3084   unsigned Opc = N.getOpcode();
3085   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3086     return false;
3087
3088   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3089   if (!N1C)
3090     return false;
3091
3092   unsigned Num;
3093   switch (N1C->getZExtValue()) {
3094   default:
3095     return false;
3096   case 0xFF:       Num = 0; break;
3097   case 0xFF00:     Num = 1; break;
3098   case 0xFF0000:   Num = 2; break;
3099   case 0xFF000000: Num = 3; break;
3100   }
3101
3102   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3103   SDValue N0 = N.getOperand(0);
3104   if (Opc == ISD::AND) {
3105     if (Num == 0 || Num == 2) {
3106       // (x >> 8) & 0xff
3107       // (x >> 8) & 0xff0000
3108       if (N0.getOpcode() != ISD::SRL)
3109         return false;
3110       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3111       if (!C || C->getZExtValue() != 8)
3112         return false;
3113     } else {
3114       // (x << 8) & 0xff00
3115       // (x << 8) & 0xff000000
3116       if (N0.getOpcode() != ISD::SHL)
3117         return false;
3118       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3119       if (!C || C->getZExtValue() != 8)
3120         return false;
3121     }
3122   } else if (Opc == ISD::SHL) {
3123     // (x & 0xff) << 8
3124     // (x & 0xff0000) << 8
3125     if (Num != 0 && Num != 2)
3126       return false;
3127     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3128     if (!C || C->getZExtValue() != 8)
3129       return false;
3130   } else { // Opc == ISD::SRL
3131     // (x & 0xff00) >> 8
3132     // (x & 0xff000000) >> 8
3133     if (Num != 1 && Num != 3)
3134       return false;
3135     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136     if (!C || C->getZExtValue() != 8)
3137       return false;
3138   }
3139
3140   if (Parts[Num])
3141     return false;
3142
3143   Parts[Num] = N0.getOperand(0).getNode();
3144   return true;
3145 }
3146
3147 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3148 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3149 /// => (rotl (bswap x), 16)
3150 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3151   if (!LegalOperations)
3152     return SDValue();
3153
3154   EVT VT = N->getValueType(0);
3155   if (VT != MVT::i32)
3156     return SDValue();
3157   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3158     return SDValue();
3159
3160   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3161   // Look for either
3162   // (or (or (and), (and)), (or (and), (and)))
3163   // (or (or (or (and), (and)), (and)), (and))
3164   if (N0.getOpcode() != ISD::OR)
3165     return SDValue();
3166   SDValue N00 = N0.getOperand(0);
3167   SDValue N01 = N0.getOperand(1);
3168
3169   if (N1.getOpcode() == ISD::OR &&
3170       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3171     // (or (or (and), (and)), (or (and), (and)))
3172     SDValue N000 = N00.getOperand(0);
3173     if (!isBSwapHWordElement(N000, Parts))
3174       return SDValue();
3175
3176     SDValue N001 = N00.getOperand(1);
3177     if (!isBSwapHWordElement(N001, Parts))
3178       return SDValue();
3179     SDValue N010 = N01.getOperand(0);
3180     if (!isBSwapHWordElement(N010, Parts))
3181       return SDValue();
3182     SDValue N011 = N01.getOperand(1);
3183     if (!isBSwapHWordElement(N011, Parts))
3184       return SDValue();
3185   } else {
3186     // (or (or (or (and), (and)), (and)), (and))
3187     if (!isBSwapHWordElement(N1, Parts))
3188       return SDValue();
3189     if (!isBSwapHWordElement(N01, Parts))
3190       return SDValue();
3191     if (N00.getOpcode() != ISD::OR)
3192       return SDValue();
3193     SDValue N000 = N00.getOperand(0);
3194     if (!isBSwapHWordElement(N000, Parts))
3195       return SDValue();
3196     SDValue N001 = N00.getOperand(1);
3197     if (!isBSwapHWordElement(N001, Parts))
3198       return SDValue();
3199   }
3200
3201   // Make sure the parts are all coming from the same node.
3202   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3203     return SDValue();
3204
3205   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3206                               SDValue(Parts[0],0));
3207
3208   // Result of the bswap should be rotated by 16. If it's not legal, then
3209   // do  (x << 16) | (x >> 16).
3210   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3211   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3212     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3213   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3214     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3215   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3216                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3217                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3218 }
3219
3220 SDValue DAGCombiner::visitOR(SDNode *N) {
3221   SDValue N0 = N->getOperand(0);
3222   SDValue N1 = N->getOperand(1);
3223   SDValue LL, LR, RL, RR, CC0, CC1;
3224   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3225   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3226   EVT VT = N1.getValueType();
3227
3228   // fold vector ops
3229   if (VT.isVector()) {
3230     SDValue FoldedVOp = SimplifyVBinOp(N);
3231     if (FoldedVOp.getNode()) return FoldedVOp;
3232
3233     // fold (or x, 0) -> x, vector edition
3234     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3235       return N1;
3236     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3237       return N0;
3238
3239     // fold (or x, -1) -> -1, vector edition
3240     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3241       return N0;
3242     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3243       return N1;
3244
3245     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3246     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3247     // Do this only if the resulting shuffle is legal.
3248     if (isa<ShuffleVectorSDNode>(N0) &&
3249         isa<ShuffleVectorSDNode>(N1) &&
3250         N0->getOperand(1) == N1->getOperand(1) &&
3251         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3252       bool CanFold = true;
3253       unsigned NumElts = VT.getVectorNumElements();
3254       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3255       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3256       // We construct two shuffle masks:
3257       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3258       // and N1 as the second operand.
3259       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3260       // and N0 as the second operand.
3261       // We do this because OR is commutable and therefore there might be
3262       // two ways to fold this node into a shuffle.
3263       SmallVector<int,4> Mask1;
3264       SmallVector<int,4> Mask2;
3265       
3266       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3267         int M0 = SV0->getMaskElt(i);
3268         int M1 = SV1->getMaskElt(i);
3269    
3270         // Both shuffle indexes are undef. Propagate Undef.
3271         if (M0 < 0 && M1 < 0) {
3272           Mask1.push_back(M0);
3273           Mask2.push_back(M0);
3274           continue;
3275         }
3276
3277         if (M0 < 0 || M1 < 0 ||
3278             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3279             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3280           CanFold = false;
3281           break;
3282         }
3283         
3284         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3285         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3286       }
3287
3288       if (CanFold) {
3289         // Fold this sequence only if the resulting shuffle is 'legal'.
3290         if (TLI.isShuffleMaskLegal(Mask1, VT))
3291           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3292                                       N1->getOperand(0), &Mask1[0]);
3293         if (TLI.isShuffleMaskLegal(Mask2, VT))
3294           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3295                                       N0->getOperand(0), &Mask2[0]);
3296       }
3297     }
3298   }
3299
3300   // fold (or x, undef) -> -1
3301   if (!LegalOperations &&
3302       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3303     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3304     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3305   }
3306   // fold (or c1, c2) -> c1|c2
3307   if (N0C && N1C)
3308     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3309   // canonicalize constant to RHS
3310   if (N0C && !N1C)
3311     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3312   // fold (or x, 0) -> x
3313   if (N1C && N1C->isNullValue())
3314     return N0;
3315   // fold (or x, -1) -> -1
3316   if (N1C && N1C->isAllOnesValue())
3317     return N1;
3318   // fold (or x, c) -> c iff (x & ~c) == 0
3319   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3320     return N1;
3321
3322   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3323   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3324   if (BSwap.getNode())
3325     return BSwap;
3326   BSwap = MatchBSwapHWordLow(N, N0, N1);
3327   if (BSwap.getNode())
3328     return BSwap;
3329
3330   // reassociate or
3331   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3332   if (ROR.getNode())
3333     return ROR;
3334   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3335   // iff (c1 & c2) == 0.
3336   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3337              isa<ConstantSDNode>(N0.getOperand(1))) {
3338     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3339     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3340       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3341       if (!COR.getNode())
3342         return SDValue();
3343       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3344                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3345                                      N0.getOperand(0), N1), COR);
3346     }
3347   }
3348   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3349   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3350     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3351     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3352
3353     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3354         LL.getValueType().isInteger()) {
3355       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3356       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3357       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3358           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3359         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3360                                      LR.getValueType(), LL, RL);
3361         AddToWorkList(ORNode.getNode());
3362         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3363       }
3364       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3365       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3366       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3367           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3368         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3369                                       LR.getValueType(), LL, RL);
3370         AddToWorkList(ANDNode.getNode());
3371         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3372       }
3373     }
3374     // canonicalize equivalent to ll == rl
3375     if (LL == RR && LR == RL) {
3376       Op1 = ISD::getSetCCSwappedOperands(Op1);
3377       std::swap(RL, RR);
3378     }
3379     if (LL == RL && LR == RR) {
3380       bool isInteger = LL.getValueType().isInteger();
3381       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3382       if (Result != ISD::SETCC_INVALID &&
3383           (!LegalOperations ||
3384            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3385             TLI.isOperationLegal(ISD::SETCC,
3386               getSetCCResultType(N0.getValueType())))))
3387         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3388                             LL, LR, Result);
3389     }
3390   }
3391
3392   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3393   if (N0.getOpcode() == N1.getOpcode()) {
3394     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3395     if (Tmp.getNode()) return Tmp;
3396   }
3397
3398   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3399   if (N0.getOpcode() == ISD::AND &&
3400       N1.getOpcode() == ISD::AND &&
3401       N0.getOperand(1).getOpcode() == ISD::Constant &&
3402       N1.getOperand(1).getOpcode() == ISD::Constant &&
3403       // Don't increase # computations.
3404       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3405     // We can only do this xform if we know that bits from X that are set in C2
3406     // but not in C1 are already zero.  Likewise for Y.
3407     const APInt &LHSMask =
3408       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3409     const APInt &RHSMask =
3410       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3411
3412     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3413         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3414       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3415                               N0.getOperand(0), N1.getOperand(0));
3416       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3417                          DAG.getConstant(LHSMask | RHSMask, VT));
3418     }
3419   }
3420
3421   // See if this is some rotate idiom.
3422   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3423     return SDValue(Rot, 0);
3424
3425   // Simplify the operands using demanded-bits information.
3426   if (!VT.isVector() &&
3427       SimplifyDemandedBits(SDValue(N, 0)))
3428     return SDValue(N, 0);
3429
3430   return SDValue();
3431 }
3432
3433 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3434 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3435   if (Op.getOpcode() == ISD::AND) {
3436     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3437       Mask = Op.getOperand(1);
3438       Op = Op.getOperand(0);
3439     } else {
3440       return false;
3441     }
3442   }
3443
3444   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3445     Shift = Op;
3446     return true;
3447   }
3448
3449   return false;
3450 }
3451
3452 // Return true if we can prove that, whenever Neg and Pos are both in the
3453 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3454 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3455 //
3456 //     (or (shift1 X, Neg), (shift2 X, Pos))
3457 //
3458 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3459 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3460 // to consider shift amounts with defined behavior.
3461 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3462   // If OpSize is a power of 2 then:
3463   //
3464   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3465   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3466   //
3467   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3468   // for the stronger condition:
3469   //
3470   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3471   //
3472   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3473   // we can just replace Neg with Neg' for the rest of the function.
3474   //
3475   // In other cases we check for the even stronger condition:
3476   //
3477   //     Neg == OpSize - Pos                                    [B]
3478   //
3479   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3480   // behavior if Pos == 0 (and consequently Neg == OpSize).
3481   //
3482   // We could actually use [A] whenever OpSize is a power of 2, but the
3483   // only extra cases that it would match are those uninteresting ones
3484   // where Neg and Pos are never in range at the same time.  E.g. for
3485   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3486   // as well as (sub 32, Pos), but:
3487   //
3488   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3489   //
3490   // always invokes undefined behavior for 32-bit X.
3491   //
3492   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3493   unsigned MaskLoBits = 0;
3494   if (Neg.getOpcode() == ISD::AND &&
3495       isPowerOf2_64(OpSize) &&
3496       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3497       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3498     Neg = Neg.getOperand(0);
3499     MaskLoBits = Log2_64(OpSize);
3500   }
3501
3502   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3503   if (Neg.getOpcode() != ISD::SUB)
3504     return 0;
3505   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3506   if (!NegC)
3507     return 0;
3508   SDValue NegOp1 = Neg.getOperand(1);
3509
3510   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3511   // Pos'.  The truncation is redundant for the purpose of the equality.
3512   if (MaskLoBits &&
3513       Pos.getOpcode() == ISD::AND &&
3514       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3515       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3516     Pos = Pos.getOperand(0);
3517
3518   // The condition we need is now:
3519   //
3520   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3521   //
3522   // If NegOp1 == Pos then we need:
3523   //
3524   //              OpSize & Mask == NegC & Mask
3525   //
3526   // (because "x & Mask" is a truncation and distributes through subtraction).
3527   APInt Width;
3528   if (Pos == NegOp1)
3529     Width = NegC->getAPIntValue();
3530   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3531   // Then the condition we want to prove becomes:
3532   //
3533   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3534   //
3535   // which, again because "x & Mask" is a truncation, becomes:
3536   //
3537   //                NegC & Mask == (OpSize - PosC) & Mask
3538   //              OpSize & Mask == (NegC + PosC) & Mask
3539   else if (Pos.getOpcode() == ISD::ADD &&
3540            Pos.getOperand(0) == NegOp1 &&
3541            Pos.getOperand(1).getOpcode() == ISD::Constant)
3542     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3543              NegC->getAPIntValue());
3544   else
3545     return false;
3546
3547   // Now we just need to check that OpSize & Mask == Width & Mask.
3548   if (MaskLoBits)
3549     // Opsize & Mask is 0 since Mask is Opsize - 1.
3550     return Width.getLoBits(MaskLoBits) == 0;
3551   return Width == OpSize;
3552 }
3553
3554 // A subroutine of MatchRotate used once we have found an OR of two opposite
3555 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3556 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3557 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3558 // Neg with outer conversions stripped away.
3559 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3560                                        SDValue Neg, SDValue InnerPos,
3561                                        SDValue InnerNeg, unsigned PosOpcode,
3562                                        unsigned NegOpcode, SDLoc DL) {
3563   // fold (or (shl x, (*ext y)),
3564   //          (srl x, (*ext (sub 32, y)))) ->
3565   //   (rotl x, y) or (rotr x, (sub 32, y))
3566   //
3567   // fold (or (shl x, (*ext (sub 32, y))),
3568   //          (srl x, (*ext y))) ->
3569   //   (rotr x, y) or (rotl x, (sub 32, y))
3570   EVT VT = Shifted.getValueType();
3571   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3572     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3573     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3574                        HasPos ? Pos : Neg).getNode();
3575   }
3576
3577   // fold (or (shl (*ext x), (*ext y)),
3578   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3579   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3580   //
3581   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3582   //          (srl (*ext x), (*ext y))) ->
3583   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3584   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3585       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3586     SDValue InnerShifted = Shifted.getOperand(0);
3587     EVT InnerVT = InnerShifted.getValueType();
3588     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3589     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3590       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3591         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3592                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3593         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3594       }
3595     }
3596   }
3597
3598   return nullptr;
3599 }
3600
3601 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3602 // idioms for rotate, and if the target supports rotation instructions, generate
3603 // a rot[lr].
3604 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3605   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3606   EVT VT = LHS.getValueType();
3607   if (!TLI.isTypeLegal(VT)) return nullptr;
3608
3609   // The target must have at least one rotate flavor.
3610   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3611   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3612   if (!HasROTL && !HasROTR) return nullptr;
3613
3614   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3615   SDValue LHSShift;   // The shift.
3616   SDValue LHSMask;    // AND value if any.
3617   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3618     return nullptr; // Not part of a rotate.
3619
3620   SDValue RHSShift;   // The shift.
3621   SDValue RHSMask;    // AND value if any.
3622   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3623     return nullptr; // Not part of a rotate.
3624
3625   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3626     return nullptr;   // Not shifting the same value.
3627
3628   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3629     return nullptr;   // Shifts must disagree.
3630
3631   // Canonicalize shl to left side in a shl/srl pair.
3632   if (RHSShift.getOpcode() == ISD::SHL) {
3633     std::swap(LHS, RHS);
3634     std::swap(LHSShift, RHSShift);
3635     std::swap(LHSMask , RHSMask );
3636   }
3637
3638   unsigned OpSizeInBits = VT.getSizeInBits();
3639   SDValue LHSShiftArg = LHSShift.getOperand(0);
3640   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3641   SDValue RHSShiftArg = RHSShift.getOperand(0);
3642   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3643
3644   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3645   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3646   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3647       RHSShiftAmt.getOpcode() == ISD::Constant) {
3648     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3649     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3650     if ((LShVal + RShVal) != OpSizeInBits)
3651       return nullptr;
3652
3653     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3654                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3655
3656     // If there is an AND of either shifted operand, apply it to the result.
3657     if (LHSMask.getNode() || RHSMask.getNode()) {
3658       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3659
3660       if (LHSMask.getNode()) {
3661         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3662         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3663       }
3664       if (RHSMask.getNode()) {
3665         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3666         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3667       }
3668
3669       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3670     }
3671
3672     return Rot.getNode();
3673   }
3674
3675   // If there is a mask here, and we have a variable shift, we can't be sure
3676   // that we're masking out the right stuff.
3677   if (LHSMask.getNode() || RHSMask.getNode())
3678     return nullptr;
3679
3680   // If the shift amount is sign/zext/any-extended just peel it off.
3681   SDValue LExtOp0 = LHSShiftAmt;
3682   SDValue RExtOp0 = RHSShiftAmt;
3683   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3684        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3685        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3686        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3687       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3688        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3689        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3690        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3691     LExtOp0 = LHSShiftAmt.getOperand(0);
3692     RExtOp0 = RHSShiftAmt.getOperand(0);
3693   }
3694
3695   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3696                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3697   if (TryL)
3698     return TryL;
3699
3700   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3701                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3702   if (TryR)
3703     return TryR;
3704
3705   return nullptr;
3706 }
3707
3708 SDValue DAGCombiner::visitXOR(SDNode *N) {
3709   SDValue N0 = N->getOperand(0);
3710   SDValue N1 = N->getOperand(1);
3711   SDValue LHS, RHS, CC;
3712   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3713   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3714   EVT VT = N0.getValueType();
3715
3716   // fold vector ops
3717   if (VT.isVector()) {
3718     SDValue FoldedVOp = SimplifyVBinOp(N);
3719     if (FoldedVOp.getNode()) return FoldedVOp;
3720
3721     // fold (xor x, 0) -> x, vector edition
3722     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3723       return N1;
3724     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3725       return N0;
3726   }
3727
3728   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3729   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3730     return DAG.getConstant(0, VT);
3731   // fold (xor x, undef) -> undef
3732   if (N0.getOpcode() == ISD::UNDEF)
3733     return N0;
3734   if (N1.getOpcode() == ISD::UNDEF)
3735     return N1;
3736   // fold (xor c1, c2) -> c1^c2
3737   if (N0C && N1C)
3738     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3739   // canonicalize constant to RHS
3740   if (N0C && !N1C)
3741     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3742   // fold (xor x, 0) -> x
3743   if (N1C && N1C->isNullValue())
3744     return N0;
3745   // reassociate xor
3746   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3747   if (RXOR.getNode())
3748     return RXOR;
3749
3750   // fold !(x cc y) -> (x !cc y)
3751   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3752     bool isInt = LHS.getValueType().isInteger();
3753     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3754                                                isInt);
3755
3756     if (!LegalOperations ||
3757         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3758       switch (N0.getOpcode()) {
3759       default:
3760         llvm_unreachable("Unhandled SetCC Equivalent!");
3761       case ISD::SETCC:
3762         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3763       case ISD::SELECT_CC:
3764         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3765                                N0.getOperand(3), NotCC);
3766       }
3767     }
3768   }
3769
3770   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3771   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3772       N0.getNode()->hasOneUse() &&
3773       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3774     SDValue V = N0.getOperand(0);
3775     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3776                     DAG.getConstant(1, V.getValueType()));
3777     AddToWorkList(V.getNode());
3778     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3779   }
3780
3781   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3782   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3783       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3784     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3785     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3786       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3787       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3788       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3789       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3790       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3791     }
3792   }
3793   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3794   if (N1C && N1C->isAllOnesValue() &&
3795       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3796     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3797     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3798       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3799       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3800       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3801       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3802       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3803     }
3804   }
3805   // fold (xor (and x, y), y) -> (and (not x), y)
3806   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3807       N0->getOperand(1) == N1) {
3808     SDValue X = N0->getOperand(0);
3809     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3810     AddToWorkList(NotX.getNode());
3811     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3812   }
3813   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3814   if (N1C && N0.getOpcode() == ISD::XOR) {
3815     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3816     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3817     if (N00C)
3818       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3819                          DAG.getConstant(N1C->getAPIntValue() ^
3820                                          N00C->getAPIntValue(), VT));
3821     if (N01C)
3822       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3823                          DAG.getConstant(N1C->getAPIntValue() ^
3824                                          N01C->getAPIntValue(), VT));
3825   }
3826   // fold (xor x, x) -> 0
3827   if (N0 == N1)
3828     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3829
3830   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3831   if (N0.getOpcode() == N1.getOpcode()) {
3832     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3833     if (Tmp.getNode()) return Tmp;
3834   }
3835
3836   // Simplify the expression using non-local knowledge.
3837   if (!VT.isVector() &&
3838       SimplifyDemandedBits(SDValue(N, 0)))
3839     return SDValue(N, 0);
3840
3841   return SDValue();
3842 }
3843
3844 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3845 /// the shift amount is a constant.
3846 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3847   // We can't and shouldn't fold opaque constants.
3848   if (Amt->isOpaque())
3849     return SDValue();
3850
3851   SDNode *LHS = N->getOperand(0).getNode();
3852   if (!LHS->hasOneUse()) return SDValue();
3853
3854   // We want to pull some binops through shifts, so that we have (and (shift))
3855   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3856   // thing happens with address calculations, so it's important to canonicalize
3857   // it.
3858   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3859
3860   switch (LHS->getOpcode()) {
3861   default: return SDValue();
3862   case ISD::OR:
3863   case ISD::XOR:
3864     HighBitSet = false; // We can only transform sra if the high bit is clear.
3865     break;
3866   case ISD::AND:
3867     HighBitSet = true;  // We can only transform sra if the high bit is set.
3868     break;
3869   case ISD::ADD:
3870     if (N->getOpcode() != ISD::SHL)
3871       return SDValue(); // only shl(add) not sr[al](add).
3872     HighBitSet = false; // We can only transform sra if the high bit is clear.
3873     break;
3874   }
3875
3876   // We require the RHS of the binop to be a constant and not opaque as well.
3877   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3878   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3879
3880   // FIXME: disable this unless the input to the binop is a shift by a constant.
3881   // If it is not a shift, it pessimizes some common cases like:
3882   //
3883   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3884   //    int bar(int *X, int i) { return X[i & 255]; }
3885   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3886   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3887        BinOpLHSVal->getOpcode() != ISD::SRA &&
3888        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3889       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3890     return SDValue();
3891
3892   EVT VT = N->getValueType(0);
3893
3894   // If this is a signed shift right, and the high bit is modified by the
3895   // logical operation, do not perform the transformation. The highBitSet
3896   // boolean indicates the value of the high bit of the constant which would
3897   // cause it to be modified for this operation.
3898   if (N->getOpcode() == ISD::SRA) {
3899     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3900     if (BinOpRHSSignSet != HighBitSet)
3901       return SDValue();
3902   }
3903
3904   // Fold the constants, shifting the binop RHS by the shift amount.
3905   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3906                                N->getValueType(0),
3907                                LHS->getOperand(1), N->getOperand(1));
3908   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3909
3910   // Create the new shift.
3911   SDValue NewShift = DAG.getNode(N->getOpcode(),
3912                                  SDLoc(LHS->getOperand(0)),
3913                                  VT, LHS->getOperand(0), N->getOperand(1));
3914
3915   // Create the new binop.
3916   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3917 }
3918
3919 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3920   assert(N->getOpcode() == ISD::TRUNCATE);
3921   assert(N->getOperand(0).getOpcode() == ISD::AND);
3922
3923   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3924   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3925     SDValue N01 = N->getOperand(0).getOperand(1);
3926
3927     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3928       EVT TruncVT = N->getValueType(0);
3929       SDValue N00 = N->getOperand(0).getOperand(0);
3930       APInt TruncC = N01C->getAPIntValue();
3931       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3932
3933       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3934                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3935                          DAG.getConstant(TruncC, TruncVT));
3936     }
3937   }
3938
3939   return SDValue();
3940 }
3941
3942 SDValue DAGCombiner::visitRotate(SDNode *N) {
3943   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3944   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3945       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3946     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3947     if (NewOp1.getNode())
3948       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3949                          N->getOperand(0), NewOp1);
3950   }
3951   return SDValue();
3952 }
3953
3954 SDValue DAGCombiner::visitSHL(SDNode *N) {
3955   SDValue N0 = N->getOperand(0);
3956   SDValue N1 = N->getOperand(1);
3957   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3958   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3959   EVT VT = N0.getValueType();
3960   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3961
3962   // fold vector ops
3963   if (VT.isVector()) {
3964     SDValue FoldedVOp = SimplifyVBinOp(N);
3965     if (FoldedVOp.getNode()) return FoldedVOp;
3966
3967     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3968     // If setcc produces all-one true value then:
3969     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3970     if (N1CV && N1CV->isConstant()) {
3971       if (N0.getOpcode() == ISD::AND &&
3972           TLI.getBooleanContents(true) ==
3973           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3974         SDValue N00 = N0->getOperand(0);
3975         SDValue N01 = N0->getOperand(1);
3976         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3977
3978         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3979           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3980           if (C.getNode())
3981             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3982         }
3983       } else {
3984         N1C = isConstOrConstSplat(N1);
3985       }
3986     }
3987   }
3988
3989   // fold (shl c1, c2) -> c1<<c2
3990   if (N0C && N1C)
3991     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3992   // fold (shl 0, x) -> 0
3993   if (N0C && N0C->isNullValue())
3994     return N0;
3995   // fold (shl x, c >= size(x)) -> undef
3996   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3997     return DAG.getUNDEF(VT);
3998   // fold (shl x, 0) -> x
3999   if (N1C && N1C->isNullValue())
4000     return N0;
4001   // fold (shl undef, x) -> 0
4002   if (N0.getOpcode() == ISD::UNDEF)
4003     return DAG.getConstant(0, VT);
4004   // if (shl x, c) is known to be zero, return 0
4005   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4006                             APInt::getAllOnesValue(OpSizeInBits)))
4007     return DAG.getConstant(0, VT);
4008   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4009   if (N1.getOpcode() == ISD::TRUNCATE &&
4010       N1.getOperand(0).getOpcode() == ISD::AND) {
4011     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4012     if (NewOp1.getNode())
4013       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4014   }
4015
4016   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4017     return SDValue(N, 0);
4018
4019   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4020   if (N1C && N0.getOpcode() == ISD::SHL) {
4021     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4022       uint64_t c1 = N0C1->getZExtValue();
4023       uint64_t c2 = N1C->getZExtValue();
4024       if (c1 + c2 >= OpSizeInBits)
4025         return DAG.getConstant(0, VT);
4026       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4027                          DAG.getConstant(c1 + c2, N1.getValueType()));
4028     }
4029   }
4030
4031   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4032   // For this to be valid, the second form must not preserve any of the bits
4033   // that are shifted out by the inner shift in the first form.  This means
4034   // the outer shift size must be >= the number of bits added by the ext.
4035   // As a corollary, we don't care what kind of ext it is.
4036   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4037               N0.getOpcode() == ISD::ANY_EXTEND ||
4038               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4039       N0.getOperand(0).getOpcode() == ISD::SHL) {
4040     SDValue N0Op0 = N0.getOperand(0);
4041     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4042       uint64_t c1 = N0Op0C1->getZExtValue();
4043       uint64_t c2 = N1C->getZExtValue();
4044       EVT InnerShiftVT = N0Op0.getValueType();
4045       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4046       if (c2 >= OpSizeInBits - InnerShiftSize) {
4047         if (c1 + c2 >= OpSizeInBits)
4048           return DAG.getConstant(0, VT);
4049         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4050                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4051                                        N0Op0->getOperand(0)),
4052                            DAG.getConstant(c1 + c2, N1.getValueType()));
4053       }
4054     }
4055   }
4056
4057   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4058   // Only fold this if the inner zext has no other uses to avoid increasing
4059   // the total number of instructions.
4060   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4061       N0.getOperand(0).getOpcode() == ISD::SRL) {
4062     SDValue N0Op0 = N0.getOperand(0);
4063     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4064       uint64_t c1 = N0Op0C1->getZExtValue();
4065       if (c1 < VT.getScalarSizeInBits()) {
4066         uint64_t c2 = N1C->getZExtValue();
4067         if (c1 == c2) {
4068           SDValue NewOp0 = N0.getOperand(0);
4069           EVT CountVT = NewOp0.getOperand(1).getValueType();
4070           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4071                                        NewOp0, DAG.getConstant(c2, CountVT));
4072           AddToWorkList(NewSHL.getNode());
4073           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4074         }
4075       }
4076     }
4077   }
4078
4079   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4080   //                               (and (srl x, (sub c1, c2), MASK)
4081   // Only fold this if the inner shift has no other uses -- if it does, folding
4082   // this will increase the total number of instructions.
4083   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4084     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4085       uint64_t c1 = N0C1->getZExtValue();
4086       if (c1 < OpSizeInBits) {
4087         uint64_t c2 = N1C->getZExtValue();
4088         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4089         SDValue Shift;
4090         if (c2 > c1) {
4091           Mask = Mask.shl(c2 - c1);
4092           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4093                               DAG.getConstant(c2 - c1, N1.getValueType()));
4094         } else {
4095           Mask = Mask.lshr(c1 - c2);
4096           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4097                               DAG.getConstant(c1 - c2, N1.getValueType()));
4098         }
4099         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4100                            DAG.getConstant(Mask, VT));
4101       }
4102     }
4103   }
4104   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4105   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4106     unsigned BitSize = VT.getScalarSizeInBits();
4107     SDValue HiBitsMask =
4108       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4109                                             BitSize - N1C->getZExtValue()), VT);
4110     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4111                        HiBitsMask);
4112   }
4113
4114   if (N1C) {
4115     SDValue NewSHL = visitShiftByConstant(N, N1C);
4116     if (NewSHL.getNode())
4117       return NewSHL;
4118   }
4119
4120   return SDValue();
4121 }
4122
4123 SDValue DAGCombiner::visitSRA(SDNode *N) {
4124   SDValue N0 = N->getOperand(0);
4125   SDValue N1 = N->getOperand(1);
4126   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4127   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4128   EVT VT = N0.getValueType();
4129   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4130
4131   // fold vector ops
4132   if (VT.isVector()) {
4133     SDValue FoldedVOp = SimplifyVBinOp(N);
4134     if (FoldedVOp.getNode()) return FoldedVOp;
4135
4136     N1C = isConstOrConstSplat(N1);
4137   }
4138
4139   // fold (sra c1, c2) -> (sra c1, c2)
4140   if (N0C && N1C)
4141     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4142   // fold (sra 0, x) -> 0
4143   if (N0C && N0C->isNullValue())
4144     return N0;
4145   // fold (sra -1, x) -> -1
4146   if (N0C && N0C->isAllOnesValue())
4147     return N0;
4148   // fold (sra x, (setge c, size(x))) -> undef
4149   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4150     return DAG.getUNDEF(VT);
4151   // fold (sra x, 0) -> x
4152   if (N1C && N1C->isNullValue())
4153     return N0;
4154   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4155   // sext_inreg.
4156   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4157     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4158     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4159     if (VT.isVector())
4160       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4161                                ExtVT, VT.getVectorNumElements());
4162     if ((!LegalOperations ||
4163          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4164       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4165                          N0.getOperand(0), DAG.getValueType(ExtVT));
4166   }
4167
4168   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4169   if (N1C && N0.getOpcode() == ISD::SRA) {
4170     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4171       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4172       if (Sum >= OpSizeInBits)
4173         Sum = OpSizeInBits - 1;
4174       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4175                          DAG.getConstant(Sum, N1.getValueType()));
4176     }
4177   }
4178
4179   // fold (sra (shl X, m), (sub result_size, n))
4180   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4181   // result_size - n != m.
4182   // If truncate is free for the target sext(shl) is likely to result in better
4183   // code.
4184   if (N0.getOpcode() == ISD::SHL && N1C) {
4185     // Get the two constanst of the shifts, CN0 = m, CN = n.
4186     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4187     if (N01C) {
4188       LLVMContext &Ctx = *DAG.getContext();
4189       // Determine what the truncate's result bitsize and type would be.
4190       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4191
4192       if (VT.isVector())
4193         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4194
4195       // Determine the residual right-shift amount.
4196       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4197
4198       // If the shift is not a no-op (in which case this should be just a sign
4199       // extend already), the truncated to type is legal, sign_extend is legal
4200       // on that type, and the truncate to that type is both legal and free,
4201       // perform the transform.
4202       if ((ShiftAmt > 0) &&
4203           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4204           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4205           TLI.isTruncateFree(VT, TruncVT)) {
4206
4207           SDValue Amt = DAG.getConstant(ShiftAmt,
4208               getShiftAmountTy(N0.getOperand(0).getValueType()));
4209           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4210                                       N0.getOperand(0), Amt);
4211           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4212                                       Shift);
4213           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4214                              N->getValueType(0), Trunc);
4215       }
4216     }
4217   }
4218
4219   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4220   if (N1.getOpcode() == ISD::TRUNCATE &&
4221       N1.getOperand(0).getOpcode() == ISD::AND) {
4222     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4223     if (NewOp1.getNode())
4224       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4225   }
4226
4227   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4228   //      if c1 is equal to the number of bits the trunc removes
4229   if (N0.getOpcode() == ISD::TRUNCATE &&
4230       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4231        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4232       N0.getOperand(0).hasOneUse() &&
4233       N0.getOperand(0).getOperand(1).hasOneUse() &&
4234       N1C) {
4235     SDValue N0Op0 = N0.getOperand(0);
4236     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4237       unsigned LargeShiftVal = LargeShift->getZExtValue();
4238       EVT LargeVT = N0Op0.getValueType();
4239
4240       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4241         SDValue Amt =
4242           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4243                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4244         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4245                                   N0Op0.getOperand(0), Amt);
4246         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4247       }
4248     }
4249   }
4250
4251   // Simplify, based on bits shifted out of the LHS.
4252   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4253     return SDValue(N, 0);
4254
4255
4256   // If the sign bit is known to be zero, switch this to a SRL.
4257   if (DAG.SignBitIsZero(N0))
4258     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4259
4260   if (N1C) {
4261     SDValue NewSRA = visitShiftByConstant(N, N1C);
4262     if (NewSRA.getNode())
4263       return NewSRA;
4264   }
4265
4266   return SDValue();
4267 }
4268
4269 SDValue DAGCombiner::visitSRL(SDNode *N) {
4270   SDValue N0 = N->getOperand(0);
4271   SDValue N1 = N->getOperand(1);
4272   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4273   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4274   EVT VT = N0.getValueType();
4275   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4276
4277   // fold vector ops
4278   if (VT.isVector()) {
4279     SDValue FoldedVOp = SimplifyVBinOp(N);
4280     if (FoldedVOp.getNode()) return FoldedVOp;
4281
4282     N1C = isConstOrConstSplat(N1);
4283   }
4284
4285   // fold (srl c1, c2) -> c1 >>u c2
4286   if (N0C && N1C)
4287     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4288   // fold (srl 0, x) -> 0
4289   if (N0C && N0C->isNullValue())
4290     return N0;
4291   // fold (srl x, c >= size(x)) -> undef
4292   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4293     return DAG.getUNDEF(VT);
4294   // fold (srl x, 0) -> x
4295   if (N1C && N1C->isNullValue())
4296     return N0;
4297   // if (srl x, c) is known to be zero, return 0
4298   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4299                                    APInt::getAllOnesValue(OpSizeInBits)))
4300     return DAG.getConstant(0, VT);
4301
4302   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4303   if (N1C && N0.getOpcode() == ISD::SRL) {
4304     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4305       uint64_t c1 = N01C->getZExtValue();
4306       uint64_t c2 = N1C->getZExtValue();
4307       if (c1 + c2 >= OpSizeInBits)
4308         return DAG.getConstant(0, VT);
4309       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4310                          DAG.getConstant(c1 + c2, N1.getValueType()));
4311     }
4312   }
4313
4314   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4315   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4316       N0.getOperand(0).getOpcode() == ISD::SRL &&
4317       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4318     uint64_t c1 =
4319       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4320     uint64_t c2 = N1C->getZExtValue();
4321     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4322     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4323     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4324     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4325     if (c1 + OpSizeInBits == InnerShiftSize) {
4326       if (c1 + c2 >= InnerShiftSize)
4327         return DAG.getConstant(0, VT);
4328       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4329                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4330                                      N0.getOperand(0)->getOperand(0),
4331                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4332     }
4333   }
4334
4335   // fold (srl (shl x, c), c) -> (and x, cst2)
4336   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4337     unsigned BitSize = N0.getScalarValueSizeInBits();
4338     if (BitSize <= 64) {
4339       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4340       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4341                          DAG.getConstant(~0ULL >> ShAmt, VT));
4342     }
4343   }
4344
4345   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4346   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4347     // Shifting in all undef bits?
4348     EVT SmallVT = N0.getOperand(0).getValueType();
4349     unsigned BitSize = SmallVT.getScalarSizeInBits();
4350     if (N1C->getZExtValue() >= BitSize)
4351       return DAG.getUNDEF(VT);
4352
4353     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4354       uint64_t ShiftAmt = N1C->getZExtValue();
4355       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4356                                        N0.getOperand(0),
4357                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4358       AddToWorkList(SmallShift.getNode());
4359       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4360       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4361                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4362                          DAG.getConstant(Mask, VT));
4363     }
4364   }
4365
4366   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4367   // bit, which is unmodified by sra.
4368   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4369     if (N0.getOpcode() == ISD::SRA)
4370       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4371   }
4372
4373   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4374   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4375       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4376     APInt KnownZero, KnownOne;
4377     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4378
4379     // If any of the input bits are KnownOne, then the input couldn't be all
4380     // zeros, thus the result of the srl will always be zero.
4381     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4382
4383     // If all of the bits input the to ctlz node are known to be zero, then
4384     // the result of the ctlz is "32" and the result of the shift is one.
4385     APInt UnknownBits = ~KnownZero;
4386     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4387
4388     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4389     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4390       // Okay, we know that only that the single bit specified by UnknownBits
4391       // could be set on input to the CTLZ node. If this bit is set, the SRL
4392       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4393       // to an SRL/XOR pair, which is likely to simplify more.
4394       unsigned ShAmt = UnknownBits.countTrailingZeros();
4395       SDValue Op = N0.getOperand(0);
4396
4397       if (ShAmt) {
4398         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4399                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4400         AddToWorkList(Op.getNode());
4401       }
4402
4403       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4404                          Op, DAG.getConstant(1, VT));
4405     }
4406   }
4407
4408   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4409   if (N1.getOpcode() == ISD::TRUNCATE &&
4410       N1.getOperand(0).getOpcode() == ISD::AND) {
4411     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4412     if (NewOp1.getNode())
4413       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4414   }
4415
4416   // fold operands of srl based on knowledge that the low bits are not
4417   // demanded.
4418   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4419     return SDValue(N, 0);
4420
4421   if (N1C) {
4422     SDValue NewSRL = visitShiftByConstant(N, N1C);
4423     if (NewSRL.getNode())
4424       return NewSRL;
4425   }
4426
4427   // Attempt to convert a srl of a load into a narrower zero-extending load.
4428   SDValue NarrowLoad = ReduceLoadWidth(N);
4429   if (NarrowLoad.getNode())
4430     return NarrowLoad;
4431
4432   // Here is a common situation. We want to optimize:
4433   //
4434   //   %a = ...
4435   //   %b = and i32 %a, 2
4436   //   %c = srl i32 %b, 1
4437   //   brcond i32 %c ...
4438   //
4439   // into
4440   //
4441   //   %a = ...
4442   //   %b = and %a, 2
4443   //   %c = setcc eq %b, 0
4444   //   brcond %c ...
4445   //
4446   // However when after the source operand of SRL is optimized into AND, the SRL
4447   // itself may not be optimized further. Look for it and add the BRCOND into
4448   // the worklist.
4449   if (N->hasOneUse()) {
4450     SDNode *Use = *N->use_begin();
4451     if (Use->getOpcode() == ISD::BRCOND)
4452       AddToWorkList(Use);
4453     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4454       // Also look pass the truncate.
4455       Use = *Use->use_begin();
4456       if (Use->getOpcode() == ISD::BRCOND)
4457         AddToWorkList(Use);
4458     }
4459   }
4460
4461   return SDValue();
4462 }
4463
4464 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4465   SDValue N0 = N->getOperand(0);
4466   EVT VT = N->getValueType(0);
4467
4468   // fold (ctlz c1) -> c2
4469   if (isa<ConstantSDNode>(N0))
4470     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4471   return SDValue();
4472 }
4473
4474 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4475   SDValue N0 = N->getOperand(0);
4476   EVT VT = N->getValueType(0);
4477
4478   // fold (ctlz_zero_undef c1) -> c2
4479   if (isa<ConstantSDNode>(N0))
4480     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4481   return SDValue();
4482 }
4483
4484 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4485   SDValue N0 = N->getOperand(0);
4486   EVT VT = N->getValueType(0);
4487
4488   // fold (cttz c1) -> c2
4489   if (isa<ConstantSDNode>(N0))
4490     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4491   return SDValue();
4492 }
4493
4494 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4495   SDValue N0 = N->getOperand(0);
4496   EVT VT = N->getValueType(0);
4497
4498   // fold (cttz_zero_undef c1) -> c2
4499   if (isa<ConstantSDNode>(N0))
4500     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4501   return SDValue();
4502 }
4503
4504 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4505   SDValue N0 = N->getOperand(0);
4506   EVT VT = N->getValueType(0);
4507
4508   // fold (ctpop c1) -> c2
4509   if (isa<ConstantSDNode>(N0))
4510     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4511   return SDValue();
4512 }
4513
4514 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4515   SDValue N0 = N->getOperand(0);
4516   SDValue N1 = N->getOperand(1);
4517   SDValue N2 = N->getOperand(2);
4518   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4519   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4520   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4521   EVT VT = N->getValueType(0);
4522   EVT VT0 = N0.getValueType();
4523
4524   // fold (select C, X, X) -> X
4525   if (N1 == N2)
4526     return N1;
4527   // fold (select true, X, Y) -> X
4528   if (N0C && !N0C->isNullValue())
4529     return N1;
4530   // fold (select false, X, Y) -> Y
4531   if (N0C && N0C->isNullValue())
4532     return N2;
4533   // fold (select C, 1, X) -> (or C, X)
4534   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4535     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4536   // fold (select C, 0, 1) -> (xor C, 1)
4537   if (VT.isInteger() &&
4538       (VT0 == MVT::i1 ||
4539        (VT0.isInteger() &&
4540         TLI.getBooleanContents(false) ==
4541         TargetLowering::ZeroOrOneBooleanContent)) &&
4542       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4543     SDValue XORNode;
4544     if (VT == VT0)
4545       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4546                          N0, DAG.getConstant(1, VT0));
4547     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4548                           N0, DAG.getConstant(1, VT0));
4549     AddToWorkList(XORNode.getNode());
4550     if (VT.bitsGT(VT0))
4551       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4552     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4553   }
4554   // fold (select C, 0, X) -> (and (not C), X)
4555   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4556     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4557     AddToWorkList(NOTNode.getNode());
4558     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4559   }
4560   // fold (select C, X, 1) -> (or (not C), X)
4561   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4562     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4563     AddToWorkList(NOTNode.getNode());
4564     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4565   }
4566   // fold (select C, X, 0) -> (and C, X)
4567   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4568     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4569   // fold (select X, X, Y) -> (or X, Y)
4570   // fold (select X, 1, Y) -> (or X, Y)
4571   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4572     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4573   // fold (select X, Y, X) -> (and X, Y)
4574   // fold (select X, Y, 0) -> (and X, Y)
4575   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4576     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4577
4578   // If we can fold this based on the true/false value, do so.
4579   if (SimplifySelectOps(N, N1, N2))
4580     return SDValue(N, 0);  // Don't revisit N.
4581
4582   // fold selects based on a setcc into other things, such as min/max/abs
4583   if (N0.getOpcode() == ISD::SETCC) {
4584     // FIXME:
4585     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4586     // having to say they don't support SELECT_CC on every type the DAG knows
4587     // about, since there is no way to mark an opcode illegal at all value types
4588     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4589         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4590       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4591                          N0.getOperand(0), N0.getOperand(1),
4592                          N1, N2, N0.getOperand(2));
4593     return SimplifySelect(SDLoc(N), N0, N1, N2);
4594   }
4595
4596   return SDValue();
4597 }
4598
4599 static
4600 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4601   SDLoc DL(N);
4602   EVT LoVT, HiVT;
4603   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4604
4605   // Split the inputs.
4606   SDValue Lo, Hi, LL, LH, RL, RH;
4607   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4608   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4609
4610   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4611   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4612
4613   return std::make_pair(Lo, Hi);
4614 }
4615
4616 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4617   SDValue N0 = N->getOperand(0);
4618   SDValue N1 = N->getOperand(1);
4619   SDValue N2 = N->getOperand(2);
4620   SDLoc DL(N);
4621
4622   // Canonicalize integer abs.
4623   // vselect (setg[te] X,  0),  X, -X ->
4624   // vselect (setgt    X, -1),  X, -X ->
4625   // vselect (setl[te] X,  0), -X,  X ->
4626   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4627   if (N0.getOpcode() == ISD::SETCC) {
4628     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4629     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4630     bool isAbs = false;
4631     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4632
4633     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4634          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4635         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4636       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4637     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4638              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4639       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4640
4641     if (isAbs) {
4642       EVT VT = LHS.getValueType();
4643       SDValue Shift = DAG.getNode(
4644           ISD::SRA, DL, VT, LHS,
4645           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4646       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4647       AddToWorkList(Shift.getNode());
4648       AddToWorkList(Add.getNode());
4649       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4650     }
4651   }
4652
4653   // If the VSELECT result requires splitting and the mask is provided by a
4654   // SETCC, then split both nodes and its operands before legalization. This
4655   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4656   // and enables future optimizations (e.g. min/max pattern matching on X86).
4657   if (N0.getOpcode() == ISD::SETCC) {
4658     EVT VT = N->getValueType(0);
4659
4660     // Check if any splitting is required.
4661     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4662         TargetLowering::TypeSplitVector)
4663       return SDValue();
4664
4665     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4666     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4667     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4668     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4669
4670     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4671     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4672
4673     // Add the new VSELECT nodes to the work list in case they need to be split
4674     // again.
4675     AddToWorkList(Lo.getNode());
4676     AddToWorkList(Hi.getNode());
4677
4678     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4679   }
4680
4681   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4682   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4683     return N1;
4684   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4685   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4686     return N2;
4687
4688   return SDValue();
4689 }
4690
4691 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4692   SDValue N0 = N->getOperand(0);
4693   SDValue N1 = N->getOperand(1);
4694   SDValue N2 = N->getOperand(2);
4695   SDValue N3 = N->getOperand(3);
4696   SDValue N4 = N->getOperand(4);
4697   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4698
4699   // fold select_cc lhs, rhs, x, x, cc -> x
4700   if (N2 == N3)
4701     return N2;
4702
4703   // Determine if the condition we're dealing with is constant
4704   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4705                               N0, N1, CC, SDLoc(N), false);
4706   if (SCC.getNode()) {
4707     AddToWorkList(SCC.getNode());
4708
4709     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4710       if (!SCCC->isNullValue())
4711         return N2;    // cond always true -> true val
4712       else
4713         return N3;    // cond always false -> false val
4714     }
4715
4716     // Fold to a simpler select_cc
4717     if (SCC.getOpcode() == ISD::SETCC)
4718       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4719                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4720                          SCC.getOperand(2));
4721   }
4722
4723   // If we can fold this based on the true/false value, do so.
4724   if (SimplifySelectOps(N, N2, N3))
4725     return SDValue(N, 0);  // Don't revisit N.
4726
4727   // fold select_cc into other things, such as min/max/abs
4728   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4729 }
4730
4731 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4732   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4733                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4734                        SDLoc(N));
4735 }
4736
4737 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4738 // dag node into a ConstantSDNode or a build_vector of constants.
4739 // This function is called by the DAGCombiner when visiting sext/zext/aext
4740 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4741 // Vector extends are not folded if operations are legal; this is to
4742 // avoid introducing illegal build_vector dag nodes.
4743 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4744                                          SelectionDAG &DAG, bool LegalTypes,
4745                                          bool LegalOperations) {
4746   unsigned Opcode = N->getOpcode();
4747   SDValue N0 = N->getOperand(0);
4748   EVT VT = N->getValueType(0);
4749
4750   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4751          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4752
4753   // fold (sext c1) -> c1
4754   // fold (zext c1) -> c1
4755   // fold (aext c1) -> c1
4756   if (isa<ConstantSDNode>(N0))
4757     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4758
4759   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4760   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4761   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4762   EVT SVT = VT.getScalarType();
4763   if (!(VT.isVector() &&
4764       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4765       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4766     return nullptr;
4767   
4768   // We can fold this node into a build_vector.
4769   unsigned VTBits = SVT.getSizeInBits();
4770   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4771   unsigned ShAmt = VTBits - EVTBits;
4772   SmallVector<SDValue, 8> Elts;
4773   unsigned NumElts = N0->getNumOperands();
4774   SDLoc DL(N);
4775
4776   for (unsigned i=0; i != NumElts; ++i) {
4777     SDValue Op = N0->getOperand(i);
4778     if (Op->getOpcode() == ISD::UNDEF) {
4779       Elts.push_back(DAG.getUNDEF(SVT));
4780       continue;
4781     }
4782
4783     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4784     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4785     if (Opcode == ISD::SIGN_EXTEND)
4786       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4787                                      SVT));
4788     else
4789       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4790                                      SVT));
4791   }
4792
4793   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4794 }
4795
4796 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4797 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4798 // transformation. Returns true if extension are possible and the above
4799 // mentioned transformation is profitable.
4800 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4801                                     unsigned ExtOpc,
4802                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4803                                     const TargetLowering &TLI) {
4804   bool HasCopyToRegUses = false;
4805   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4806   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4807                             UE = N0.getNode()->use_end();
4808        UI != UE; ++UI) {
4809     SDNode *User = *UI;
4810     if (User == N)
4811       continue;
4812     if (UI.getUse().getResNo() != N0.getResNo())
4813       continue;
4814     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4815     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4816       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4817       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4818         // Sign bits will be lost after a zext.
4819         return false;
4820       bool Add = false;
4821       for (unsigned i = 0; i != 2; ++i) {
4822         SDValue UseOp = User->getOperand(i);
4823         if (UseOp == N0)
4824           continue;
4825         if (!isa<ConstantSDNode>(UseOp))
4826           return false;
4827         Add = true;
4828       }
4829       if (Add)
4830         ExtendNodes.push_back(User);
4831       continue;
4832     }
4833     // If truncates aren't free and there are users we can't
4834     // extend, it isn't worthwhile.
4835     if (!isTruncFree)
4836       return false;
4837     // Remember if this value is live-out.
4838     if (User->getOpcode() == ISD::CopyToReg)
4839       HasCopyToRegUses = true;
4840   }
4841
4842   if (HasCopyToRegUses) {
4843     bool BothLiveOut = false;
4844     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4845          UI != UE; ++UI) {
4846       SDUse &Use = UI.getUse();
4847       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4848         BothLiveOut = true;
4849         break;
4850       }
4851     }
4852     if (BothLiveOut)
4853       // Both unextended and extended values are live out. There had better be
4854       // a good reason for the transformation.
4855       return ExtendNodes.size();
4856   }
4857   return true;
4858 }
4859
4860 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4861                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4862                                   ISD::NodeType ExtType) {
4863   // Extend SetCC uses if necessary.
4864   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4865     SDNode *SetCC = SetCCs[i];
4866     SmallVector<SDValue, 4> Ops;
4867
4868     for (unsigned j = 0; j != 2; ++j) {
4869       SDValue SOp = SetCC->getOperand(j);
4870       if (SOp == Trunc)
4871         Ops.push_back(ExtLoad);
4872       else
4873         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4874     }
4875
4876     Ops.push_back(SetCC->getOperand(2));
4877     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4878                                  &Ops[0], Ops.size()));
4879   }
4880 }
4881
4882 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4883   SDValue N0 = N->getOperand(0);
4884   EVT VT = N->getValueType(0);
4885
4886   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4887                                               LegalOperations))
4888     return SDValue(Res, 0);
4889
4890   // fold (sext (sext x)) -> (sext x)
4891   // fold (sext (aext x)) -> (sext x)
4892   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4893     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4894                        N0.getOperand(0));
4895
4896   if (N0.getOpcode() == ISD::TRUNCATE) {
4897     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4898     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4899     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4900     if (NarrowLoad.getNode()) {
4901       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4902       if (NarrowLoad.getNode() != N0.getNode()) {
4903         CombineTo(N0.getNode(), NarrowLoad);
4904         // CombineTo deleted the truncate, if needed, but not what's under it.
4905         AddToWorkList(oye);
4906       }
4907       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4908     }
4909
4910     // See if the value being truncated is already sign extended.  If so, just
4911     // eliminate the trunc/sext pair.
4912     SDValue Op = N0.getOperand(0);
4913     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4914     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4915     unsigned DestBits = VT.getScalarType().getSizeInBits();
4916     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4917
4918     if (OpBits == DestBits) {
4919       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4920       // bits, it is already ready.
4921       if (NumSignBits > DestBits-MidBits)
4922         return Op;
4923     } else if (OpBits < DestBits) {
4924       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4925       // bits, just sext from i32.
4926       if (NumSignBits > OpBits-MidBits)
4927         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4928     } else {
4929       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4930       // bits, just truncate to i32.
4931       if (NumSignBits > OpBits-MidBits)
4932         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4933     }
4934
4935     // fold (sext (truncate x)) -> (sextinreg x).
4936     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4937                                                  N0.getValueType())) {
4938       if (OpBits < DestBits)
4939         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4940       else if (OpBits > DestBits)
4941         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4942       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4943                          DAG.getValueType(N0.getValueType()));
4944     }
4945   }
4946
4947   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4948   // None of the supported targets knows how to perform load and sign extend
4949   // on vectors in one instruction.  We only perform this transformation on
4950   // scalars.
4951   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4952       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4953       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4954        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4955     bool DoXform = true;
4956     SmallVector<SDNode*, 4> SetCCs;
4957     if (!N0.hasOneUse())
4958       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4959     if (DoXform) {
4960       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4961       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4962                                        LN0->getChain(),
4963                                        LN0->getBasePtr(), N0.getValueType(),
4964                                        LN0->getMemOperand());
4965       CombineTo(N, ExtLoad);
4966       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4967                                   N0.getValueType(), ExtLoad);
4968       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4969       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4970                       ISD::SIGN_EXTEND);
4971       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4972     }
4973   }
4974
4975   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4976   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4977   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4978       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4979     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4980     EVT MemVT = LN0->getMemoryVT();
4981     if ((!LegalOperations && !LN0->isVolatile()) ||
4982         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4983       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4984                                        LN0->getChain(),
4985                                        LN0->getBasePtr(), MemVT,
4986                                        LN0->getMemOperand());
4987       CombineTo(N, ExtLoad);
4988       CombineTo(N0.getNode(),
4989                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4990                             N0.getValueType(), ExtLoad),
4991                 ExtLoad.getValue(1));
4992       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4993     }
4994   }
4995
4996   // fold (sext (and/or/xor (load x), cst)) ->
4997   //      (and/or/xor (sextload x), (sext cst))
4998   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4999        N0.getOpcode() == ISD::XOR) &&
5000       isa<LoadSDNode>(N0.getOperand(0)) &&
5001       N0.getOperand(1).getOpcode() == ISD::Constant &&
5002       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5003       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5004     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5005     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5006       bool DoXform = true;
5007       SmallVector<SDNode*, 4> SetCCs;
5008       if (!N0.hasOneUse())
5009         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5010                                           SetCCs, TLI);
5011       if (DoXform) {
5012         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5013                                          LN0->getChain(), LN0->getBasePtr(),
5014                                          LN0->getMemoryVT(),
5015                                          LN0->getMemOperand());
5016         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5017         Mask = Mask.sext(VT.getSizeInBits());
5018         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5019                                   ExtLoad, DAG.getConstant(Mask, VT));
5020         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5021                                     SDLoc(N0.getOperand(0)),
5022                                     N0.getOperand(0).getValueType(), ExtLoad);
5023         CombineTo(N, And);
5024         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5025         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5026                         ISD::SIGN_EXTEND);
5027         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5028       }
5029     }
5030   }
5031
5032   if (N0.getOpcode() == ISD::SETCC) {
5033     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5034     // Only do this before legalize for now.
5035     if (VT.isVector() && !LegalOperations &&
5036         TLI.getBooleanContents(true) ==
5037           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5038       EVT N0VT = N0.getOperand(0).getValueType();
5039       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5040       // of the same size as the compared operands. Only optimize sext(setcc())
5041       // if this is the case.
5042       EVT SVT = getSetCCResultType(N0VT);
5043
5044       // We know that the # elements of the results is the same as the
5045       // # elements of the compare (and the # elements of the compare result
5046       // for that matter).  Check to see that they are the same size.  If so,
5047       // we know that the element size of the sext'd result matches the
5048       // element size of the compare operands.
5049       if (VT.getSizeInBits() == SVT.getSizeInBits())
5050         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5051                              N0.getOperand(1),
5052                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5053
5054       // If the desired elements are smaller or larger than the source
5055       // elements we can use a matching integer vector type and then
5056       // truncate/sign extend
5057       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5058       if (SVT == MatchingVectorType) {
5059         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5060                                N0.getOperand(0), N0.getOperand(1),
5061                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5062         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5063       }
5064     }
5065
5066     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5067     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5068     SDValue NegOne =
5069       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5070     SDValue SCC =
5071       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5072                        NegOne, DAG.getConstant(0, VT),
5073                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5074     if (SCC.getNode()) return SCC;
5075
5076     if (!VT.isVector()) {
5077       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5078       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5079         SDLoc DL(N);
5080         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5081         SDValue SetCC = DAG.getSetCC(DL,
5082                                      SetCCVT,
5083                                      N0.getOperand(0), N0.getOperand(1), CC);
5084         EVT SelectVT = getSetCCResultType(VT);
5085         return DAG.getSelect(DL, VT,
5086                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5087                              NegOne, DAG.getConstant(0, VT));
5088
5089       }
5090     }
5091   }
5092
5093   // fold (sext x) -> (zext x) if the sign bit is known zero.
5094   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5095       DAG.SignBitIsZero(N0))
5096     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5097
5098   return SDValue();
5099 }
5100
5101 // isTruncateOf - If N is a truncate of some other value, return true, record
5102 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5103 // This function computes KnownZero to avoid a duplicated call to
5104 // ComputeMaskedBits in the caller.
5105 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5106                          APInt &KnownZero) {
5107   APInt KnownOne;
5108   if (N->getOpcode() == ISD::TRUNCATE) {
5109     Op = N->getOperand(0);
5110     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5111     return true;
5112   }
5113
5114   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5115       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5116     return false;
5117
5118   SDValue Op0 = N->getOperand(0);
5119   SDValue Op1 = N->getOperand(1);
5120   assert(Op0.getValueType() == Op1.getValueType());
5121
5122   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5123   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5124   if (COp0 && COp0->isNullValue())
5125     Op = Op1;
5126   else if (COp1 && COp1->isNullValue())
5127     Op = Op0;
5128   else
5129     return false;
5130
5131   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5132
5133   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5134     return false;
5135
5136   return true;
5137 }
5138
5139 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5140   SDValue N0 = N->getOperand(0);
5141   EVT VT = N->getValueType(0);
5142
5143   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5144                                               LegalOperations))
5145     return SDValue(Res, 0);
5146
5147   // fold (zext (zext x)) -> (zext x)
5148   // fold (zext (aext x)) -> (zext x)
5149   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5150     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5151                        N0.getOperand(0));
5152
5153   // fold (zext (truncate x)) -> (zext x) or
5154   //      (zext (truncate x)) -> (truncate x)
5155   // This is valid when the truncated bits of x are already zero.
5156   // FIXME: We should extend this to work for vectors too.
5157   SDValue Op;
5158   APInt KnownZero;
5159   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5160     APInt TruncatedBits =
5161       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5162       APInt(Op.getValueSizeInBits(), 0) :
5163       APInt::getBitsSet(Op.getValueSizeInBits(),
5164                         N0.getValueSizeInBits(),
5165                         std::min(Op.getValueSizeInBits(),
5166                                  VT.getSizeInBits()));
5167     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5168       if (VT.bitsGT(Op.getValueType()))
5169         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5170       if (VT.bitsLT(Op.getValueType()))
5171         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5172
5173       return Op;
5174     }
5175   }
5176
5177   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5178   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5179   if (N0.getOpcode() == ISD::TRUNCATE) {
5180     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5181     if (NarrowLoad.getNode()) {
5182       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5183       if (NarrowLoad.getNode() != N0.getNode()) {
5184         CombineTo(N0.getNode(), NarrowLoad);
5185         // CombineTo deleted the truncate, if needed, but not what's under it.
5186         AddToWorkList(oye);
5187       }
5188       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5189     }
5190   }
5191
5192   // fold (zext (truncate x)) -> (and x, mask)
5193   if (N0.getOpcode() == ISD::TRUNCATE &&
5194       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5195
5196     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5197     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5198     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5199     if (NarrowLoad.getNode()) {
5200       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5201       if (NarrowLoad.getNode() != N0.getNode()) {
5202         CombineTo(N0.getNode(), NarrowLoad);
5203         // CombineTo deleted the truncate, if needed, but not what's under it.
5204         AddToWorkList(oye);
5205       }
5206       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5207     }
5208
5209     SDValue Op = N0.getOperand(0);
5210     if (Op.getValueType().bitsLT(VT)) {
5211       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5212       AddToWorkList(Op.getNode());
5213     } else if (Op.getValueType().bitsGT(VT)) {
5214       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5215       AddToWorkList(Op.getNode());
5216     }
5217     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5218                                   N0.getValueType().getScalarType());
5219   }
5220
5221   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5222   // if either of the casts is not free.
5223   if (N0.getOpcode() == ISD::AND &&
5224       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5225       N0.getOperand(1).getOpcode() == ISD::Constant &&
5226       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5227                            N0.getValueType()) ||
5228        !TLI.isZExtFree(N0.getValueType(), VT))) {
5229     SDValue X = N0.getOperand(0).getOperand(0);
5230     if (X.getValueType().bitsLT(VT)) {
5231       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5232     } else if (X.getValueType().bitsGT(VT)) {
5233       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5234     }
5235     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5236     Mask = Mask.zext(VT.getSizeInBits());
5237     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5238                        X, DAG.getConstant(Mask, VT));
5239   }
5240
5241   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5242   // None of the supported targets knows how to perform load and vector_zext
5243   // on vectors in one instruction.  We only perform this transformation on
5244   // scalars.
5245   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5246       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5247       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5248        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5249     bool DoXform = true;
5250     SmallVector<SDNode*, 4> SetCCs;
5251     if (!N0.hasOneUse())
5252       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5253     if (DoXform) {
5254       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5255       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5256                                        LN0->getChain(),
5257                                        LN0->getBasePtr(), N0.getValueType(),
5258                                        LN0->getMemOperand());
5259       CombineTo(N, ExtLoad);
5260       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5261                                   N0.getValueType(), ExtLoad);
5262       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5263
5264       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5265                       ISD::ZERO_EXTEND);
5266       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5267     }
5268   }
5269
5270   // fold (zext (and/or/xor (load x), cst)) ->
5271   //      (and/or/xor (zextload x), (zext cst))
5272   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5273        N0.getOpcode() == ISD::XOR) &&
5274       isa<LoadSDNode>(N0.getOperand(0)) &&
5275       N0.getOperand(1).getOpcode() == ISD::Constant &&
5276       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5277       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5278     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5279     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5280       bool DoXform = true;
5281       SmallVector<SDNode*, 4> SetCCs;
5282       if (!N0.hasOneUse())
5283         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5284                                           SetCCs, TLI);
5285       if (DoXform) {
5286         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5287                                          LN0->getChain(), LN0->getBasePtr(),
5288                                          LN0->getMemoryVT(),
5289                                          LN0->getMemOperand());
5290         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5291         Mask = Mask.zext(VT.getSizeInBits());
5292         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5293                                   ExtLoad, DAG.getConstant(Mask, VT));
5294         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5295                                     SDLoc(N0.getOperand(0)),
5296                                     N0.getOperand(0).getValueType(), ExtLoad);
5297         CombineTo(N, And);
5298         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5299         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5300                         ISD::ZERO_EXTEND);
5301         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5302       }
5303     }
5304   }
5305
5306   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5307   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5308   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5309       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5310     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5311     EVT MemVT = LN0->getMemoryVT();
5312     if ((!LegalOperations && !LN0->isVolatile()) ||
5313         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5314       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5315                                        LN0->getChain(),
5316                                        LN0->getBasePtr(), MemVT,
5317                                        LN0->getMemOperand());
5318       CombineTo(N, ExtLoad);
5319       CombineTo(N0.getNode(),
5320                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5321                             ExtLoad),
5322                 ExtLoad.getValue(1));
5323       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5324     }
5325   }
5326
5327   if (N0.getOpcode() == ISD::SETCC) {
5328     if (!LegalOperations && VT.isVector() &&
5329         N0.getValueType().getVectorElementType() == MVT::i1) {
5330       EVT N0VT = N0.getOperand(0).getValueType();
5331       if (getSetCCResultType(N0VT) == N0.getValueType())
5332         return SDValue();
5333
5334       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5335       // Only do this before legalize for now.
5336       EVT EltVT = VT.getVectorElementType();
5337       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5338                                     DAG.getConstant(1, EltVT));
5339       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5340         // We know that the # elements of the results is the same as the
5341         // # elements of the compare (and the # elements of the compare result
5342         // for that matter).  Check to see that they are the same size.  If so,
5343         // we know that the element size of the sext'd result matches the
5344         // element size of the compare operands.
5345         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5346                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5347                                          N0.getOperand(1),
5348                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5349                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5350                                        &OneOps[0], OneOps.size()));
5351
5352       // If the desired elements are smaller or larger than the source
5353       // elements we can use a matching integer vector type and then
5354       // truncate/sign extend
5355       EVT MatchingElementType =
5356         EVT::getIntegerVT(*DAG.getContext(),
5357                           N0VT.getScalarType().getSizeInBits());
5358       EVT MatchingVectorType =
5359         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5360                          N0VT.getVectorNumElements());
5361       SDValue VsetCC =
5362         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5363                       N0.getOperand(1),
5364                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5365       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5366                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5367                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5368                                      &OneOps[0], OneOps.size()));
5369     }
5370
5371     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5372     SDValue SCC =
5373       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5374                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5375                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5376     if (SCC.getNode()) return SCC;
5377   }
5378
5379   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5380   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5381       isa<ConstantSDNode>(N0.getOperand(1)) &&
5382       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5383       N0.hasOneUse()) {
5384     SDValue ShAmt = N0.getOperand(1);
5385     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5386     if (N0.getOpcode() == ISD::SHL) {
5387       SDValue InnerZExt = N0.getOperand(0);
5388       // If the original shl may be shifting out bits, do not perform this
5389       // transformation.
5390       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5391         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5392       if (ShAmtVal > KnownZeroBits)
5393         return SDValue();
5394     }
5395
5396     SDLoc DL(N);
5397
5398     // Ensure that the shift amount is wide enough for the shifted value.
5399     if (VT.getSizeInBits() >= 256)
5400       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5401
5402     return DAG.getNode(N0.getOpcode(), DL, VT,
5403                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5404                        ShAmt);
5405   }
5406
5407   return SDValue();
5408 }
5409
5410 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5411   SDValue N0 = N->getOperand(0);
5412   EVT VT = N->getValueType(0);
5413
5414   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5415                                               LegalOperations))
5416     return SDValue(Res, 0);
5417
5418   // fold (aext (aext x)) -> (aext x)
5419   // fold (aext (zext x)) -> (zext x)
5420   // fold (aext (sext x)) -> (sext x)
5421   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5422       N0.getOpcode() == ISD::ZERO_EXTEND ||
5423       N0.getOpcode() == ISD::SIGN_EXTEND)
5424     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5425
5426   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5427   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5428   if (N0.getOpcode() == ISD::TRUNCATE) {
5429     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5430     if (NarrowLoad.getNode()) {
5431       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5432       if (NarrowLoad.getNode() != N0.getNode()) {
5433         CombineTo(N0.getNode(), NarrowLoad);
5434         // CombineTo deleted the truncate, if needed, but not what's under it.
5435         AddToWorkList(oye);
5436       }
5437       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5438     }
5439   }
5440
5441   // fold (aext (truncate x))
5442   if (N0.getOpcode() == ISD::TRUNCATE) {
5443     SDValue TruncOp = N0.getOperand(0);
5444     if (TruncOp.getValueType() == VT)
5445       return TruncOp; // x iff x size == zext size.
5446     if (TruncOp.getValueType().bitsGT(VT))
5447       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5448     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5449   }
5450
5451   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5452   // if the trunc is not free.
5453   if (N0.getOpcode() == ISD::AND &&
5454       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5455       N0.getOperand(1).getOpcode() == ISD::Constant &&
5456       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5457                           N0.getValueType())) {
5458     SDValue X = N0.getOperand(0).getOperand(0);
5459     if (X.getValueType().bitsLT(VT)) {
5460       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5461     } else if (X.getValueType().bitsGT(VT)) {
5462       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5463     }
5464     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5465     Mask = Mask.zext(VT.getSizeInBits());
5466     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5467                        X, DAG.getConstant(Mask, VT));
5468   }
5469
5470   // fold (aext (load x)) -> (aext (truncate (extload x)))
5471   // None of the supported targets knows how to perform load and any_ext
5472   // on vectors in one instruction.  We only perform this transformation on
5473   // scalars.
5474   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5475       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5476       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5477        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5478     bool DoXform = true;
5479     SmallVector<SDNode*, 4> SetCCs;
5480     if (!N0.hasOneUse())
5481       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5482     if (DoXform) {
5483       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5484       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5485                                        LN0->getChain(),
5486                                        LN0->getBasePtr(), N0.getValueType(),
5487                                        LN0->getMemOperand());
5488       CombineTo(N, ExtLoad);
5489       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5490                                   N0.getValueType(), ExtLoad);
5491       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5492       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5493                       ISD::ANY_EXTEND);
5494       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5495     }
5496   }
5497
5498   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5499   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5500   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5501   if (N0.getOpcode() == ISD::LOAD &&
5502       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5503       N0.hasOneUse()) {
5504     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5505     ISD::LoadExtType ExtType = LN0->getExtensionType();
5506     EVT MemVT = LN0->getMemoryVT();
5507     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5508       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5509                                        VT, LN0->getChain(), LN0->getBasePtr(),
5510                                        MemVT, LN0->getMemOperand());
5511       CombineTo(N, ExtLoad);
5512       CombineTo(N0.getNode(),
5513                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5514                             N0.getValueType(), ExtLoad),
5515                 ExtLoad.getValue(1));
5516       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5517     }
5518   }
5519
5520   if (N0.getOpcode() == ISD::SETCC) {
5521     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5522     // Only do this before legalize for now.
5523     if (VT.isVector() && !LegalOperations) {
5524       EVT N0VT = N0.getOperand(0).getValueType();
5525         // We know that the # elements of the results is the same as the
5526         // # elements of the compare (and the # elements of the compare result
5527         // for that matter).  Check to see that they are the same size.  If so,
5528         // we know that the element size of the sext'd result matches the
5529         // element size of the compare operands.
5530       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5531         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5532                              N0.getOperand(1),
5533                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5534       // If the desired elements are smaller or larger than the source
5535       // elements we can use a matching integer vector type and then
5536       // truncate/sign extend
5537       else {
5538         EVT MatchingElementType =
5539           EVT::getIntegerVT(*DAG.getContext(),
5540                             N0VT.getScalarType().getSizeInBits());
5541         EVT MatchingVectorType =
5542           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5543                            N0VT.getVectorNumElements());
5544         SDValue VsetCC =
5545           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5546                         N0.getOperand(1),
5547                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5548         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5549       }
5550     }
5551
5552     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5553     SDValue SCC =
5554       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5555                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5556                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5557     if (SCC.getNode())
5558       return SCC;
5559   }
5560
5561   return SDValue();
5562 }
5563
5564 /// GetDemandedBits - See if the specified operand can be simplified with the
5565 /// knowledge that only the bits specified by Mask are used.  If so, return the
5566 /// simpler operand, otherwise return a null SDValue.
5567 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5568   switch (V.getOpcode()) {
5569   default: break;
5570   case ISD::Constant: {
5571     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5572     assert(CV && "Const value should be ConstSDNode.");
5573     const APInt &CVal = CV->getAPIntValue();
5574     APInt NewVal = CVal & Mask;
5575     if (NewVal != CVal)
5576       return DAG.getConstant(NewVal, V.getValueType());
5577     break;
5578   }
5579   case ISD::OR:
5580   case ISD::XOR:
5581     // If the LHS or RHS don't contribute bits to the or, drop them.
5582     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5583       return V.getOperand(1);
5584     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5585       return V.getOperand(0);
5586     break;
5587   case ISD::SRL:
5588     // Only look at single-use SRLs.
5589     if (!V.getNode()->hasOneUse())
5590       break;
5591     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5592       // See if we can recursively simplify the LHS.
5593       unsigned Amt = RHSC->getZExtValue();
5594
5595       // Watch out for shift count overflow though.
5596       if (Amt >= Mask.getBitWidth()) break;
5597       APInt NewMask = Mask << Amt;
5598       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5599       if (SimplifyLHS.getNode())
5600         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5601                            SimplifyLHS, V.getOperand(1));
5602     }
5603   }
5604   return SDValue();
5605 }
5606
5607 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5608 /// bits and then truncated to a narrower type and where N is a multiple
5609 /// of number of bits of the narrower type, transform it to a narrower load
5610 /// from address + N / num of bits of new type. If the result is to be
5611 /// extended, also fold the extension to form a extending load.
5612 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5613   unsigned Opc = N->getOpcode();
5614
5615   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5616   SDValue N0 = N->getOperand(0);
5617   EVT VT = N->getValueType(0);
5618   EVT ExtVT = VT;
5619
5620   // This transformation isn't valid for vector loads.
5621   if (VT.isVector())
5622     return SDValue();
5623
5624   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5625   // extended to VT.
5626   if (Opc == ISD::SIGN_EXTEND_INREG) {
5627     ExtType = ISD::SEXTLOAD;
5628     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5629   } else if (Opc == ISD::SRL) {
5630     // Another special-case: SRL is basically zero-extending a narrower value.
5631     ExtType = ISD::ZEXTLOAD;
5632     N0 = SDValue(N, 0);
5633     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5634     if (!N01) return SDValue();
5635     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5636                               VT.getSizeInBits() - N01->getZExtValue());
5637   }
5638   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5639     return SDValue();
5640
5641   unsigned EVTBits = ExtVT.getSizeInBits();
5642
5643   // Do not generate loads of non-round integer types since these can
5644   // be expensive (and would be wrong if the type is not byte sized).
5645   if (!ExtVT.isRound())
5646     return SDValue();
5647
5648   unsigned ShAmt = 0;
5649   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5650     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5651       ShAmt = N01->getZExtValue();
5652       // Is the shift amount a multiple of size of VT?
5653       if ((ShAmt & (EVTBits-1)) == 0) {
5654         N0 = N0.getOperand(0);
5655         // Is the load width a multiple of size of VT?
5656         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5657           return SDValue();
5658       }
5659
5660       // At this point, we must have a load or else we can't do the transform.
5661       if (!isa<LoadSDNode>(N0)) return SDValue();
5662
5663       // Because a SRL must be assumed to *need* to zero-extend the high bits
5664       // (as opposed to anyext the high bits), we can't combine the zextload
5665       // lowering of SRL and an sextload.
5666       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5667         return SDValue();
5668
5669       // If the shift amount is larger than the input type then we're not
5670       // accessing any of the loaded bytes.  If the load was a zextload/extload
5671       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5672       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5673         return SDValue();
5674     }
5675   }
5676
5677   // If the load is shifted left (and the result isn't shifted back right),
5678   // we can fold the truncate through the shift.
5679   unsigned ShLeftAmt = 0;
5680   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5681       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5682     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5683       ShLeftAmt = N01->getZExtValue();
5684       N0 = N0.getOperand(0);
5685     }
5686   }
5687
5688   // If we haven't found a load, we can't narrow it.  Don't transform one with
5689   // multiple uses, this would require adding a new load.
5690   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5691     return SDValue();
5692
5693   // Don't change the width of a volatile load.
5694   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695   if (LN0->isVolatile())
5696     return SDValue();
5697
5698   // Verify that we are actually reducing a load width here.
5699   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5700     return SDValue();
5701
5702   // For the transform to be legal, the load must produce only two values
5703   // (the value loaded and the chain).  Don't transform a pre-increment
5704   // load, for example, which produces an extra value.  Otherwise the
5705   // transformation is not equivalent, and the downstream logic to replace
5706   // uses gets things wrong.
5707   if (LN0->getNumValues() > 2)
5708     return SDValue();
5709
5710   // If the load that we're shrinking is an extload and we're not just
5711   // discarding the extension we can't simply shrink the load. Bail.
5712   // TODO: It would be possible to merge the extensions in some cases.
5713   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5714       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5715     return SDValue();
5716
5717   EVT PtrType = N0.getOperand(1).getValueType();
5718
5719   if (PtrType == MVT::Untyped || PtrType.isExtended())
5720     // It's not possible to generate a constant of extended or untyped type.
5721     return SDValue();
5722
5723   // For big endian targets, we need to adjust the offset to the pointer to
5724   // load the correct bytes.
5725   if (TLI.isBigEndian()) {
5726     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5727     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5728     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5729   }
5730
5731   uint64_t PtrOff = ShAmt / 8;
5732   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5733   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5734                                PtrType, LN0->getBasePtr(),
5735                                DAG.getConstant(PtrOff, PtrType));
5736   AddToWorkList(NewPtr.getNode());
5737
5738   SDValue Load;
5739   if (ExtType == ISD::NON_EXTLOAD)
5740     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5741                         LN0->getPointerInfo().getWithOffset(PtrOff),
5742                         LN0->isVolatile(), LN0->isNonTemporal(),
5743                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5744   else
5745     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5746                           LN0->getPointerInfo().getWithOffset(PtrOff),
5747                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5748                           NewAlign, LN0->getTBAAInfo());
5749
5750   // Replace the old load's chain with the new load's chain.
5751   WorkListRemover DeadNodes(*this);
5752   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5753
5754   // Shift the result left, if we've swallowed a left shift.
5755   SDValue Result = Load;
5756   if (ShLeftAmt != 0) {
5757     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5758     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5759       ShImmTy = VT;
5760     // If the shift amount is as large as the result size (but, presumably,
5761     // no larger than the source) then the useful bits of the result are
5762     // zero; we can't simply return the shortened shift, because the result
5763     // of that operation is undefined.
5764     if (ShLeftAmt >= VT.getSizeInBits())
5765       Result = DAG.getConstant(0, VT);
5766     else
5767       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5768                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5769   }
5770
5771   // Return the new loaded value.
5772   return Result;
5773 }
5774
5775 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5776   SDValue N0 = N->getOperand(0);
5777   SDValue N1 = N->getOperand(1);
5778   EVT VT = N->getValueType(0);
5779   EVT EVT = cast<VTSDNode>(N1)->getVT();
5780   unsigned VTBits = VT.getScalarType().getSizeInBits();
5781   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5782
5783   // fold (sext_in_reg c1) -> c1
5784   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5785     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5786
5787   // If the input is already sign extended, just drop the extension.
5788   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5789     return N0;
5790
5791   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5792   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5793       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5794     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5795                        N0.getOperand(0), N1);
5796
5797   // fold (sext_in_reg (sext x)) -> (sext x)
5798   // fold (sext_in_reg (aext x)) -> (sext x)
5799   // if x is small enough.
5800   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5801     SDValue N00 = N0.getOperand(0);
5802     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5803         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5804       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5805   }
5806
5807   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5808   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5809     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5810
5811   // fold operands of sext_in_reg based on knowledge that the top bits are not
5812   // demanded.
5813   if (SimplifyDemandedBits(SDValue(N, 0)))
5814     return SDValue(N, 0);
5815
5816   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5817   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5818   SDValue NarrowLoad = ReduceLoadWidth(N);
5819   if (NarrowLoad.getNode())
5820     return NarrowLoad;
5821
5822   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5823   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5824   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5825   if (N0.getOpcode() == ISD::SRL) {
5826     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5827       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5828         // We can turn this into an SRA iff the input to the SRL is already sign
5829         // extended enough.
5830         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5831         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5832           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5833                              N0.getOperand(0), N0.getOperand(1));
5834       }
5835   }
5836
5837   // fold (sext_inreg (extload x)) -> (sextload x)
5838   if (ISD::isEXTLoad(N0.getNode()) &&
5839       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5840       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5841       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5842        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5843     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5844     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5845                                      LN0->getChain(),
5846                                      LN0->getBasePtr(), EVT,
5847                                      LN0->getMemOperand());
5848     CombineTo(N, ExtLoad);
5849     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5850     AddToWorkList(ExtLoad.getNode());
5851     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5852   }
5853   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5854   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5855       N0.hasOneUse() &&
5856       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5857       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5858        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5859     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5860     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5861                                      LN0->getChain(),
5862                                      LN0->getBasePtr(), EVT,
5863                                      LN0->getMemOperand());
5864     CombineTo(N, ExtLoad);
5865     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5866     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5867   }
5868
5869   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5870   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5871     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5872                                        N0.getOperand(1), false);
5873     if (BSwap.getNode())
5874       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5875                          BSwap, N1);
5876   }
5877
5878   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5879   // into a build_vector.
5880   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5881     SmallVector<SDValue, 8> Elts;
5882     unsigned NumElts = N0->getNumOperands();
5883     unsigned ShAmt = VTBits - EVTBits;
5884
5885     for (unsigned i = 0; i != NumElts; ++i) {
5886       SDValue Op = N0->getOperand(i);
5887       if (Op->getOpcode() == ISD::UNDEF) {
5888         Elts.push_back(Op);
5889         continue;
5890       }
5891
5892       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5893       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5894       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5895                                      Op.getValueType()));
5896     }
5897
5898     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5899   }
5900
5901   return SDValue();
5902 }
5903
5904 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5905   SDValue N0 = N->getOperand(0);
5906   EVT VT = N->getValueType(0);
5907   bool isLE = TLI.isLittleEndian();
5908
5909   // noop truncate
5910   if (N0.getValueType() == N->getValueType(0))
5911     return N0;
5912   // fold (truncate c1) -> c1
5913   if (isa<ConstantSDNode>(N0))
5914     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5915   // fold (truncate (truncate x)) -> (truncate x)
5916   if (N0.getOpcode() == ISD::TRUNCATE)
5917     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5918   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5919   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5920       N0.getOpcode() == ISD::SIGN_EXTEND ||
5921       N0.getOpcode() == ISD::ANY_EXTEND) {
5922     if (N0.getOperand(0).getValueType().bitsLT(VT))
5923       // if the source is smaller than the dest, we still need an extend
5924       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5925                          N0.getOperand(0));
5926     if (N0.getOperand(0).getValueType().bitsGT(VT))
5927       // if the source is larger than the dest, than we just need the truncate
5928       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5929     // if the source and dest are the same type, we can drop both the extend
5930     // and the truncate.
5931     return N0.getOperand(0);
5932   }
5933
5934   // Fold extract-and-trunc into a narrow extract. For example:
5935   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5936   //   i32 y = TRUNCATE(i64 x)
5937   //        -- becomes --
5938   //   v16i8 b = BITCAST (v2i64 val)
5939   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5940   //
5941   // Note: We only run this optimization after type legalization (which often
5942   // creates this pattern) and before operation legalization after which
5943   // we need to be more careful about the vector instructions that we generate.
5944   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5945       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5946
5947     EVT VecTy = N0.getOperand(0).getValueType();
5948     EVT ExTy = N0.getValueType();
5949     EVT TrTy = N->getValueType(0);
5950
5951     unsigned NumElem = VecTy.getVectorNumElements();
5952     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5953
5954     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5955     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5956
5957     SDValue EltNo = N0->getOperand(1);
5958     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5959       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5960       EVT IndexTy = TLI.getVectorIdxTy();
5961       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5962
5963       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5964                               NVT, N0.getOperand(0));
5965
5966       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5967                          SDLoc(N), TrTy, V,
5968                          DAG.getConstant(Index, IndexTy));
5969     }
5970   }
5971
5972   // Fold a series of buildvector, bitcast, and truncate if possible.
5973   // For example fold
5974   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5975   //   (2xi32 (buildvector x, y)).
5976   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5977       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5978       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5979       N0.getOperand(0).hasOneUse()) {
5980
5981     SDValue BuildVect = N0.getOperand(0);
5982     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5983     EVT TruncVecEltTy = VT.getVectorElementType();
5984
5985     // Check that the element types match.
5986     if (BuildVectEltTy == TruncVecEltTy) {
5987       // Now we only need to compute the offset of the truncated elements.
5988       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5989       unsigned TruncVecNumElts = VT.getVectorNumElements();
5990       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5991
5992       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5993              "Invalid number of elements");
5994
5995       SmallVector<SDValue, 8> Opnds;
5996       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5997         Opnds.push_back(BuildVect.getOperand(i));
5998
5999       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
6000                          Opnds.size());
6001     }
6002   }
6003
6004   // See if we can simplify the input to this truncate through knowledge that
6005   // only the low bits are being used.
6006   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6007   // Currently we only perform this optimization on scalars because vectors
6008   // may have different active low bits.
6009   if (!VT.isVector()) {
6010     SDValue Shorter =
6011       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6012                                                VT.getSizeInBits()));
6013     if (Shorter.getNode())
6014       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6015   }
6016   // fold (truncate (load x)) -> (smaller load x)
6017   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6018   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6019     SDValue Reduced = ReduceLoadWidth(N);
6020     if (Reduced.getNode())
6021       return Reduced;
6022     // Handle the case where the load remains an extending load even
6023     // after truncation.
6024     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6025       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6026       if (!LN0->isVolatile() &&
6027           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6028         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6029                                          VT, LN0->getChain(), LN0->getBasePtr(),
6030                                          LN0->getMemoryVT(),
6031                                          LN0->getMemOperand());
6032         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6033         return NewLoad;
6034       }
6035     }
6036   }
6037   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6038   // where ... are all 'undef'.
6039   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6040     SmallVector<EVT, 8> VTs;
6041     SDValue V;
6042     unsigned Idx = 0;
6043     unsigned NumDefs = 0;
6044
6045     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6046       SDValue X = N0.getOperand(i);
6047       if (X.getOpcode() != ISD::UNDEF) {
6048         V = X;
6049         Idx = i;
6050         NumDefs++;
6051       }
6052       // Stop if more than one members are non-undef.
6053       if (NumDefs > 1)
6054         break;
6055       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6056                                      VT.getVectorElementType(),
6057                                      X.getValueType().getVectorNumElements()));
6058     }
6059
6060     if (NumDefs == 0)
6061       return DAG.getUNDEF(VT);
6062
6063     if (NumDefs == 1) {
6064       assert(V.getNode() && "The single defined operand is empty!");
6065       SmallVector<SDValue, 8> Opnds;
6066       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6067         if (i != Idx) {
6068           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6069           continue;
6070         }
6071         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6072         AddToWorkList(NV.getNode());
6073         Opnds.push_back(NV);
6074       }
6075       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6076                          &Opnds[0], Opnds.size());
6077     }
6078   }
6079
6080   // Simplify the operands using demanded-bits information.
6081   if (!VT.isVector() &&
6082       SimplifyDemandedBits(SDValue(N, 0)))
6083     return SDValue(N, 0);
6084
6085   return SDValue();
6086 }
6087
6088 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6089   SDValue Elt = N->getOperand(i);
6090   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6091     return Elt.getNode();
6092   return Elt.getOperand(Elt.getResNo()).getNode();
6093 }
6094
6095 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6096 /// if load locations are consecutive.
6097 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6098   assert(N->getOpcode() == ISD::BUILD_PAIR);
6099
6100   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6101   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6102   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6103       LD1->getAddressSpace() != LD2->getAddressSpace())
6104     return SDValue();
6105   EVT LD1VT = LD1->getValueType(0);
6106
6107   if (ISD::isNON_EXTLoad(LD2) &&
6108       LD2->hasOneUse() &&
6109       // If both are volatile this would reduce the number of volatile loads.
6110       // If one is volatile it might be ok, but play conservative and bail out.
6111       !LD1->isVolatile() &&
6112       !LD2->isVolatile() &&
6113       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6114     unsigned Align = LD1->getAlignment();
6115     unsigned NewAlign = TLI.getDataLayout()->
6116       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6117
6118     if (NewAlign <= Align &&
6119         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6120       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6121                          LD1->getBasePtr(), LD1->getPointerInfo(),
6122                          false, false, false, Align);
6123   }
6124
6125   return SDValue();
6126 }
6127
6128 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6129   SDValue N0 = N->getOperand(0);
6130   EVT VT = N->getValueType(0);
6131
6132   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6133   // Only do this before legalize, since afterward the target may be depending
6134   // on the bitconvert.
6135   // First check to see if this is all constant.
6136   if (!LegalTypes &&
6137       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6138       VT.isVector()) {
6139     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6140
6141     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6142     assert(!DestEltVT.isVector() &&
6143            "Element type of vector ValueType must not be vector!");
6144     if (isSimple)
6145       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6146   }
6147
6148   // If the input is a constant, let getNode fold it.
6149   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6150     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6151     if (Res.getNode() != N) {
6152       if (!LegalOperations ||
6153           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6154         return Res;
6155
6156       // Folding it resulted in an illegal node, and it's too late to
6157       // do that. Clean up the old node and forego the transformation.
6158       // Ideally this won't happen very often, because instcombine
6159       // and the earlier dagcombine runs (where illegal nodes are
6160       // permitted) should have folded most of them already.
6161       DAG.DeleteNode(Res.getNode());
6162     }
6163   }
6164
6165   // (conv (conv x, t1), t2) -> (conv x, t2)
6166   if (N0.getOpcode() == ISD::BITCAST)
6167     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6168                        N0.getOperand(0));
6169
6170   // fold (conv (load x)) -> (load (conv*)x)
6171   // If the resultant load doesn't need a higher alignment than the original!
6172   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6173       // Do not change the width of a volatile load.
6174       !cast<LoadSDNode>(N0)->isVolatile() &&
6175       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6176       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6177     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6178     unsigned Align = TLI.getDataLayout()->
6179       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6180     unsigned OrigAlign = LN0->getAlignment();
6181
6182     if (Align <= OrigAlign) {
6183       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6184                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6185                                  LN0->isVolatile(), LN0->isNonTemporal(),
6186                                  LN0->isInvariant(), OrigAlign,
6187                                  LN0->getTBAAInfo());
6188       AddToWorkList(N);
6189       CombineTo(N0.getNode(),
6190                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6191                             N0.getValueType(), Load),
6192                 Load.getValue(1));
6193       return Load;
6194     }
6195   }
6196
6197   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6198   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6199   // This often reduces constant pool loads.
6200   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6201        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6202       N0.getNode()->hasOneUse() && VT.isInteger() &&
6203       !VT.isVector() && !N0.getValueType().isVector()) {
6204     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6205                                   N0.getOperand(0));
6206     AddToWorkList(NewConv.getNode());
6207
6208     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6209     if (N0.getOpcode() == ISD::FNEG)
6210       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6211                          NewConv, DAG.getConstant(SignBit, VT));
6212     assert(N0.getOpcode() == ISD::FABS);
6213     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6214                        NewConv, DAG.getConstant(~SignBit, VT));
6215   }
6216
6217   // fold (bitconvert (fcopysign cst, x)) ->
6218   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6219   // Note that we don't handle (copysign x, cst) because this can always be
6220   // folded to an fneg or fabs.
6221   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6222       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6223       VT.isInteger() && !VT.isVector()) {
6224     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6225     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6226     if (isTypeLegal(IntXVT)) {
6227       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6228                               IntXVT, N0.getOperand(1));
6229       AddToWorkList(X.getNode());
6230
6231       // If X has a different width than the result/lhs, sext it or truncate it.
6232       unsigned VTWidth = VT.getSizeInBits();
6233       if (OrigXWidth < VTWidth) {
6234         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6235         AddToWorkList(X.getNode());
6236       } else if (OrigXWidth > VTWidth) {
6237         // To get the sign bit in the right place, we have to shift it right
6238         // before truncating.
6239         X = DAG.getNode(ISD::SRL, SDLoc(X),
6240                         X.getValueType(), X,
6241                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6242         AddToWorkList(X.getNode());
6243         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6244         AddToWorkList(X.getNode());
6245       }
6246
6247       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6248       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6249                       X, DAG.getConstant(SignBit, VT));
6250       AddToWorkList(X.getNode());
6251
6252       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6253                                 VT, N0.getOperand(0));
6254       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6255                         Cst, DAG.getConstant(~SignBit, VT));
6256       AddToWorkList(Cst.getNode());
6257
6258       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6259     }
6260   }
6261
6262   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6263   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6264     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6265     if (CombineLD.getNode())
6266       return CombineLD;
6267   }
6268
6269   return SDValue();
6270 }
6271
6272 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6273   EVT VT = N->getValueType(0);
6274   return CombineConsecutiveLoads(N, VT);
6275 }
6276
6277 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6278 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6279 /// destination element value type.
6280 SDValue DAGCombiner::
6281 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6282   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6283
6284   // If this is already the right type, we're done.
6285   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6286
6287   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6288   unsigned DstBitSize = DstEltVT.getSizeInBits();
6289
6290   // If this is a conversion of N elements of one type to N elements of another
6291   // type, convert each element.  This handles FP<->INT cases.
6292   if (SrcBitSize == DstBitSize) {
6293     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6294                               BV->getValueType(0).getVectorNumElements());
6295
6296     // Due to the FP element handling below calling this routine recursively,
6297     // we can end up with a scalar-to-vector node here.
6298     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6299       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6300                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6301                                      DstEltVT, BV->getOperand(0)));
6302
6303     SmallVector<SDValue, 8> Ops;
6304     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6305       SDValue Op = BV->getOperand(i);
6306       // If the vector element type is not legal, the BUILD_VECTOR operands
6307       // are promoted and implicitly truncated.  Make that explicit here.
6308       if (Op.getValueType() != SrcEltVT)
6309         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6310       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6311                                 DstEltVT, Op));
6312       AddToWorkList(Ops.back().getNode());
6313     }
6314     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6315                        &Ops[0], Ops.size());
6316   }
6317
6318   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6319   // handle annoying details of growing/shrinking FP values, we convert them to
6320   // int first.
6321   if (SrcEltVT.isFloatingPoint()) {
6322     // Convert the input float vector to a int vector where the elements are the
6323     // same sizes.
6324     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6325     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6326     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6327     SrcEltVT = IntVT;
6328   }
6329
6330   // Now we know the input is an integer vector.  If the output is a FP type,
6331   // convert to integer first, then to FP of the right size.
6332   if (DstEltVT.isFloatingPoint()) {
6333     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6334     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6335     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6336
6337     // Next, convert to FP elements of the same size.
6338     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6339   }
6340
6341   // Okay, we know the src/dst types are both integers of differing types.
6342   // Handling growing first.
6343   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6344   if (SrcBitSize < DstBitSize) {
6345     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6346
6347     SmallVector<SDValue, 8> Ops;
6348     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6349          i += NumInputsPerOutput) {
6350       bool isLE = TLI.isLittleEndian();
6351       APInt NewBits = APInt(DstBitSize, 0);
6352       bool EltIsUndef = true;
6353       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6354         // Shift the previously computed bits over.
6355         NewBits <<= SrcBitSize;
6356         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6357         if (Op.getOpcode() == ISD::UNDEF) continue;
6358         EltIsUndef = false;
6359
6360         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6361                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6362       }
6363
6364       if (EltIsUndef)
6365         Ops.push_back(DAG.getUNDEF(DstEltVT));
6366       else
6367         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6368     }
6369
6370     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6371     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6372                        &Ops[0], Ops.size());
6373   }
6374
6375   // Finally, this must be the case where we are shrinking elements: each input
6376   // turns into multiple outputs.
6377   bool isS2V = ISD::isScalarToVector(BV);
6378   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6379   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6380                             NumOutputsPerInput*BV->getNumOperands());
6381   SmallVector<SDValue, 8> Ops;
6382
6383   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6384     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6385       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6386         Ops.push_back(DAG.getUNDEF(DstEltVT));
6387       continue;
6388     }
6389
6390     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6391                   getAPIntValue().zextOrTrunc(SrcBitSize);
6392
6393     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6394       APInt ThisVal = OpVal.trunc(DstBitSize);
6395       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6396       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6397         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6398         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6399                            Ops[0]);
6400       OpVal = OpVal.lshr(DstBitSize);
6401     }
6402
6403     // For big endian targets, swap the order of the pieces of each element.
6404     if (TLI.isBigEndian())
6405       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6406   }
6407
6408   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6409                      &Ops[0], Ops.size());
6410 }
6411
6412 SDValue DAGCombiner::visitFADD(SDNode *N) {
6413   SDValue N0 = N->getOperand(0);
6414   SDValue N1 = N->getOperand(1);
6415   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6416   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6417   EVT VT = N->getValueType(0);
6418
6419   // fold vector ops
6420   if (VT.isVector()) {
6421     SDValue FoldedVOp = SimplifyVBinOp(N);
6422     if (FoldedVOp.getNode()) return FoldedVOp;
6423   }
6424
6425   // fold (fadd c1, c2) -> c1 + c2
6426   if (N0CFP && N1CFP)
6427     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6428   // canonicalize constant to RHS
6429   if (N0CFP && !N1CFP)
6430     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6431   // fold (fadd A, 0) -> A
6432   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6433       N1CFP->getValueAPF().isZero())
6434     return N0;
6435   // fold (fadd A, (fneg B)) -> (fsub A, B)
6436   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6437     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6438     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6439                        GetNegatedExpression(N1, DAG, LegalOperations));
6440   // fold (fadd (fneg A), B) -> (fsub B, A)
6441   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6442     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6443     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6444                        GetNegatedExpression(N0, DAG, LegalOperations));
6445
6446   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6447   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6448       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6449       isa<ConstantFPSDNode>(N0.getOperand(1)))
6450     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6451                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6452                                    N0.getOperand(1), N1));
6453
6454   // No FP constant should be created after legalization as Instruction
6455   // Selection pass has hard time in dealing with FP constant.
6456   //
6457   // We don't need test this condition for transformation like following, as
6458   // the DAG being transformed implies it is legal to take FP constant as
6459   // operand.
6460   //
6461   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6462   //
6463   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6464
6465   // If allow, fold (fadd (fneg x), x) -> 0.0
6466   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6467       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6468     return DAG.getConstantFP(0.0, VT);
6469
6470     // If allow, fold (fadd x, (fneg x)) -> 0.0
6471   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6472       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6473     return DAG.getConstantFP(0.0, VT);
6474
6475   // In unsafe math mode, we can fold chains of FADD's of the same value
6476   // into multiplications.  This transform is not safe in general because
6477   // we are reducing the number of rounding steps.
6478   if (DAG.getTarget().Options.UnsafeFPMath &&
6479       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6480       !N0CFP && !N1CFP) {
6481     if (N0.getOpcode() == ISD::FMUL) {
6482       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6483       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6484
6485       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6486       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6487         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6488                                      SDValue(CFP00, 0),
6489                                      DAG.getConstantFP(1.0, VT));
6490         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6491                            N1, NewCFP);
6492       }
6493
6494       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6495       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6496         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6497                                      SDValue(CFP01, 0),
6498                                      DAG.getConstantFP(1.0, VT));
6499         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6500                            N1, NewCFP);
6501       }
6502
6503       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6504       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6505           N1.getOperand(0) == N1.getOperand(1) &&
6506           N0.getOperand(1) == N1.getOperand(0)) {
6507         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6508                                      SDValue(CFP00, 0),
6509                                      DAG.getConstantFP(2.0, VT));
6510         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6511                            N0.getOperand(1), NewCFP);
6512       }
6513
6514       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6515       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6516           N1.getOperand(0) == N1.getOperand(1) &&
6517           N0.getOperand(0) == N1.getOperand(0)) {
6518         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6519                                      SDValue(CFP01, 0),
6520                                      DAG.getConstantFP(2.0, VT));
6521         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6522                            N0.getOperand(0), NewCFP);
6523       }
6524     }
6525
6526     if (N1.getOpcode() == ISD::FMUL) {
6527       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6528       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6529
6530       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6531       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6532         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6533                                      SDValue(CFP10, 0),
6534                                      DAG.getConstantFP(1.0, VT));
6535         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6536                            N0, NewCFP);
6537       }
6538
6539       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6540       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6541         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6542                                      SDValue(CFP11, 0),
6543                                      DAG.getConstantFP(1.0, VT));
6544         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6545                            N0, NewCFP);
6546       }
6547
6548
6549       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6550       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6551           N0.getOperand(0) == N0.getOperand(1) &&
6552           N1.getOperand(1) == N0.getOperand(0)) {
6553         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6554                                      SDValue(CFP10, 0),
6555                                      DAG.getConstantFP(2.0, VT));
6556         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557                            N1.getOperand(1), NewCFP);
6558       }
6559
6560       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6561       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6562           N0.getOperand(0) == N0.getOperand(1) &&
6563           N1.getOperand(0) == N0.getOperand(0)) {
6564         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6565                                      SDValue(CFP11, 0),
6566                                      DAG.getConstantFP(2.0, VT));
6567         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6568                            N1.getOperand(0), NewCFP);
6569       }
6570     }
6571
6572     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6573       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6574       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6575       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6576           (N0.getOperand(0) == N1))
6577         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6578                            N1, DAG.getConstantFP(3.0, VT));
6579     }
6580
6581     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6582       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6583       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6584       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6585           N1.getOperand(0) == N0)
6586         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6587                            N0, DAG.getConstantFP(3.0, VT));
6588     }
6589
6590     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6591     if (AllowNewFpConst &&
6592         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6593         N0.getOperand(0) == N0.getOperand(1) &&
6594         N1.getOperand(0) == N1.getOperand(1) &&
6595         N0.getOperand(0) == N1.getOperand(0))
6596       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6597                          N0.getOperand(0),
6598                          DAG.getConstantFP(4.0, VT));
6599   }
6600
6601   // FADD -> FMA combines:
6602   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6603        DAG.getTarget().Options.UnsafeFPMath) &&
6604       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6605       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6606
6607     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6608     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6609       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6610                          N0.getOperand(0), N0.getOperand(1), N1);
6611
6612     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6613     // Note: Commutes FADD operands.
6614     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6615       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6616                          N1.getOperand(0), N1.getOperand(1), N0);
6617   }
6618
6619   return SDValue();
6620 }
6621
6622 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6623   SDValue N0 = N->getOperand(0);
6624   SDValue N1 = N->getOperand(1);
6625   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6626   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6627   EVT VT = N->getValueType(0);
6628   SDLoc dl(N);
6629
6630   // fold vector ops
6631   if (VT.isVector()) {
6632     SDValue FoldedVOp = SimplifyVBinOp(N);
6633     if (FoldedVOp.getNode()) return FoldedVOp;
6634   }
6635
6636   // fold (fsub c1, c2) -> c1-c2
6637   if (N0CFP && N1CFP)
6638     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6639   // fold (fsub A, 0) -> A
6640   if (DAG.getTarget().Options.UnsafeFPMath &&
6641       N1CFP && N1CFP->getValueAPF().isZero())
6642     return N0;
6643   // fold (fsub 0, B) -> -B
6644   if (DAG.getTarget().Options.UnsafeFPMath &&
6645       N0CFP && N0CFP->getValueAPF().isZero()) {
6646     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6647       return GetNegatedExpression(N1, DAG, LegalOperations);
6648     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6649       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6650   }
6651   // fold (fsub A, (fneg B)) -> (fadd A, B)
6652   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6653     return DAG.getNode(ISD::FADD, dl, VT, N0,
6654                        GetNegatedExpression(N1, DAG, LegalOperations));
6655
6656   // If 'unsafe math' is enabled, fold
6657   //    (fsub x, x) -> 0.0 &
6658   //    (fsub x, (fadd x, y)) -> (fneg y) &
6659   //    (fsub x, (fadd y, x)) -> (fneg y)
6660   if (DAG.getTarget().Options.UnsafeFPMath) {
6661     if (N0 == N1)
6662       return DAG.getConstantFP(0.0f, VT);
6663
6664     if (N1.getOpcode() == ISD::FADD) {
6665       SDValue N10 = N1->getOperand(0);
6666       SDValue N11 = N1->getOperand(1);
6667
6668       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6669                                           &DAG.getTarget().Options))
6670         return GetNegatedExpression(N11, DAG, LegalOperations);
6671
6672       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6673                                           &DAG.getTarget().Options))
6674         return GetNegatedExpression(N10, DAG, LegalOperations);
6675     }
6676   }
6677
6678   // FSUB -> FMA combines:
6679   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6680        DAG.getTarget().Options.UnsafeFPMath) &&
6681       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6682       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6683
6684     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6685     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6686       return DAG.getNode(ISD::FMA, dl, VT,
6687                          N0.getOperand(0), N0.getOperand(1),
6688                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6689
6690     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6691     // Note: Commutes FSUB operands.
6692     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6693       return DAG.getNode(ISD::FMA, dl, VT,
6694                          DAG.getNode(ISD::FNEG, dl, VT,
6695                          N1.getOperand(0)),
6696                          N1.getOperand(1), N0);
6697
6698     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6699     if (N0.getOpcode() == ISD::FNEG &&
6700         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6701         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6702       SDValue N00 = N0.getOperand(0).getOperand(0);
6703       SDValue N01 = N0.getOperand(0).getOperand(1);
6704       return DAG.getNode(ISD::FMA, dl, VT,
6705                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6706                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6707     }
6708   }
6709
6710   return SDValue();
6711 }
6712
6713 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6714   SDValue N0 = N->getOperand(0);
6715   SDValue N1 = N->getOperand(1);
6716   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6717   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6718   EVT VT = N->getValueType(0);
6719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6720
6721   // fold vector ops
6722   if (VT.isVector()) {
6723     SDValue FoldedVOp = SimplifyVBinOp(N);
6724     if (FoldedVOp.getNode()) return FoldedVOp;
6725   }
6726
6727   // fold (fmul c1, c2) -> c1*c2
6728   if (N0CFP && N1CFP)
6729     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6730   // canonicalize constant to RHS
6731   if (N0CFP && !N1CFP)
6732     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6733   // fold (fmul A, 0) -> 0
6734   if (DAG.getTarget().Options.UnsafeFPMath &&
6735       N1CFP && N1CFP->getValueAPF().isZero())
6736     return N1;
6737   // fold (fmul A, 0) -> 0, vector edition.
6738   if (DAG.getTarget().Options.UnsafeFPMath &&
6739       ISD::isBuildVectorAllZeros(N1.getNode()))
6740     return N1;
6741   // fold (fmul A, 1.0) -> A
6742   if (N1CFP && N1CFP->isExactlyValue(1.0))
6743     return N0;
6744   // fold (fmul X, 2.0) -> (fadd X, X)
6745   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6746     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6747   // fold (fmul X, -1.0) -> (fneg X)
6748   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6749     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6750       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6751
6752   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6753   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6754                                        &DAG.getTarget().Options)) {
6755     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6756                                          &DAG.getTarget().Options)) {
6757       // Both can be negated for free, check to see if at least one is cheaper
6758       // negated.
6759       if (LHSNeg == 2 || RHSNeg == 2)
6760         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6761                            GetNegatedExpression(N0, DAG, LegalOperations),
6762                            GetNegatedExpression(N1, DAG, LegalOperations));
6763     }
6764   }
6765
6766   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6767   if (DAG.getTarget().Options.UnsafeFPMath &&
6768       N1CFP && N0.getOpcode() == ISD::FMUL &&
6769       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6770     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6771                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6772                                    N0.getOperand(1), N1));
6773
6774   return SDValue();
6775 }
6776
6777 SDValue DAGCombiner::visitFMA(SDNode *N) {
6778   SDValue N0 = N->getOperand(0);
6779   SDValue N1 = N->getOperand(1);
6780   SDValue N2 = N->getOperand(2);
6781   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6782   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6783   EVT VT = N->getValueType(0);
6784   SDLoc dl(N);
6785
6786   if (DAG.getTarget().Options.UnsafeFPMath) {
6787     if (N0CFP && N0CFP->isZero())
6788       return N2;
6789     if (N1CFP && N1CFP->isZero())
6790       return N2;
6791   }
6792   if (N0CFP && N0CFP->isExactlyValue(1.0))
6793     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6794   if (N1CFP && N1CFP->isExactlyValue(1.0))
6795     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6796
6797   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6798   if (N0CFP && !N1CFP)
6799     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6800
6801   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6802   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6803       N2.getOpcode() == ISD::FMUL &&
6804       N0 == N2.getOperand(0) &&
6805       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6806     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6807                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6808   }
6809
6810
6811   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6812   if (DAG.getTarget().Options.UnsafeFPMath &&
6813       N0.getOpcode() == ISD::FMUL && N1CFP &&
6814       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6815     return DAG.getNode(ISD::FMA, dl, VT,
6816                        N0.getOperand(0),
6817                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6818                        N2);
6819   }
6820
6821   // (fma x, 1, y) -> (fadd x, y)
6822   // (fma x, -1, y) -> (fadd (fneg x), y)
6823   if (N1CFP) {
6824     if (N1CFP->isExactlyValue(1.0))
6825       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6826
6827     if (N1CFP->isExactlyValue(-1.0) &&
6828         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6829       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6830       AddToWorkList(RHSNeg.getNode());
6831       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6832     }
6833   }
6834
6835   // (fma x, c, x) -> (fmul x, (c+1))
6836   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6837     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6838                        DAG.getNode(ISD::FADD, dl, VT,
6839                                    N1, DAG.getConstantFP(1.0, VT)));
6840
6841   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6842   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6843       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6844     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6845                        DAG.getNode(ISD::FADD, dl, VT,
6846                                    N1, DAG.getConstantFP(-1.0, VT)));
6847
6848
6849   return SDValue();
6850 }
6851
6852 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6853   SDValue N0 = N->getOperand(0);
6854   SDValue N1 = N->getOperand(1);
6855   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6856   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6857   EVT VT = N->getValueType(0);
6858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6859
6860   // fold vector ops
6861   if (VT.isVector()) {
6862     SDValue FoldedVOp = SimplifyVBinOp(N);
6863     if (FoldedVOp.getNode()) return FoldedVOp;
6864   }
6865
6866   // fold (fdiv c1, c2) -> c1/c2
6867   if (N0CFP && N1CFP)
6868     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6869
6870   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6871   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6872     // Compute the reciprocal 1.0 / c2.
6873     APFloat N1APF = N1CFP->getValueAPF();
6874     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6875     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6876     // Only do the transform if the reciprocal is a legal fp immediate that
6877     // isn't too nasty (eg NaN, denormal, ...).
6878     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6879         (!LegalOperations ||
6880          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6881          // backend)... we should handle this gracefully after Legalize.
6882          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6883          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6884          TLI.isFPImmLegal(Recip, VT)))
6885       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6886                          DAG.getConstantFP(Recip, VT));
6887   }
6888
6889   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6890   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6891                                        &DAG.getTarget().Options)) {
6892     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6893                                          &DAG.getTarget().Options)) {
6894       // Both can be negated for free, check to see if at least one is cheaper
6895       // negated.
6896       if (LHSNeg == 2 || RHSNeg == 2)
6897         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6898                            GetNegatedExpression(N0, DAG, LegalOperations),
6899                            GetNegatedExpression(N1, DAG, LegalOperations));
6900     }
6901   }
6902
6903   return SDValue();
6904 }
6905
6906 SDValue DAGCombiner::visitFREM(SDNode *N) {
6907   SDValue N0 = N->getOperand(0);
6908   SDValue N1 = N->getOperand(1);
6909   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6910   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6911   EVT VT = N->getValueType(0);
6912
6913   // fold (frem c1, c2) -> fmod(c1,c2)
6914   if (N0CFP && N1CFP)
6915     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6916
6917   return SDValue();
6918 }
6919
6920 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6921   SDValue N0 = N->getOperand(0);
6922   SDValue N1 = N->getOperand(1);
6923   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6924   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6925   EVT VT = N->getValueType(0);
6926
6927   if (N0CFP && N1CFP)  // Constant fold
6928     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6929
6930   if (N1CFP) {
6931     const APFloat& V = N1CFP->getValueAPF();
6932     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6933     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6934     if (!V.isNegative()) {
6935       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6936         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6937     } else {
6938       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6939         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6940                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6941     }
6942   }
6943
6944   // copysign(fabs(x), y) -> copysign(x, y)
6945   // copysign(fneg(x), y) -> copysign(x, y)
6946   // copysign(copysign(x,z), y) -> copysign(x, y)
6947   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6948       N0.getOpcode() == ISD::FCOPYSIGN)
6949     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6950                        N0.getOperand(0), N1);
6951
6952   // copysign(x, abs(y)) -> abs(x)
6953   if (N1.getOpcode() == ISD::FABS)
6954     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6955
6956   // copysign(x, copysign(y,z)) -> copysign(x, z)
6957   if (N1.getOpcode() == ISD::FCOPYSIGN)
6958     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6959                        N0, N1.getOperand(1));
6960
6961   // copysign(x, fp_extend(y)) -> copysign(x, y)
6962   // copysign(x, fp_round(y)) -> copysign(x, y)
6963   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6964     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6965                        N0, N1.getOperand(0));
6966
6967   return SDValue();
6968 }
6969
6970 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6971   SDValue N0 = N->getOperand(0);
6972   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6973   EVT VT = N->getValueType(0);
6974   EVT OpVT = N0.getValueType();
6975
6976   // fold (sint_to_fp c1) -> c1fp
6977   if (N0C &&
6978       // ...but only if the target supports immediate floating-point values
6979       (!LegalOperations ||
6980        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6981     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6982
6983   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6984   // but UINT_TO_FP is legal on this target, try to convert.
6985   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6986       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6987     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6988     if (DAG.SignBitIsZero(N0))
6989       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6990   }
6991
6992   // The next optimizations are desirable only if SELECT_CC can be lowered.
6993   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6994   // having to say they don't support SELECT_CC on every type the DAG knows
6995   // about, since there is no way to mark an opcode illegal at all value types
6996   // (See also visitSELECT)
6997   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6998     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6999     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7000         !VT.isVector() &&
7001         (!LegalOperations ||
7002          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7003       SDValue Ops[] =
7004         { N0.getOperand(0), N0.getOperand(1),
7005           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7006           N0.getOperand(2) };
7007       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7008     }
7009
7010     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7011     //      (select_cc x, y, 1.0, 0.0,, cc)
7012     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7013         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7014         (!LegalOperations ||
7015          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7016       SDValue Ops[] =
7017         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7018           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7019           N0.getOperand(0).getOperand(2) };
7020       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7021     }
7022   }
7023
7024   return SDValue();
7025 }
7026
7027 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7028   SDValue N0 = N->getOperand(0);
7029   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7030   EVT VT = N->getValueType(0);
7031   EVT OpVT = N0.getValueType();
7032
7033   // fold (uint_to_fp c1) -> c1fp
7034   if (N0C &&
7035       // ...but only if the target supports immediate floating-point values
7036       (!LegalOperations ||
7037        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7038     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7039
7040   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7041   // but SINT_TO_FP is legal on this target, try to convert.
7042   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7043       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7044     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7045     if (DAG.SignBitIsZero(N0))
7046       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7047   }
7048
7049   // The next optimizations are desirable only if SELECT_CC can be lowered.
7050   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7051   // having to say they don't support SELECT_CC on every type the DAG knows
7052   // about, since there is no way to mark an opcode illegal at all value types
7053   // (See also visitSELECT)
7054   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7055     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7056
7057     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7058         (!LegalOperations ||
7059          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7060       SDValue Ops[] =
7061         { N0.getOperand(0), N0.getOperand(1),
7062           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7063           N0.getOperand(2) };
7064       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7065     }
7066   }
7067
7068   return SDValue();
7069 }
7070
7071 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7072   SDValue N0 = N->getOperand(0);
7073   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7074   EVT VT = N->getValueType(0);
7075
7076   // fold (fp_to_sint c1fp) -> c1
7077   if (N0CFP)
7078     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7079
7080   return SDValue();
7081 }
7082
7083 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7084   SDValue N0 = N->getOperand(0);
7085   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7086   EVT VT = N->getValueType(0);
7087
7088   // fold (fp_to_uint c1fp) -> c1
7089   if (N0CFP)
7090     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7091
7092   return SDValue();
7093 }
7094
7095 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7096   SDValue N0 = N->getOperand(0);
7097   SDValue N1 = N->getOperand(1);
7098   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7099   EVT VT = N->getValueType(0);
7100
7101   // fold (fp_round c1fp) -> c1fp
7102   if (N0CFP)
7103     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7104
7105   // fold (fp_round (fp_extend x)) -> x
7106   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7107     return N0.getOperand(0);
7108
7109   // fold (fp_round (fp_round x)) -> (fp_round x)
7110   if (N0.getOpcode() == ISD::FP_ROUND) {
7111     // This is a value preserving truncation if both round's are.
7112     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7113                    N0.getNode()->getConstantOperandVal(1) == 1;
7114     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7115                        DAG.getIntPtrConstant(IsTrunc));
7116   }
7117
7118   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7119   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7120     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7121                               N0.getOperand(0), N1);
7122     AddToWorkList(Tmp.getNode());
7123     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7124                        Tmp, N0.getOperand(1));
7125   }
7126
7127   return SDValue();
7128 }
7129
7130 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7131   SDValue N0 = N->getOperand(0);
7132   EVT VT = N->getValueType(0);
7133   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7134   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7135
7136   // fold (fp_round_inreg c1fp) -> c1fp
7137   if (N0CFP && isTypeLegal(EVT)) {
7138     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7139     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7140   }
7141
7142   return SDValue();
7143 }
7144
7145 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7146   SDValue N0 = N->getOperand(0);
7147   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7148   EVT VT = N->getValueType(0);
7149
7150   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7151   if (N->hasOneUse() &&
7152       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7153     return SDValue();
7154
7155   // fold (fp_extend c1fp) -> c1fp
7156   if (N0CFP)
7157     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7158
7159   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7160   // value of X.
7161   if (N0.getOpcode() == ISD::FP_ROUND
7162       && N0.getNode()->getConstantOperandVal(1) == 1) {
7163     SDValue In = N0.getOperand(0);
7164     if (In.getValueType() == VT) return In;
7165     if (VT.bitsLT(In.getValueType()))
7166       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7167                          In, N0.getOperand(1));
7168     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7169   }
7170
7171   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7172   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7173       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7174        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7175     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7176     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7177                                      LN0->getChain(),
7178                                      LN0->getBasePtr(), N0.getValueType(),
7179                                      LN0->getMemOperand());
7180     CombineTo(N, ExtLoad);
7181     CombineTo(N0.getNode(),
7182               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7183                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7184               ExtLoad.getValue(1));
7185     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7186   }
7187
7188   return SDValue();
7189 }
7190
7191 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7192   SDValue N0 = N->getOperand(0);
7193   EVT VT = N->getValueType(0);
7194
7195   if (VT.isVector()) {
7196     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7197     if (FoldedVOp.getNode()) return FoldedVOp;
7198   }
7199
7200   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7201                          &DAG.getTarget().Options))
7202     return GetNegatedExpression(N0, DAG, LegalOperations);
7203
7204   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7205   // constant pool values.
7206   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7207       !VT.isVector() &&
7208       N0.getNode()->hasOneUse() &&
7209       N0.getOperand(0).getValueType().isInteger()) {
7210     SDValue Int = N0.getOperand(0);
7211     EVT IntVT = Int.getValueType();
7212     if (IntVT.isInteger() && !IntVT.isVector()) {
7213       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7214               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7215       AddToWorkList(Int.getNode());
7216       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7217                          VT, Int);
7218     }
7219   }
7220
7221   // (fneg (fmul c, x)) -> (fmul -c, x)
7222   if (N0.getOpcode() == ISD::FMUL) {
7223     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7224     if (CFP1)
7225       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7226                          N0.getOperand(0),
7227                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7228                                      N0.getOperand(1)));
7229   }
7230
7231   return SDValue();
7232 }
7233
7234 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7235   SDValue N0 = N->getOperand(0);
7236   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7237   EVT VT = N->getValueType(0);
7238
7239   // fold (fceil c1) -> fceil(c1)
7240   if (N0CFP)
7241     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7242
7243   return SDValue();
7244 }
7245
7246 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7247   SDValue N0 = N->getOperand(0);
7248   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7249   EVT VT = N->getValueType(0);
7250
7251   // fold (ftrunc c1) -> ftrunc(c1)
7252   if (N0CFP)
7253     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7254
7255   return SDValue();
7256 }
7257
7258 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7259   SDValue N0 = N->getOperand(0);
7260   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7261   EVT VT = N->getValueType(0);
7262
7263   // fold (ffloor c1) -> ffloor(c1)
7264   if (N0CFP)
7265     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7266
7267   return SDValue();
7268 }
7269
7270 SDValue DAGCombiner::visitFABS(SDNode *N) {
7271   SDValue N0 = N->getOperand(0);
7272   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7273   EVT VT = N->getValueType(0);
7274
7275   if (VT.isVector()) {
7276     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7277     if (FoldedVOp.getNode()) return FoldedVOp;
7278   }
7279
7280   // fold (fabs c1) -> fabs(c1)
7281   if (N0CFP)
7282     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7283   // fold (fabs (fabs x)) -> (fabs x)
7284   if (N0.getOpcode() == ISD::FABS)
7285     return N->getOperand(0);
7286   // fold (fabs (fneg x)) -> (fabs x)
7287   // fold (fabs (fcopysign x, y)) -> (fabs x)
7288   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7289     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7290
7291   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7292   // constant pool values.
7293   if (!TLI.isFAbsFree(VT) &&
7294       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7295       N0.getOperand(0).getValueType().isInteger() &&
7296       !N0.getOperand(0).getValueType().isVector()) {
7297     SDValue Int = N0.getOperand(0);
7298     EVT IntVT = Int.getValueType();
7299     if (IntVT.isInteger() && !IntVT.isVector()) {
7300       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7301              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7302       AddToWorkList(Int.getNode());
7303       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7304                          N->getValueType(0), Int);
7305     }
7306   }
7307
7308   return SDValue();
7309 }
7310
7311 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7312   SDValue Chain = N->getOperand(0);
7313   SDValue N1 = N->getOperand(1);
7314   SDValue N2 = N->getOperand(2);
7315
7316   // If N is a constant we could fold this into a fallthrough or unconditional
7317   // branch. However that doesn't happen very often in normal code, because
7318   // Instcombine/SimplifyCFG should have handled the available opportunities.
7319   // If we did this folding here, it would be necessary to update the
7320   // MachineBasicBlock CFG, which is awkward.
7321
7322   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7323   // on the target.
7324   if (N1.getOpcode() == ISD::SETCC &&
7325       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7326                                    N1.getOperand(0).getValueType())) {
7327     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7328                        Chain, N1.getOperand(2),
7329                        N1.getOperand(0), N1.getOperand(1), N2);
7330   }
7331
7332   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7333       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7334        (N1.getOperand(0).hasOneUse() &&
7335         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7336     SDNode *Trunc = nullptr;
7337     if (N1.getOpcode() == ISD::TRUNCATE) {
7338       // Look pass the truncate.
7339       Trunc = N1.getNode();
7340       N1 = N1.getOperand(0);
7341     }
7342
7343     // Match this pattern so that we can generate simpler code:
7344     //
7345     //   %a = ...
7346     //   %b = and i32 %a, 2
7347     //   %c = srl i32 %b, 1
7348     //   brcond i32 %c ...
7349     //
7350     // into
7351     //
7352     //   %a = ...
7353     //   %b = and i32 %a, 2
7354     //   %c = setcc eq %b, 0
7355     //   brcond %c ...
7356     //
7357     // This applies only when the AND constant value has one bit set and the
7358     // SRL constant is equal to the log2 of the AND constant. The back-end is
7359     // smart enough to convert the result into a TEST/JMP sequence.
7360     SDValue Op0 = N1.getOperand(0);
7361     SDValue Op1 = N1.getOperand(1);
7362
7363     if (Op0.getOpcode() == ISD::AND &&
7364         Op1.getOpcode() == ISD::Constant) {
7365       SDValue AndOp1 = Op0.getOperand(1);
7366
7367       if (AndOp1.getOpcode() == ISD::Constant) {
7368         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7369
7370         if (AndConst.isPowerOf2() &&
7371             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7372           SDValue SetCC =
7373             DAG.getSetCC(SDLoc(N),
7374                          getSetCCResultType(Op0.getValueType()),
7375                          Op0, DAG.getConstant(0, Op0.getValueType()),
7376                          ISD::SETNE);
7377
7378           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7379                                           MVT::Other, Chain, SetCC, N2);
7380           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7381           // will convert it back to (X & C1) >> C2.
7382           CombineTo(N, NewBRCond, false);
7383           // Truncate is dead.
7384           if (Trunc) {
7385             removeFromWorkList(Trunc);
7386             DAG.DeleteNode(Trunc);
7387           }
7388           // Replace the uses of SRL with SETCC
7389           WorkListRemover DeadNodes(*this);
7390           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7391           removeFromWorkList(N1.getNode());
7392           DAG.DeleteNode(N1.getNode());
7393           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7394         }
7395       }
7396     }
7397
7398     if (Trunc)
7399       // Restore N1 if the above transformation doesn't match.
7400       N1 = N->getOperand(1);
7401   }
7402
7403   // Transform br(xor(x, y)) -> br(x != y)
7404   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7405   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7406     SDNode *TheXor = N1.getNode();
7407     SDValue Op0 = TheXor->getOperand(0);
7408     SDValue Op1 = TheXor->getOperand(1);
7409     if (Op0.getOpcode() == Op1.getOpcode()) {
7410       // Avoid missing important xor optimizations.
7411       SDValue Tmp = visitXOR(TheXor);
7412       if (Tmp.getNode()) {
7413         if (Tmp.getNode() != TheXor) {
7414           DEBUG(dbgs() << "\nReplacing.8 ";
7415                 TheXor->dump(&DAG);
7416                 dbgs() << "\nWith: ";
7417                 Tmp.getNode()->dump(&DAG);
7418                 dbgs() << '\n');
7419           WorkListRemover DeadNodes(*this);
7420           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7421           removeFromWorkList(TheXor);
7422           DAG.DeleteNode(TheXor);
7423           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7424                              MVT::Other, Chain, Tmp, N2);
7425         }
7426
7427         // visitXOR has changed XOR's operands or replaced the XOR completely,
7428         // bail out.
7429         return SDValue(N, 0);
7430       }
7431     }
7432
7433     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7434       bool Equal = false;
7435       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7436         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7437             Op0.getOpcode() == ISD::XOR) {
7438           TheXor = Op0.getNode();
7439           Equal = true;
7440         }
7441
7442       EVT SetCCVT = N1.getValueType();
7443       if (LegalTypes)
7444         SetCCVT = getSetCCResultType(SetCCVT);
7445       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7446                                    SetCCVT,
7447                                    Op0, Op1,
7448                                    Equal ? ISD::SETEQ : ISD::SETNE);
7449       // Replace the uses of XOR with SETCC
7450       WorkListRemover DeadNodes(*this);
7451       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7452       removeFromWorkList(N1.getNode());
7453       DAG.DeleteNode(N1.getNode());
7454       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7455                          MVT::Other, Chain, SetCC, N2);
7456     }
7457   }
7458
7459   return SDValue();
7460 }
7461
7462 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7463 //
7464 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7465   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7466   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7467
7468   // If N is a constant we could fold this into a fallthrough or unconditional
7469   // branch. However that doesn't happen very often in normal code, because
7470   // Instcombine/SimplifyCFG should have handled the available opportunities.
7471   // If we did this folding here, it would be necessary to update the
7472   // MachineBasicBlock CFG, which is awkward.
7473
7474   // Use SimplifySetCC to simplify SETCC's.
7475   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7476                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7477                                false);
7478   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7479
7480   // fold to a simpler setcc
7481   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7482     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7483                        N->getOperand(0), Simp.getOperand(2),
7484                        Simp.getOperand(0), Simp.getOperand(1),
7485                        N->getOperand(4));
7486
7487   return SDValue();
7488 }
7489
7490 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7491 /// uses N as its base pointer and that N may be folded in the load / store
7492 /// addressing mode.
7493 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7494                                     SelectionDAG &DAG,
7495                                     const TargetLowering &TLI) {
7496   EVT VT;
7497   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7498     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7499       return false;
7500     VT = Use->getValueType(0);
7501   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7502     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7503       return false;
7504     VT = ST->getValue().getValueType();
7505   } else
7506     return false;
7507
7508   TargetLowering::AddrMode AM;
7509   if (N->getOpcode() == ISD::ADD) {
7510     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7511     if (Offset)
7512       // [reg +/- imm]
7513       AM.BaseOffs = Offset->getSExtValue();
7514     else
7515       // [reg +/- reg]
7516       AM.Scale = 1;
7517   } else if (N->getOpcode() == ISD::SUB) {
7518     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7519     if (Offset)
7520       // [reg +/- imm]
7521       AM.BaseOffs = -Offset->getSExtValue();
7522     else
7523       // [reg +/- reg]
7524       AM.Scale = 1;
7525   } else
7526     return false;
7527
7528   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7529 }
7530
7531 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7532 /// pre-indexed load / store when the base pointer is an add or subtract
7533 /// and it has other uses besides the load / store. After the
7534 /// transformation, the new indexed load / store has effectively folded
7535 /// the add / subtract in and all of its other uses are redirected to the
7536 /// new load / store.
7537 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7538   if (Level < AfterLegalizeDAG)
7539     return false;
7540
7541   bool isLoad = true;
7542   SDValue Ptr;
7543   EVT VT;
7544   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7545     if (LD->isIndexed())
7546       return false;
7547     VT = LD->getMemoryVT();
7548     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7549         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7550       return false;
7551     Ptr = LD->getBasePtr();
7552   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7553     if (ST->isIndexed())
7554       return false;
7555     VT = ST->getMemoryVT();
7556     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7557         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7558       return false;
7559     Ptr = ST->getBasePtr();
7560     isLoad = false;
7561   } else {
7562     return false;
7563   }
7564
7565   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7566   // out.  There is no reason to make this a preinc/predec.
7567   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7568       Ptr.getNode()->hasOneUse())
7569     return false;
7570
7571   // Ask the target to do addressing mode selection.
7572   SDValue BasePtr;
7573   SDValue Offset;
7574   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7575   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7576     return false;
7577
7578   // Backends without true r+i pre-indexed forms may need to pass a
7579   // constant base with a variable offset so that constant coercion
7580   // will work with the patterns in canonical form.
7581   bool Swapped = false;
7582   if (isa<ConstantSDNode>(BasePtr)) {
7583     std::swap(BasePtr, Offset);
7584     Swapped = true;
7585   }
7586
7587   // Don't create a indexed load / store with zero offset.
7588   if (isa<ConstantSDNode>(Offset) &&
7589       cast<ConstantSDNode>(Offset)->isNullValue())
7590     return false;
7591
7592   // Try turning it into a pre-indexed load / store except when:
7593   // 1) The new base ptr is a frame index.
7594   // 2) If N is a store and the new base ptr is either the same as or is a
7595   //    predecessor of the value being stored.
7596   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7597   //    that would create a cycle.
7598   // 4) All uses are load / store ops that use it as old base ptr.
7599
7600   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7601   // (plus the implicit offset) to a register to preinc anyway.
7602   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7603     return false;
7604
7605   // Check #2.
7606   if (!isLoad) {
7607     SDValue Val = cast<StoreSDNode>(N)->getValue();
7608     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7609       return false;
7610   }
7611
7612   // If the offset is a constant, there may be other adds of constants that
7613   // can be folded with this one. We should do this to avoid having to keep
7614   // a copy of the original base pointer.
7615   SmallVector<SDNode *, 16> OtherUses;
7616   if (isa<ConstantSDNode>(Offset))
7617     for (SDNode *Use : BasePtr.getNode()->uses()) {
7618       if (Use == Ptr.getNode())
7619         continue;
7620
7621       if (Use->isPredecessorOf(N))
7622         continue;
7623
7624       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7625         OtherUses.clear();
7626         break;
7627       }
7628
7629       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7630       if (Op1.getNode() == BasePtr.getNode())
7631         std::swap(Op0, Op1);
7632       assert(Op0.getNode() == BasePtr.getNode() &&
7633              "Use of ADD/SUB but not an operand");
7634
7635       if (!isa<ConstantSDNode>(Op1)) {
7636         OtherUses.clear();
7637         break;
7638       }
7639
7640       // FIXME: In some cases, we can be smarter about this.
7641       if (Op1.getValueType() != Offset.getValueType()) {
7642         OtherUses.clear();
7643         break;
7644       }
7645
7646       OtherUses.push_back(Use);
7647     }
7648
7649   if (Swapped)
7650     std::swap(BasePtr, Offset);
7651
7652   // Now check for #3 and #4.
7653   bool RealUse = false;
7654
7655   // Caches for hasPredecessorHelper
7656   SmallPtrSet<const SDNode *, 32> Visited;
7657   SmallVector<const SDNode *, 16> Worklist;
7658
7659   for (SDNode *Use : Ptr.getNode()->uses()) {
7660     if (Use == N)
7661       continue;
7662     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7663       return false;
7664
7665     // If Ptr may be folded in addressing mode of other use, then it's
7666     // not profitable to do this transformation.
7667     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7668       RealUse = true;
7669   }
7670
7671   if (!RealUse)
7672     return false;
7673
7674   SDValue Result;
7675   if (isLoad)
7676     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7677                                 BasePtr, Offset, AM);
7678   else
7679     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7680                                  BasePtr, Offset, AM);
7681   ++PreIndexedNodes;
7682   ++NodesCombined;
7683   DEBUG(dbgs() << "\nReplacing.4 ";
7684         N->dump(&DAG);
7685         dbgs() << "\nWith: ";
7686         Result.getNode()->dump(&DAG);
7687         dbgs() << '\n');
7688   WorkListRemover DeadNodes(*this);
7689   if (isLoad) {
7690     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7691     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7692   } else {
7693     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7694   }
7695
7696   // Finally, since the node is now dead, remove it from the graph.
7697   DAG.DeleteNode(N);
7698
7699   if (Swapped)
7700     std::swap(BasePtr, Offset);
7701
7702   // Replace other uses of BasePtr that can be updated to use Ptr
7703   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7704     unsigned OffsetIdx = 1;
7705     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7706       OffsetIdx = 0;
7707     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7708            BasePtr.getNode() && "Expected BasePtr operand");
7709
7710     // We need to replace ptr0 in the following expression:
7711     //   x0 * offset0 + y0 * ptr0 = t0
7712     // knowing that
7713     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7714     //
7715     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7716     // indexed load/store and the expresion that needs to be re-written.
7717     //
7718     // Therefore, we have:
7719     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7720
7721     ConstantSDNode *CN =
7722       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7723     int X0, X1, Y0, Y1;
7724     APInt Offset0 = CN->getAPIntValue();
7725     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7726
7727     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7728     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7729     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7730     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7731
7732     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7733
7734     APInt CNV = Offset0;
7735     if (X0 < 0) CNV = -CNV;
7736     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7737     else CNV = CNV - Offset1;
7738
7739     // We can now generate the new expression.
7740     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7741     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7742
7743     SDValue NewUse = DAG.getNode(Opcode,
7744                                  SDLoc(OtherUses[i]),
7745                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7746     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7747     removeFromWorkList(OtherUses[i]);
7748     DAG.DeleteNode(OtherUses[i]);
7749   }
7750
7751   // Replace the uses of Ptr with uses of the updated base value.
7752   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7753   removeFromWorkList(Ptr.getNode());
7754   DAG.DeleteNode(Ptr.getNode());
7755
7756   return true;
7757 }
7758
7759 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7760 /// add / sub of the base pointer node into a post-indexed load / store.
7761 /// The transformation folded the add / subtract into the new indexed
7762 /// load / store effectively and all of its uses are redirected to the
7763 /// new load / store.
7764 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7765   if (Level < AfterLegalizeDAG)
7766     return false;
7767
7768   bool isLoad = true;
7769   SDValue Ptr;
7770   EVT VT;
7771   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7772     if (LD->isIndexed())
7773       return false;
7774     VT = LD->getMemoryVT();
7775     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7776         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7777       return false;
7778     Ptr = LD->getBasePtr();
7779   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7780     if (ST->isIndexed())
7781       return false;
7782     VT = ST->getMemoryVT();
7783     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7784         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7785       return false;
7786     Ptr = ST->getBasePtr();
7787     isLoad = false;
7788   } else {
7789     return false;
7790   }
7791
7792   if (Ptr.getNode()->hasOneUse())
7793     return false;
7794
7795   for (SDNode *Op : Ptr.getNode()->uses()) {
7796     if (Op == N ||
7797         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7798       continue;
7799
7800     SDValue BasePtr;
7801     SDValue Offset;
7802     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7803     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7804       // Don't create a indexed load / store with zero offset.
7805       if (isa<ConstantSDNode>(Offset) &&
7806           cast<ConstantSDNode>(Offset)->isNullValue())
7807         continue;
7808
7809       // Try turning it into a post-indexed load / store except when
7810       // 1) All uses are load / store ops that use it as base ptr (and
7811       //    it may be folded as addressing mmode).
7812       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7813       //    nor a successor of N. Otherwise, if Op is folded that would
7814       //    create a cycle.
7815
7816       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7817         continue;
7818
7819       // Check for #1.
7820       bool TryNext = false;
7821       for (SDNode *Use : BasePtr.getNode()->uses()) {
7822         if (Use == Ptr.getNode())
7823           continue;
7824
7825         // If all the uses are load / store addresses, then don't do the
7826         // transformation.
7827         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7828           bool RealUse = false;
7829           for (SDNode *UseUse : Use->uses()) {
7830             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7831               RealUse = true;
7832           }
7833
7834           if (!RealUse) {
7835             TryNext = true;
7836             break;
7837           }
7838         }
7839       }
7840
7841       if (TryNext)
7842         continue;
7843
7844       // Check for #2
7845       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7846         SDValue Result = isLoad
7847           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7848                                BasePtr, Offset, AM)
7849           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7850                                 BasePtr, Offset, AM);
7851         ++PostIndexedNodes;
7852         ++NodesCombined;
7853         DEBUG(dbgs() << "\nReplacing.5 ";
7854               N->dump(&DAG);
7855               dbgs() << "\nWith: ";
7856               Result.getNode()->dump(&DAG);
7857               dbgs() << '\n');
7858         WorkListRemover DeadNodes(*this);
7859         if (isLoad) {
7860           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7861           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7862         } else {
7863           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7864         }
7865
7866         // Finally, since the node is now dead, remove it from the graph.
7867         DAG.DeleteNode(N);
7868
7869         // Replace the uses of Use with uses of the updated base value.
7870         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7871                                       Result.getValue(isLoad ? 1 : 0));
7872         removeFromWorkList(Op);
7873         DAG.DeleteNode(Op);
7874         return true;
7875       }
7876     }
7877   }
7878
7879   return false;
7880 }
7881
7882 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7883   LoadSDNode *LD  = cast<LoadSDNode>(N);
7884   SDValue Chain = LD->getChain();
7885   SDValue Ptr   = LD->getBasePtr();
7886
7887   // If load is not volatile and there are no uses of the loaded value (and
7888   // the updated indexed value in case of indexed loads), change uses of the
7889   // chain value into uses of the chain input (i.e. delete the dead load).
7890   if (!LD->isVolatile()) {
7891     if (N->getValueType(1) == MVT::Other) {
7892       // Unindexed loads.
7893       if (!N->hasAnyUseOfValue(0)) {
7894         // It's not safe to use the two value CombineTo variant here. e.g.
7895         // v1, chain2 = load chain1, loc
7896         // v2, chain3 = load chain2, loc
7897         // v3         = add v2, c
7898         // Now we replace use of chain2 with chain1.  This makes the second load
7899         // isomorphic to the one we are deleting, and thus makes this load live.
7900         DEBUG(dbgs() << "\nReplacing.6 ";
7901               N->dump(&DAG);
7902               dbgs() << "\nWith chain: ";
7903               Chain.getNode()->dump(&DAG);
7904               dbgs() << "\n");
7905         WorkListRemover DeadNodes(*this);
7906         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7907
7908         if (N->use_empty()) {
7909           removeFromWorkList(N);
7910           DAG.DeleteNode(N);
7911         }
7912
7913         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7914       }
7915     } else {
7916       // Indexed loads.
7917       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7918       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7919         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7920         DEBUG(dbgs() << "\nReplacing.7 ";
7921               N->dump(&DAG);
7922               dbgs() << "\nWith: ";
7923               Undef.getNode()->dump(&DAG);
7924               dbgs() << " and 2 other values\n");
7925         WorkListRemover DeadNodes(*this);
7926         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7927         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7928                                       DAG.getUNDEF(N->getValueType(1)));
7929         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7930         removeFromWorkList(N);
7931         DAG.DeleteNode(N);
7932         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7933       }
7934     }
7935   }
7936
7937   // If this load is directly stored, replace the load value with the stored
7938   // value.
7939   // TODO: Handle store large -> read small portion.
7940   // TODO: Handle TRUNCSTORE/LOADEXT
7941   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7942     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7943       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7944       if (PrevST->getBasePtr() == Ptr &&
7945           PrevST->getValue().getValueType() == N->getValueType(0))
7946       return CombineTo(N, Chain.getOperand(1), Chain);
7947     }
7948   }
7949
7950   // Try to infer better alignment information than the load already has.
7951   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7952     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7953       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7954         SDValue NewLoad =
7955                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7956                               LD->getValueType(0),
7957                               Chain, Ptr, LD->getPointerInfo(),
7958                               LD->getMemoryVT(),
7959                               LD->isVolatile(), LD->isNonTemporal(), Align,
7960                               LD->getTBAAInfo());
7961         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7962       }
7963     }
7964   }
7965
7966   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7967     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7968 #ifndef NDEBUG
7969   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7970       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7971     UseAA = false;
7972 #endif
7973   if (UseAA && LD->isUnindexed()) {
7974     // Walk up chain skipping non-aliasing memory nodes.
7975     SDValue BetterChain = FindBetterChain(N, Chain);
7976
7977     // If there is a better chain.
7978     if (Chain != BetterChain) {
7979       SDValue ReplLoad;
7980
7981       // Replace the chain to void dependency.
7982       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7983         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7984                                BetterChain, Ptr, LD->getMemOperand());
7985       } else {
7986         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7987                                   LD->getValueType(0),
7988                                   BetterChain, Ptr, LD->getMemoryVT(),
7989                                   LD->getMemOperand());
7990       }
7991
7992       // Create token factor to keep old chain connected.
7993       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7994                                   MVT::Other, Chain, ReplLoad.getValue(1));
7995
7996       // Make sure the new and old chains are cleaned up.
7997       AddToWorkList(Token.getNode());
7998
7999       // Replace uses with load result and token factor. Don't add users
8000       // to work list.
8001       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8002     }
8003   }
8004
8005   // Try transforming N to an indexed load.
8006   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8007     return SDValue(N, 0);
8008
8009   // Try to slice up N to more direct loads if the slices are mapped to
8010   // different register banks or pairing can take place.
8011   if (SliceUpLoad(N))
8012     return SDValue(N, 0);
8013
8014   return SDValue();
8015 }
8016
8017 namespace {
8018 /// \brief Helper structure used to slice a load in smaller loads.
8019 /// Basically a slice is obtained from the following sequence:
8020 /// Origin = load Ty1, Base
8021 /// Shift = srl Ty1 Origin, CstTy Amount
8022 /// Inst = trunc Shift to Ty2
8023 ///
8024 /// Then, it will be rewriten into:
8025 /// Slice = load SliceTy, Base + SliceOffset
8026 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8027 ///
8028 /// SliceTy is deduced from the number of bits that are actually used to
8029 /// build Inst.
8030 struct LoadedSlice {
8031   /// \brief Helper structure used to compute the cost of a slice.
8032   struct Cost {
8033     /// Are we optimizing for code size.
8034     bool ForCodeSize;
8035     /// Various cost.
8036     unsigned Loads;
8037     unsigned Truncates;
8038     unsigned CrossRegisterBanksCopies;
8039     unsigned ZExts;
8040     unsigned Shift;
8041
8042     Cost(bool ForCodeSize = false)
8043         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8044           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8045
8046     /// \brief Get the cost of one isolated slice.
8047     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8048         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8049           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8050       EVT TruncType = LS.Inst->getValueType(0);
8051       EVT LoadedType = LS.getLoadedType();
8052       if (TruncType != LoadedType &&
8053           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8054         ZExts = 1;
8055     }
8056
8057     /// \brief Account for slicing gain in the current cost.
8058     /// Slicing provide a few gains like removing a shift or a
8059     /// truncate. This method allows to grow the cost of the original
8060     /// load with the gain from this slice.
8061     void addSliceGain(const LoadedSlice &LS) {
8062       // Each slice saves a truncate.
8063       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8064       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8065                               LS.Inst->getOperand(0).getValueType()))
8066         ++Truncates;
8067       // If there is a shift amount, this slice gets rid of it.
8068       if (LS.Shift)
8069         ++Shift;
8070       // If this slice can merge a cross register bank copy, account for it.
8071       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8072         ++CrossRegisterBanksCopies;
8073     }
8074
8075     Cost &operator+=(const Cost &RHS) {
8076       Loads += RHS.Loads;
8077       Truncates += RHS.Truncates;
8078       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8079       ZExts += RHS.ZExts;
8080       Shift += RHS.Shift;
8081       return *this;
8082     }
8083
8084     bool operator==(const Cost &RHS) const {
8085       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8086              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8087              ZExts == RHS.ZExts && Shift == RHS.Shift;
8088     }
8089
8090     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8091
8092     bool operator<(const Cost &RHS) const {
8093       // Assume cross register banks copies are as expensive as loads.
8094       // FIXME: Do we want some more target hooks?
8095       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8096       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8097       // Unless we are optimizing for code size, consider the
8098       // expensive operation first.
8099       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8100         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8101       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8102              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8103     }
8104
8105     bool operator>(const Cost &RHS) const { return RHS < *this; }
8106
8107     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8108
8109     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8110   };
8111   // The last instruction that represent the slice. This should be a
8112   // truncate instruction.
8113   SDNode *Inst;
8114   // The original load instruction.
8115   LoadSDNode *Origin;
8116   // The right shift amount in bits from the original load.
8117   unsigned Shift;
8118   // The DAG from which Origin came from.
8119   // This is used to get some contextual information about legal types, etc.
8120   SelectionDAG *DAG;
8121
8122   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8123               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8124       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8125
8126   LoadedSlice(const LoadedSlice &LS)
8127       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8128
8129   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8130   /// \return Result is \p BitWidth and has used bits set to 1 and
8131   ///         not used bits set to 0.
8132   APInt getUsedBits() const {
8133     // Reproduce the trunc(lshr) sequence:
8134     // - Start from the truncated value.
8135     // - Zero extend to the desired bit width.
8136     // - Shift left.
8137     assert(Origin && "No original load to compare against.");
8138     unsigned BitWidth = Origin->getValueSizeInBits(0);
8139     assert(Inst && "This slice is not bound to an instruction");
8140     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8141            "Extracted slice is bigger than the whole type!");
8142     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8143     UsedBits.setAllBits();
8144     UsedBits = UsedBits.zext(BitWidth);
8145     UsedBits <<= Shift;
8146     return UsedBits;
8147   }
8148
8149   /// \brief Get the size of the slice to be loaded in bytes.
8150   unsigned getLoadedSize() const {
8151     unsigned SliceSize = getUsedBits().countPopulation();
8152     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8153     return SliceSize / 8;
8154   }
8155
8156   /// \brief Get the type that will be loaded for this slice.
8157   /// Note: This may not be the final type for the slice.
8158   EVT getLoadedType() const {
8159     assert(DAG && "Missing context");
8160     LLVMContext &Ctxt = *DAG->getContext();
8161     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8162   }
8163
8164   /// \brief Get the alignment of the load used for this slice.
8165   unsigned getAlignment() const {
8166     unsigned Alignment = Origin->getAlignment();
8167     unsigned Offset = getOffsetFromBase();
8168     if (Offset != 0)
8169       Alignment = MinAlign(Alignment, Alignment + Offset);
8170     return Alignment;
8171   }
8172
8173   /// \brief Check if this slice can be rewritten with legal operations.
8174   bool isLegal() const {
8175     // An invalid slice is not legal.
8176     if (!Origin || !Inst || !DAG)
8177       return false;
8178
8179     // Offsets are for indexed load only, we do not handle that.
8180     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8181       return false;
8182
8183     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8184
8185     // Check that the type is legal.
8186     EVT SliceType = getLoadedType();
8187     if (!TLI.isTypeLegal(SliceType))
8188       return false;
8189
8190     // Check that the load is legal for this type.
8191     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8192       return false;
8193
8194     // Check that the offset can be computed.
8195     // 1. Check its type.
8196     EVT PtrType = Origin->getBasePtr().getValueType();
8197     if (PtrType == MVT::Untyped || PtrType.isExtended())
8198       return false;
8199
8200     // 2. Check that it fits in the immediate.
8201     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8202       return false;
8203
8204     // 3. Check that the computation is legal.
8205     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8206       return false;
8207
8208     // Check that the zext is legal if it needs one.
8209     EVT TruncateType = Inst->getValueType(0);
8210     if (TruncateType != SliceType &&
8211         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8212       return false;
8213
8214     return true;
8215   }
8216
8217   /// \brief Get the offset in bytes of this slice in the original chunk of
8218   /// bits.
8219   /// \pre DAG != nullptr.
8220   uint64_t getOffsetFromBase() const {
8221     assert(DAG && "Missing context.");
8222     bool IsBigEndian =
8223         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8224     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8225     uint64_t Offset = Shift / 8;
8226     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8227     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8228            "The size of the original loaded type is not a multiple of a"
8229            " byte.");
8230     // If Offset is bigger than TySizeInBytes, it means we are loading all
8231     // zeros. This should have been optimized before in the process.
8232     assert(TySizeInBytes > Offset &&
8233            "Invalid shift amount for given loaded size");
8234     if (IsBigEndian)
8235       Offset = TySizeInBytes - Offset - getLoadedSize();
8236     return Offset;
8237   }
8238
8239   /// \brief Generate the sequence of instructions to load the slice
8240   /// represented by this object and redirect the uses of this slice to
8241   /// this new sequence of instructions.
8242   /// \pre this->Inst && this->Origin are valid Instructions and this
8243   /// object passed the legal check: LoadedSlice::isLegal returned true.
8244   /// \return The last instruction of the sequence used to load the slice.
8245   SDValue loadSlice() const {
8246     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8247     const SDValue &OldBaseAddr = Origin->getBasePtr();
8248     SDValue BaseAddr = OldBaseAddr;
8249     // Get the offset in that chunk of bytes w.r.t. the endianess.
8250     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8251     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8252     if (Offset) {
8253       // BaseAddr = BaseAddr + Offset.
8254       EVT ArithType = BaseAddr.getValueType();
8255       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8256                               DAG->getConstant(Offset, ArithType));
8257     }
8258
8259     // Create the type of the loaded slice according to its size.
8260     EVT SliceType = getLoadedType();
8261
8262     // Create the load for the slice.
8263     SDValue LastInst = DAG->getLoad(
8264         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8265         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8266         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8267     // If the final type is not the same as the loaded type, this means that
8268     // we have to pad with zero. Create a zero extend for that.
8269     EVT FinalType = Inst->getValueType(0);
8270     if (SliceType != FinalType)
8271       LastInst =
8272           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8273     return LastInst;
8274   }
8275
8276   /// \brief Check if this slice can be merged with an expensive cross register
8277   /// bank copy. E.g.,
8278   /// i = load i32
8279   /// f = bitcast i32 i to float
8280   bool canMergeExpensiveCrossRegisterBankCopy() const {
8281     if (!Inst || !Inst->hasOneUse())
8282       return false;
8283     SDNode *Use = *Inst->use_begin();
8284     if (Use->getOpcode() != ISD::BITCAST)
8285       return false;
8286     assert(DAG && "Missing context");
8287     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8288     EVT ResVT = Use->getValueType(0);
8289     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8290     const TargetRegisterClass *ArgRC =
8291         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8292     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8293       return false;
8294
8295     // At this point, we know that we perform a cross-register-bank copy.
8296     // Check if it is expensive.
8297     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8298     // Assume bitcasts are cheap, unless both register classes do not
8299     // explicitly share a common sub class.
8300     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8301       return false;
8302
8303     // Check if it will be merged with the load.
8304     // 1. Check the alignment constraint.
8305     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8306         ResVT.getTypeForEVT(*DAG->getContext()));
8307
8308     if (RequiredAlignment > getAlignment())
8309       return false;
8310
8311     // 2. Check that the load is a legal operation for that type.
8312     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8313       return false;
8314
8315     // 3. Check that we do not have a zext in the way.
8316     if (Inst->getValueType(0) != getLoadedType())
8317       return false;
8318
8319     return true;
8320   }
8321 };
8322 }
8323
8324 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8325 /// \p UsedBits looks like 0..0 1..1 0..0.
8326 static bool areUsedBitsDense(const APInt &UsedBits) {
8327   // If all the bits are one, this is dense!
8328   if (UsedBits.isAllOnesValue())
8329     return true;
8330
8331   // Get rid of the unused bits on the right.
8332   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8333   // Get rid of the unused bits on the left.
8334   if (NarrowedUsedBits.countLeadingZeros())
8335     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8336   // Check that the chunk of bits is completely used.
8337   return NarrowedUsedBits.isAllOnesValue();
8338 }
8339
8340 /// \brief Check whether or not \p First and \p Second are next to each other
8341 /// in memory. This means that there is no hole between the bits loaded
8342 /// by \p First and the bits loaded by \p Second.
8343 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8344                                      const LoadedSlice &Second) {
8345   assert(First.Origin == Second.Origin && First.Origin &&
8346          "Unable to match different memory origins.");
8347   APInt UsedBits = First.getUsedBits();
8348   assert((UsedBits & Second.getUsedBits()) == 0 &&
8349          "Slices are not supposed to overlap.");
8350   UsedBits |= Second.getUsedBits();
8351   return areUsedBitsDense(UsedBits);
8352 }
8353
8354 /// \brief Adjust the \p GlobalLSCost according to the target
8355 /// paring capabilities and the layout of the slices.
8356 /// \pre \p GlobalLSCost should account for at least as many loads as
8357 /// there is in the slices in \p LoadedSlices.
8358 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8359                                  LoadedSlice::Cost &GlobalLSCost) {
8360   unsigned NumberOfSlices = LoadedSlices.size();
8361   // If there is less than 2 elements, no pairing is possible.
8362   if (NumberOfSlices < 2)
8363     return;
8364
8365   // Sort the slices so that elements that are likely to be next to each
8366   // other in memory are next to each other in the list.
8367   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8368             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8369     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8370     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8371   });
8372   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8373   // First (resp. Second) is the first (resp. Second) potentially candidate
8374   // to be placed in a paired load.
8375   const LoadedSlice *First = nullptr;
8376   const LoadedSlice *Second = nullptr;
8377   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8378                 // Set the beginning of the pair.
8379                                                            First = Second) {
8380
8381     Second = &LoadedSlices[CurrSlice];
8382
8383     // If First is NULL, it means we start a new pair.
8384     // Get to the next slice.
8385     if (!First)
8386       continue;
8387
8388     EVT LoadedType = First->getLoadedType();
8389
8390     // If the types of the slices are different, we cannot pair them.
8391     if (LoadedType != Second->getLoadedType())
8392       continue;
8393
8394     // Check if the target supplies paired loads for this type.
8395     unsigned RequiredAlignment = 0;
8396     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8397       // move to the next pair, this type is hopeless.
8398       Second = nullptr;
8399       continue;
8400     }
8401     // Check if we meet the alignment requirement.
8402     if (RequiredAlignment > First->getAlignment())
8403       continue;
8404
8405     // Check that both loads are next to each other in memory.
8406     if (!areSlicesNextToEachOther(*First, *Second))
8407       continue;
8408
8409     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8410     --GlobalLSCost.Loads;
8411     // Move to the next pair.
8412     Second = nullptr;
8413   }
8414 }
8415
8416 /// \brief Check the profitability of all involved LoadedSlice.
8417 /// Currently, it is considered profitable if there is exactly two
8418 /// involved slices (1) which are (2) next to each other in memory, and
8419 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8420 ///
8421 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8422 /// the elements themselves.
8423 ///
8424 /// FIXME: When the cost model will be mature enough, we can relax
8425 /// constraints (1) and (2).
8426 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8427                                 const APInt &UsedBits, bool ForCodeSize) {
8428   unsigned NumberOfSlices = LoadedSlices.size();
8429   if (StressLoadSlicing)
8430     return NumberOfSlices > 1;
8431
8432   // Check (1).
8433   if (NumberOfSlices != 2)
8434     return false;
8435
8436   // Check (2).
8437   if (!areUsedBitsDense(UsedBits))
8438     return false;
8439
8440   // Check (3).
8441   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8442   // The original code has one big load.
8443   OrigCost.Loads = 1;
8444   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8445     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8446     // Accumulate the cost of all the slices.
8447     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8448     GlobalSlicingCost += SliceCost;
8449
8450     // Account as cost in the original configuration the gain obtained
8451     // with the current slices.
8452     OrigCost.addSliceGain(LS);
8453   }
8454
8455   // If the target supports paired load, adjust the cost accordingly.
8456   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8457   return OrigCost > GlobalSlicingCost;
8458 }
8459
8460 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8461 /// operations, split it in the various pieces being extracted.
8462 ///
8463 /// This sort of thing is introduced by SROA.
8464 /// This slicing takes care not to insert overlapping loads.
8465 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8466 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8467   if (Level < AfterLegalizeDAG)
8468     return false;
8469
8470   LoadSDNode *LD = cast<LoadSDNode>(N);
8471   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8472       !LD->getValueType(0).isInteger())
8473     return false;
8474
8475   // Keep track of already used bits to detect overlapping values.
8476   // In that case, we will just abort the transformation.
8477   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8478
8479   SmallVector<LoadedSlice, 4> LoadedSlices;
8480
8481   // Check if this load is used as several smaller chunks of bits.
8482   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8483   // of computation for each trunc.
8484   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8485        UI != UIEnd; ++UI) {
8486     // Skip the uses of the chain.
8487     if (UI.getUse().getResNo() != 0)
8488       continue;
8489
8490     SDNode *User = *UI;
8491     unsigned Shift = 0;
8492
8493     // Check if this is a trunc(lshr).
8494     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8495         isa<ConstantSDNode>(User->getOperand(1))) {
8496       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8497       User = *User->use_begin();
8498     }
8499
8500     // At this point, User is a Truncate, iff we encountered, trunc or
8501     // trunc(lshr).
8502     if (User->getOpcode() != ISD::TRUNCATE)
8503       return false;
8504
8505     // The width of the type must be a power of 2 and greater than 8-bits.
8506     // Otherwise the load cannot be represented in LLVM IR.
8507     // Moreover, if we shifted with a non-8-bits multiple, the slice
8508     // will be across several bytes. We do not support that.
8509     unsigned Width = User->getValueSizeInBits(0);
8510     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8511       return 0;
8512
8513     // Build the slice for this chain of computations.
8514     LoadedSlice LS(User, LD, Shift, &DAG);
8515     APInt CurrentUsedBits = LS.getUsedBits();
8516
8517     // Check if this slice overlaps with another.
8518     if ((CurrentUsedBits & UsedBits) != 0)
8519       return false;
8520     // Update the bits used globally.
8521     UsedBits |= CurrentUsedBits;
8522
8523     // Check if the new slice would be legal.
8524     if (!LS.isLegal())
8525       return false;
8526
8527     // Record the slice.
8528     LoadedSlices.push_back(LS);
8529   }
8530
8531   // Abort slicing if it does not seem to be profitable.
8532   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8533     return false;
8534
8535   ++SlicedLoads;
8536
8537   // Rewrite each chain to use an independent load.
8538   // By construction, each chain can be represented by a unique load.
8539
8540   // Prepare the argument for the new token factor for all the slices.
8541   SmallVector<SDValue, 8> ArgChains;
8542   for (SmallVectorImpl<LoadedSlice>::const_iterator
8543            LSIt = LoadedSlices.begin(),
8544            LSItEnd = LoadedSlices.end();
8545        LSIt != LSItEnd; ++LSIt) {
8546     SDValue SliceInst = LSIt->loadSlice();
8547     CombineTo(LSIt->Inst, SliceInst, true);
8548     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8549       SliceInst = SliceInst.getOperand(0);
8550     assert(SliceInst->getOpcode() == ISD::LOAD &&
8551            "It takes more than a zext to get to the loaded slice!!");
8552     ArgChains.push_back(SliceInst.getValue(1));
8553   }
8554
8555   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8556                               &ArgChains[0], ArgChains.size());
8557   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8558   return true;
8559 }
8560
8561 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8562 /// load is having specific bytes cleared out.  If so, return the byte size
8563 /// being masked out and the shift amount.
8564 static std::pair<unsigned, unsigned>
8565 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8566   std::pair<unsigned, unsigned> Result(0, 0);
8567
8568   // Check for the structure we're looking for.
8569   if (V->getOpcode() != ISD::AND ||
8570       !isa<ConstantSDNode>(V->getOperand(1)) ||
8571       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8572     return Result;
8573
8574   // Check the chain and pointer.
8575   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8576   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8577
8578   // The store should be chained directly to the load or be an operand of a
8579   // tokenfactor.
8580   if (LD == Chain.getNode())
8581     ; // ok.
8582   else if (Chain->getOpcode() != ISD::TokenFactor)
8583     return Result; // Fail.
8584   else {
8585     bool isOk = false;
8586     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8587       if (Chain->getOperand(i).getNode() == LD) {
8588         isOk = true;
8589         break;
8590       }
8591     if (!isOk) return Result;
8592   }
8593
8594   // This only handles simple types.
8595   if (V.getValueType() != MVT::i16 &&
8596       V.getValueType() != MVT::i32 &&
8597       V.getValueType() != MVT::i64)
8598     return Result;
8599
8600   // Check the constant mask.  Invert it so that the bits being masked out are
8601   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8602   // follow the sign bit for uniformity.
8603   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8604   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8605   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8606   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8607   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8608   if (NotMaskLZ == 64) return Result;  // All zero mask.
8609
8610   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8611   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8612     return Result;
8613
8614   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8615   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8616     NotMaskLZ -= 64-V.getValueSizeInBits();
8617
8618   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8619   switch (MaskedBytes) {
8620   case 1:
8621   case 2:
8622   case 4: break;
8623   default: return Result; // All one mask, or 5-byte mask.
8624   }
8625
8626   // Verify that the first bit starts at a multiple of mask so that the access
8627   // is aligned the same as the access width.
8628   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8629
8630   Result.first = MaskedBytes;
8631   Result.second = NotMaskTZ/8;
8632   return Result;
8633 }
8634
8635
8636 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8637 /// provides a value as specified by MaskInfo.  If so, replace the specified
8638 /// store with a narrower store of truncated IVal.
8639 static SDNode *
8640 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8641                                 SDValue IVal, StoreSDNode *St,
8642                                 DAGCombiner *DC) {
8643   unsigned NumBytes = MaskInfo.first;
8644   unsigned ByteShift = MaskInfo.second;
8645   SelectionDAG &DAG = DC->getDAG();
8646
8647   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8648   // that uses this.  If not, this is not a replacement.
8649   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8650                                   ByteShift*8, (ByteShift+NumBytes)*8);
8651   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8652
8653   // Check that it is legal on the target to do this.  It is legal if the new
8654   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8655   // legalization.
8656   MVT VT = MVT::getIntegerVT(NumBytes*8);
8657   if (!DC->isTypeLegal(VT))
8658     return nullptr;
8659
8660   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8661   // shifted by ByteShift and truncated down to NumBytes.
8662   if (ByteShift)
8663     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8664                        DAG.getConstant(ByteShift*8,
8665                                     DC->getShiftAmountTy(IVal.getValueType())));
8666
8667   // Figure out the offset for the store and the alignment of the access.
8668   unsigned StOffset;
8669   unsigned NewAlign = St->getAlignment();
8670
8671   if (DAG.getTargetLoweringInfo().isLittleEndian())
8672     StOffset = ByteShift;
8673   else
8674     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8675
8676   SDValue Ptr = St->getBasePtr();
8677   if (StOffset) {
8678     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8679                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8680     NewAlign = MinAlign(NewAlign, StOffset);
8681   }
8682
8683   // Truncate down to the new size.
8684   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8685
8686   ++OpsNarrowed;
8687   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8688                       St->getPointerInfo().getWithOffset(StOffset),
8689                       false, false, NewAlign).getNode();
8690 }
8691
8692
8693 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8694 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8695 /// of the loaded bits, try narrowing the load and store if it would end up
8696 /// being a win for performance or code size.
8697 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8698   StoreSDNode *ST  = cast<StoreSDNode>(N);
8699   if (ST->isVolatile())
8700     return SDValue();
8701
8702   SDValue Chain = ST->getChain();
8703   SDValue Value = ST->getValue();
8704   SDValue Ptr   = ST->getBasePtr();
8705   EVT VT = Value.getValueType();
8706
8707   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8708     return SDValue();
8709
8710   unsigned Opc = Value.getOpcode();
8711
8712   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8713   // is a byte mask indicating a consecutive number of bytes, check to see if
8714   // Y is known to provide just those bytes.  If so, we try to replace the
8715   // load + replace + store sequence with a single (narrower) store, which makes
8716   // the load dead.
8717   if (Opc == ISD::OR) {
8718     std::pair<unsigned, unsigned> MaskedLoad;
8719     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8720     if (MaskedLoad.first)
8721       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8722                                                   Value.getOperand(1), ST,this))
8723         return SDValue(NewST, 0);
8724
8725     // Or is commutative, so try swapping X and Y.
8726     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8727     if (MaskedLoad.first)
8728       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8729                                                   Value.getOperand(0), ST,this))
8730         return SDValue(NewST, 0);
8731   }
8732
8733   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8734       Value.getOperand(1).getOpcode() != ISD::Constant)
8735     return SDValue();
8736
8737   SDValue N0 = Value.getOperand(0);
8738   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8739       Chain == SDValue(N0.getNode(), 1)) {
8740     LoadSDNode *LD = cast<LoadSDNode>(N0);
8741     if (LD->getBasePtr() != Ptr ||
8742         LD->getPointerInfo().getAddrSpace() !=
8743         ST->getPointerInfo().getAddrSpace())
8744       return SDValue();
8745
8746     // Find the type to narrow it the load / op / store to.
8747     SDValue N1 = Value.getOperand(1);
8748     unsigned BitWidth = N1.getValueSizeInBits();
8749     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8750     if (Opc == ISD::AND)
8751       Imm ^= APInt::getAllOnesValue(BitWidth);
8752     if (Imm == 0 || Imm.isAllOnesValue())
8753       return SDValue();
8754     unsigned ShAmt = Imm.countTrailingZeros();
8755     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8756     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8757     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8758     while (NewBW < BitWidth &&
8759            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8760              TLI.isNarrowingProfitable(VT, NewVT))) {
8761       NewBW = NextPowerOf2(NewBW);
8762       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8763     }
8764     if (NewBW >= BitWidth)
8765       return SDValue();
8766
8767     // If the lsb changed does not start at the type bitwidth boundary,
8768     // start at the previous one.
8769     if (ShAmt % NewBW)
8770       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8771     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8772                                    std::min(BitWidth, ShAmt + NewBW));
8773     if ((Imm & Mask) == Imm) {
8774       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8775       if (Opc == ISD::AND)
8776         NewImm ^= APInt::getAllOnesValue(NewBW);
8777       uint64_t PtrOff = ShAmt / 8;
8778       // For big endian targets, we need to adjust the offset to the pointer to
8779       // load the correct bytes.
8780       if (TLI.isBigEndian())
8781         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8782
8783       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8784       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8785       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8786         return SDValue();
8787
8788       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8789                                    Ptr.getValueType(), Ptr,
8790                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8791       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8792                                   LD->getChain(), NewPtr,
8793                                   LD->getPointerInfo().getWithOffset(PtrOff),
8794                                   LD->isVolatile(), LD->isNonTemporal(),
8795                                   LD->isInvariant(), NewAlign,
8796                                   LD->getTBAAInfo());
8797       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8798                                    DAG.getConstant(NewImm, NewVT));
8799       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8800                                    NewVal, NewPtr,
8801                                    ST->getPointerInfo().getWithOffset(PtrOff),
8802                                    false, false, NewAlign);
8803
8804       AddToWorkList(NewPtr.getNode());
8805       AddToWorkList(NewLD.getNode());
8806       AddToWorkList(NewVal.getNode());
8807       WorkListRemover DeadNodes(*this);
8808       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8809       ++OpsNarrowed;
8810       return NewST;
8811     }
8812   }
8813
8814   return SDValue();
8815 }
8816
8817 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8818 /// if the load value isn't used by any other operations, then consider
8819 /// transforming the pair to integer load / store operations if the target
8820 /// deems the transformation profitable.
8821 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8822   StoreSDNode *ST  = cast<StoreSDNode>(N);
8823   SDValue Chain = ST->getChain();
8824   SDValue Value = ST->getValue();
8825   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8826       Value.hasOneUse() &&
8827       Chain == SDValue(Value.getNode(), 1)) {
8828     LoadSDNode *LD = cast<LoadSDNode>(Value);
8829     EVT VT = LD->getMemoryVT();
8830     if (!VT.isFloatingPoint() ||
8831         VT != ST->getMemoryVT() ||
8832         LD->isNonTemporal() ||
8833         ST->isNonTemporal() ||
8834         LD->getPointerInfo().getAddrSpace() != 0 ||
8835         ST->getPointerInfo().getAddrSpace() != 0)
8836       return SDValue();
8837
8838     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8839     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8840         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8841         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8842         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8843       return SDValue();
8844
8845     unsigned LDAlign = LD->getAlignment();
8846     unsigned STAlign = ST->getAlignment();
8847     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8848     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8849     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8850       return SDValue();
8851
8852     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8853                                 LD->getChain(), LD->getBasePtr(),
8854                                 LD->getPointerInfo(),
8855                                 false, false, false, LDAlign);
8856
8857     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8858                                  NewLD, ST->getBasePtr(),
8859                                  ST->getPointerInfo(),
8860                                  false, false, STAlign);
8861
8862     AddToWorkList(NewLD.getNode());
8863     AddToWorkList(NewST.getNode());
8864     WorkListRemover DeadNodes(*this);
8865     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8866     ++LdStFP2Int;
8867     return NewST;
8868   }
8869
8870   return SDValue();
8871 }
8872
8873 /// Helper struct to parse and store a memory address as base + index + offset.
8874 /// We ignore sign extensions when it is safe to do so.
8875 /// The following two expressions are not equivalent. To differentiate we need
8876 /// to store whether there was a sign extension involved in the index
8877 /// computation.
8878 ///  (load (i64 add (i64 copyfromreg %c)
8879 ///                 (i64 signextend (add (i8 load %index)
8880 ///                                      (i8 1))))
8881 /// vs
8882 ///
8883 /// (load (i64 add (i64 copyfromreg %c)
8884 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8885 ///                                         (i32 1)))))
8886 struct BaseIndexOffset {
8887   SDValue Base;
8888   SDValue Index;
8889   int64_t Offset;
8890   bool IsIndexSignExt;
8891
8892   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8893
8894   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8895                   bool IsIndexSignExt) :
8896     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8897
8898   bool equalBaseIndex(const BaseIndexOffset &Other) {
8899     return Other.Base == Base && Other.Index == Index &&
8900       Other.IsIndexSignExt == IsIndexSignExt;
8901   }
8902
8903   /// Parses tree in Ptr for base, index, offset addresses.
8904   static BaseIndexOffset match(SDValue Ptr) {
8905     bool IsIndexSignExt = false;
8906
8907     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8908     // instruction, then it could be just the BASE or everything else we don't
8909     // know how to handle. Just use Ptr as BASE and give up.
8910     if (Ptr->getOpcode() != ISD::ADD)
8911       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8912
8913     // We know that we have at least an ADD instruction. Try to pattern match
8914     // the simple case of BASE + OFFSET.
8915     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8916       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8917       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8918                               IsIndexSignExt);
8919     }
8920
8921     // Inside a loop the current BASE pointer is calculated using an ADD and a
8922     // MUL instruction. In this case Ptr is the actual BASE pointer.
8923     // (i64 add (i64 %array_ptr)
8924     //          (i64 mul (i64 %induction_var)
8925     //                   (i64 %element_size)))
8926     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8927       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8928
8929     // Look at Base + Index + Offset cases.
8930     SDValue Base = Ptr->getOperand(0);
8931     SDValue IndexOffset = Ptr->getOperand(1);
8932
8933     // Skip signextends.
8934     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8935       IndexOffset = IndexOffset->getOperand(0);
8936       IsIndexSignExt = true;
8937     }
8938
8939     // Either the case of Base + Index (no offset) or something else.
8940     if (IndexOffset->getOpcode() != ISD::ADD)
8941       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8942
8943     // Now we have the case of Base + Index + offset.
8944     SDValue Index = IndexOffset->getOperand(0);
8945     SDValue Offset = IndexOffset->getOperand(1);
8946
8947     if (!isa<ConstantSDNode>(Offset))
8948       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8949
8950     // Ignore signextends.
8951     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8952       Index = Index->getOperand(0);
8953       IsIndexSignExt = true;
8954     } else IsIndexSignExt = false;
8955
8956     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8957     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8958   }
8959 };
8960
8961 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8962 /// is located in a sequence of memory operations connected by a chain.
8963 struct MemOpLink {
8964   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8965     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8966   // Ptr to the mem node.
8967   LSBaseSDNode *MemNode;
8968   // Offset from the base ptr.
8969   int64_t OffsetFromBase;
8970   // What is the sequence number of this mem node.
8971   // Lowest mem operand in the DAG starts at zero.
8972   unsigned SequenceNum;
8973 };
8974
8975 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8976   EVT MemVT = St->getMemoryVT();
8977   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8978   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8979     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8980
8981   // Don't merge vectors into wider inputs.
8982   if (MemVT.isVector() || !MemVT.isSimple())
8983     return false;
8984
8985   // Perform an early exit check. Do not bother looking at stored values that
8986   // are not constants or loads.
8987   SDValue StoredVal = St->getValue();
8988   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8989   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8990       !IsLoadSrc)
8991     return false;
8992
8993   // Only look at ends of store sequences.
8994   SDValue Chain = SDValue(St, 1);
8995   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8996     return false;
8997
8998   // This holds the base pointer, index, and the offset in bytes from the base
8999   // pointer.
9000   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9001
9002   // We must have a base and an offset.
9003   if (!BasePtr.Base.getNode())
9004     return false;
9005
9006   // Do not handle stores to undef base pointers.
9007   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9008     return false;
9009
9010   // Save the LoadSDNodes that we find in the chain.
9011   // We need to make sure that these nodes do not interfere with
9012   // any of the store nodes.
9013   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9014
9015   // Save the StoreSDNodes that we find in the chain.
9016   SmallVector<MemOpLink, 8> StoreNodes;
9017
9018   // Walk up the chain and look for nodes with offsets from the same
9019   // base pointer. Stop when reaching an instruction with a different kind
9020   // or instruction which has a different base pointer.
9021   unsigned Seq = 0;
9022   StoreSDNode *Index = St;
9023   while (Index) {
9024     // If the chain has more than one use, then we can't reorder the mem ops.
9025     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9026       break;
9027
9028     // Find the base pointer and offset for this memory node.
9029     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9030
9031     // Check that the base pointer is the same as the original one.
9032     if (!Ptr.equalBaseIndex(BasePtr))
9033       break;
9034
9035     // Check that the alignment is the same.
9036     if (Index->getAlignment() != St->getAlignment())
9037       break;
9038
9039     // The memory operands must not be volatile.
9040     if (Index->isVolatile() || Index->isIndexed())
9041       break;
9042
9043     // No truncation.
9044     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9045       if (St->isTruncatingStore())
9046         break;
9047
9048     // The stored memory type must be the same.
9049     if (Index->getMemoryVT() != MemVT)
9050       break;
9051
9052     // We do not allow unaligned stores because we want to prevent overriding
9053     // stores.
9054     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9055       break;
9056
9057     // We found a potential memory operand to merge.
9058     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9059
9060     // Find the next memory operand in the chain. If the next operand in the
9061     // chain is a store then move up and continue the scan with the next
9062     // memory operand. If the next operand is a load save it and use alias
9063     // information to check if it interferes with anything.
9064     SDNode *NextInChain = Index->getChain().getNode();
9065     while (1) {
9066       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9067         // We found a store node. Use it for the next iteration.
9068         Index = STn;
9069         break;
9070       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9071         if (Ldn->isVolatile()) {
9072           Index = nullptr;
9073           break;
9074         }
9075
9076         // Save the load node for later. Continue the scan.
9077         AliasLoadNodes.push_back(Ldn);
9078         NextInChain = Ldn->getChain().getNode();
9079         continue;
9080       } else {
9081         Index = nullptr;
9082         break;
9083       }
9084     }
9085   }
9086
9087   // Check if there is anything to merge.
9088   if (StoreNodes.size() < 2)
9089     return false;
9090
9091   // Sort the memory operands according to their distance from the base pointer.
9092   std::sort(StoreNodes.begin(), StoreNodes.end(),
9093             [](MemOpLink LHS, MemOpLink RHS) {
9094     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9095            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9096             LHS.SequenceNum > RHS.SequenceNum);
9097   });
9098
9099   // Scan the memory operations on the chain and find the first non-consecutive
9100   // store memory address.
9101   unsigned LastConsecutiveStore = 0;
9102   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9103   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9104
9105     // Check that the addresses are consecutive starting from the second
9106     // element in the list of stores.
9107     if (i > 0) {
9108       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9109       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9110         break;
9111     }
9112
9113     bool Alias = false;
9114     // Check if this store interferes with any of the loads that we found.
9115     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9116       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9117         Alias = true;
9118         break;
9119       }
9120     // We found a load that alias with this store. Stop the sequence.
9121     if (Alias)
9122       break;
9123
9124     // Mark this node as useful.
9125     LastConsecutiveStore = i;
9126   }
9127
9128   // The node with the lowest store address.
9129   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9130
9131   // Store the constants into memory as one consecutive store.
9132   if (!IsLoadSrc) {
9133     unsigned LastLegalType = 0;
9134     unsigned LastLegalVectorType = 0;
9135     bool NonZero = false;
9136     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9137       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9138       SDValue StoredVal = St->getValue();
9139
9140       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9141         NonZero |= !C->isNullValue();
9142       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9143         NonZero |= !C->getConstantFPValue()->isNullValue();
9144       } else {
9145         // Non-constant.
9146         break;
9147       }
9148
9149       // Find a legal type for the constant store.
9150       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9151       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9152       if (TLI.isTypeLegal(StoreTy))
9153         LastLegalType = i+1;
9154       // Or check whether a truncstore is legal.
9155       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9156                TargetLowering::TypePromoteInteger) {
9157         EVT LegalizedStoredValueTy =
9158           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9159         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9160           LastLegalType = i+1;
9161       }
9162
9163       // Find a legal type for the vector store.
9164       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9165       if (TLI.isTypeLegal(Ty))
9166         LastLegalVectorType = i + 1;
9167     }
9168
9169     // We only use vectors if the constant is known to be zero and the
9170     // function is not marked with the noimplicitfloat attribute.
9171     if (NonZero || NoVectors)
9172       LastLegalVectorType = 0;
9173
9174     // Check if we found a legal integer type to store.
9175     if (LastLegalType == 0 && LastLegalVectorType == 0)
9176       return false;
9177
9178     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9179     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9180
9181     // Make sure we have something to merge.
9182     if (NumElem < 2)
9183       return false;
9184
9185     unsigned EarliestNodeUsed = 0;
9186     for (unsigned i=0; i < NumElem; ++i) {
9187       // Find a chain for the new wide-store operand. Notice that some
9188       // of the store nodes that we found may not be selected for inclusion
9189       // in the wide store. The chain we use needs to be the chain of the
9190       // earliest store node which is *used* and replaced by the wide store.
9191       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9192         EarliestNodeUsed = i;
9193     }
9194
9195     // The earliest Node in the DAG.
9196     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9197     SDLoc DL(StoreNodes[0].MemNode);
9198
9199     SDValue StoredVal;
9200     if (UseVector) {
9201       // Find a legal type for the vector store.
9202       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9203       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9204       StoredVal = DAG.getConstant(0, Ty);
9205     } else {
9206       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9207       APInt StoreInt(StoreBW, 0);
9208
9209       // Construct a single integer constant which is made of the smaller
9210       // constant inputs.
9211       bool IsLE = TLI.isLittleEndian();
9212       for (unsigned i = 0; i < NumElem ; ++i) {
9213         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9214         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9215         SDValue Val = St->getValue();
9216         StoreInt<<=ElementSizeBytes*8;
9217         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9218           StoreInt|=C->getAPIntValue().zext(StoreBW);
9219         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9220           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9221         } else {
9222           assert(false && "Invalid constant element type");
9223         }
9224       }
9225
9226       // Create the new Load and Store operations.
9227       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9228       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9229     }
9230
9231     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9232                                     FirstInChain->getBasePtr(),
9233                                     FirstInChain->getPointerInfo(),
9234                                     false, false,
9235                                     FirstInChain->getAlignment());
9236
9237     // Replace the first store with the new store
9238     CombineTo(EarliestOp, NewStore);
9239     // Erase all other stores.
9240     for (unsigned i = 0; i < NumElem ; ++i) {
9241       if (StoreNodes[i].MemNode == EarliestOp)
9242         continue;
9243       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9244       // ReplaceAllUsesWith will replace all uses that existed when it was
9245       // called, but graph optimizations may cause new ones to appear. For
9246       // example, the case in pr14333 looks like
9247       //
9248       //  St's chain -> St -> another store -> X
9249       //
9250       // And the only difference from St to the other store is the chain.
9251       // When we change it's chain to be St's chain they become identical,
9252       // get CSEed and the net result is that X is now a use of St.
9253       // Since we know that St is redundant, just iterate.
9254       while (!St->use_empty())
9255         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9256       removeFromWorkList(St);
9257       DAG.DeleteNode(St);
9258     }
9259
9260     return true;
9261   }
9262
9263   // Below we handle the case of multiple consecutive stores that
9264   // come from multiple consecutive loads. We merge them into a single
9265   // wide load and a single wide store.
9266
9267   // Look for load nodes which are used by the stored values.
9268   SmallVector<MemOpLink, 8> LoadNodes;
9269
9270   // Find acceptable loads. Loads need to have the same chain (token factor),
9271   // must not be zext, volatile, indexed, and they must be consecutive.
9272   BaseIndexOffset LdBasePtr;
9273   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9274     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9275     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9276     if (!Ld) break;
9277
9278     // Loads must only have one use.
9279     if (!Ld->hasNUsesOfValue(1, 0))
9280       break;
9281
9282     // Check that the alignment is the same as the stores.
9283     if (Ld->getAlignment() != St->getAlignment())
9284       break;
9285
9286     // The memory operands must not be volatile.
9287     if (Ld->isVolatile() || Ld->isIndexed())
9288       break;
9289
9290     // We do not accept ext loads.
9291     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9292       break;
9293
9294     // The stored memory type must be the same.
9295     if (Ld->getMemoryVT() != MemVT)
9296       break;
9297
9298     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9299     // If this is not the first ptr that we check.
9300     if (LdBasePtr.Base.getNode()) {
9301       // The base ptr must be the same.
9302       if (!LdPtr.equalBaseIndex(LdBasePtr))
9303         break;
9304     } else {
9305       // Check that all other base pointers are the same as this one.
9306       LdBasePtr = LdPtr;
9307     }
9308
9309     // We found a potential memory operand to merge.
9310     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9311   }
9312
9313   if (LoadNodes.size() < 2)
9314     return false;
9315
9316   // Scan the memory operations on the chain and find the first non-consecutive
9317   // load memory address. These variables hold the index in the store node
9318   // array.
9319   unsigned LastConsecutiveLoad = 0;
9320   // This variable refers to the size and not index in the array.
9321   unsigned LastLegalVectorType = 0;
9322   unsigned LastLegalIntegerType = 0;
9323   StartAddress = LoadNodes[0].OffsetFromBase;
9324   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9325   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9326     // All loads much share the same chain.
9327     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9328       break;
9329
9330     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9331     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9332       break;
9333     LastConsecutiveLoad = i;
9334
9335     // Find a legal type for the vector store.
9336     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9337     if (TLI.isTypeLegal(StoreTy))
9338       LastLegalVectorType = i + 1;
9339
9340     // Find a legal type for the integer store.
9341     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9342     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9343     if (TLI.isTypeLegal(StoreTy))
9344       LastLegalIntegerType = i + 1;
9345     // Or check whether a truncstore and extload is legal.
9346     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9347              TargetLowering::TypePromoteInteger) {
9348       EVT LegalizedStoredValueTy =
9349         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9350       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9351           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9352           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9353           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9354         LastLegalIntegerType = i+1;
9355     }
9356   }
9357
9358   // Only use vector types if the vector type is larger than the integer type.
9359   // If they are the same, use integers.
9360   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9361   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9362
9363   // We add +1 here because the LastXXX variables refer to location while
9364   // the NumElem refers to array/index size.
9365   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9366   NumElem = std::min(LastLegalType, NumElem);
9367
9368   if (NumElem < 2)
9369     return false;
9370
9371   // The earliest Node in the DAG.
9372   unsigned EarliestNodeUsed = 0;
9373   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9374   for (unsigned i=1; i<NumElem; ++i) {
9375     // Find a chain for the new wide-store operand. Notice that some
9376     // of the store nodes that we found may not be selected for inclusion
9377     // in the wide store. The chain we use needs to be the chain of the
9378     // earliest store node which is *used* and replaced by the wide store.
9379     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9380       EarliestNodeUsed = i;
9381   }
9382
9383   // Find if it is better to use vectors or integers to load and store
9384   // to memory.
9385   EVT JointMemOpVT;
9386   if (UseVectorTy) {
9387     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9388   } else {
9389     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9390     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9391   }
9392
9393   SDLoc LoadDL(LoadNodes[0].MemNode);
9394   SDLoc StoreDL(StoreNodes[0].MemNode);
9395
9396   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9397   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9398                                 FirstLoad->getChain(),
9399                                 FirstLoad->getBasePtr(),
9400                                 FirstLoad->getPointerInfo(),
9401                                 false, false, false,
9402                                 FirstLoad->getAlignment());
9403
9404   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9405                                   FirstInChain->getBasePtr(),
9406                                   FirstInChain->getPointerInfo(), false, false,
9407                                   FirstInChain->getAlignment());
9408
9409   // Replace one of the loads with the new load.
9410   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9411   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9412                                 SDValue(NewLoad.getNode(), 1));
9413
9414   // Remove the rest of the load chains.
9415   for (unsigned i = 1; i < NumElem ; ++i) {
9416     // Replace all chain users of the old load nodes with the chain of the new
9417     // load node.
9418     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9419     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9420   }
9421
9422   // Replace the first store with the new store.
9423   CombineTo(EarliestOp, NewStore);
9424   // Erase all other stores.
9425   for (unsigned i = 0; i < NumElem ; ++i) {
9426     // Remove all Store nodes.
9427     if (StoreNodes[i].MemNode == EarliestOp)
9428       continue;
9429     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9430     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9431     removeFromWorkList(St);
9432     DAG.DeleteNode(St);
9433   }
9434
9435   return true;
9436 }
9437
9438 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9439   StoreSDNode *ST  = cast<StoreSDNode>(N);
9440   SDValue Chain = ST->getChain();
9441   SDValue Value = ST->getValue();
9442   SDValue Ptr   = ST->getBasePtr();
9443
9444   // If this is a store of a bit convert, store the input value if the
9445   // resultant store does not need a higher alignment than the original.
9446   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9447       ST->isUnindexed()) {
9448     unsigned OrigAlign = ST->getAlignment();
9449     EVT SVT = Value.getOperand(0).getValueType();
9450     unsigned Align = TLI.getDataLayout()->
9451       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9452     if (Align <= OrigAlign &&
9453         ((!LegalOperations && !ST->isVolatile()) ||
9454          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9455       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9456                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9457                           ST->isNonTemporal(), OrigAlign,
9458                           ST->getTBAAInfo());
9459   }
9460
9461   // Turn 'store undef, Ptr' -> nothing.
9462   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9463     return Chain;
9464
9465   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9466   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9467     // NOTE: If the original store is volatile, this transform must not increase
9468     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9469     // processor operation but an i64 (which is not legal) requires two.  So the
9470     // transform should not be done in this case.
9471     if (Value.getOpcode() != ISD::TargetConstantFP) {
9472       SDValue Tmp;
9473       switch (CFP->getSimpleValueType(0).SimpleTy) {
9474       default: llvm_unreachable("Unknown FP type");
9475       case MVT::f16:    // We don't do this for these yet.
9476       case MVT::f80:
9477       case MVT::f128:
9478       case MVT::ppcf128:
9479         break;
9480       case MVT::f32:
9481         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9482             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9483           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9484                               bitcastToAPInt().getZExtValue(), MVT::i32);
9485           return DAG.getStore(Chain, SDLoc(N), Tmp,
9486                               Ptr, ST->getMemOperand());
9487         }
9488         break;
9489       case MVT::f64:
9490         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9491              !ST->isVolatile()) ||
9492             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9493           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9494                                 getZExtValue(), MVT::i64);
9495           return DAG.getStore(Chain, SDLoc(N), Tmp,
9496                               Ptr, ST->getMemOperand());
9497         }
9498
9499         if (!ST->isVolatile() &&
9500             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9501           // Many FP stores are not made apparent until after legalize, e.g. for
9502           // argument passing.  Since this is so common, custom legalize the
9503           // 64-bit integer store into two 32-bit stores.
9504           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9505           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9506           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9507           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9508
9509           unsigned Alignment = ST->getAlignment();
9510           bool isVolatile = ST->isVolatile();
9511           bool isNonTemporal = ST->isNonTemporal();
9512           const MDNode *TBAAInfo = ST->getTBAAInfo();
9513
9514           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9515                                      Ptr, ST->getPointerInfo(),
9516                                      isVolatile, isNonTemporal,
9517                                      ST->getAlignment(), TBAAInfo);
9518           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9519                             DAG.getConstant(4, Ptr.getValueType()));
9520           Alignment = MinAlign(Alignment, 4U);
9521           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9522                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9523                                      isVolatile, isNonTemporal,
9524                                      Alignment, TBAAInfo);
9525           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9526                              St0, St1);
9527         }
9528
9529         break;
9530       }
9531     }
9532   }
9533
9534   // Try to infer better alignment information than the store already has.
9535   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9536     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9537       if (Align > ST->getAlignment())
9538         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9539                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9540                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9541                                  ST->getTBAAInfo());
9542     }
9543   }
9544
9545   // Try transforming a pair floating point load / store ops to integer
9546   // load / store ops.
9547   SDValue NewST = TransformFPLoadStorePair(N);
9548   if (NewST.getNode())
9549     return NewST;
9550
9551   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9552     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9553 #ifndef NDEBUG
9554   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9555       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9556     UseAA = false;
9557 #endif
9558   if (UseAA && ST->isUnindexed()) {
9559     // Walk up chain skipping non-aliasing memory nodes.
9560     SDValue BetterChain = FindBetterChain(N, Chain);
9561
9562     // If there is a better chain.
9563     if (Chain != BetterChain) {
9564       SDValue ReplStore;
9565
9566       // Replace the chain to avoid dependency.
9567       if (ST->isTruncatingStore()) {
9568         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9569                                       ST->getMemoryVT(), ST->getMemOperand());
9570       } else {
9571         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9572                                  ST->getMemOperand());
9573       }
9574
9575       // Create token to keep both nodes around.
9576       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9577                                   MVT::Other, Chain, ReplStore);
9578
9579       // Make sure the new and old chains are cleaned up.
9580       AddToWorkList(Token.getNode());
9581
9582       // Don't add users to work list.
9583       return CombineTo(N, Token, false);
9584     }
9585   }
9586
9587   // Try transforming N to an indexed store.
9588   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9589     return SDValue(N, 0);
9590
9591   // FIXME: is there such a thing as a truncating indexed store?
9592   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9593       Value.getValueType().isInteger()) {
9594     // See if we can simplify the input to this truncstore with knowledge that
9595     // only the low bits are being used.  For example:
9596     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9597     SDValue Shorter =
9598       GetDemandedBits(Value,
9599                       APInt::getLowBitsSet(
9600                         Value.getValueType().getScalarType().getSizeInBits(),
9601                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9602     AddToWorkList(Value.getNode());
9603     if (Shorter.getNode())
9604       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9605                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9606
9607     // Otherwise, see if we can simplify the operation with
9608     // SimplifyDemandedBits, which only works if the value has a single use.
9609     if (SimplifyDemandedBits(Value,
9610                         APInt::getLowBitsSet(
9611                           Value.getValueType().getScalarType().getSizeInBits(),
9612                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9613       return SDValue(N, 0);
9614   }
9615
9616   // If this is a load followed by a store to the same location, then the store
9617   // is dead/noop.
9618   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9619     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9620         ST->isUnindexed() && !ST->isVolatile() &&
9621         // There can't be any side effects between the load and store, such as
9622         // a call or store.
9623         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9624       // The store is dead, remove it.
9625       return Chain;
9626     }
9627   }
9628
9629   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9630   // truncating store.  We can do this even if this is already a truncstore.
9631   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9632       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9633       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9634                             ST->getMemoryVT())) {
9635     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9636                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9637   }
9638
9639   // Only perform this optimization before the types are legal, because we
9640   // don't want to perform this optimization on every DAGCombine invocation.
9641   if (!LegalTypes) {
9642     bool EverChanged = false;
9643
9644     do {
9645       // There can be multiple store sequences on the same chain.
9646       // Keep trying to merge store sequences until we are unable to do so
9647       // or until we merge the last store on the chain.
9648       bool Changed = MergeConsecutiveStores(ST);
9649       EverChanged |= Changed;
9650       if (!Changed) break;
9651     } while (ST->getOpcode() != ISD::DELETED_NODE);
9652
9653     if (EverChanged)
9654       return SDValue(N, 0);
9655   }
9656
9657   return ReduceLoadOpStoreWidth(N);
9658 }
9659
9660 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9661   SDValue InVec = N->getOperand(0);
9662   SDValue InVal = N->getOperand(1);
9663   SDValue EltNo = N->getOperand(2);
9664   SDLoc dl(N);
9665
9666   // If the inserted element is an UNDEF, just use the input vector.
9667   if (InVal.getOpcode() == ISD::UNDEF)
9668     return InVec;
9669
9670   EVT VT = InVec.getValueType();
9671
9672   // If we can't generate a legal BUILD_VECTOR, exit
9673   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9674     return SDValue();
9675
9676   // Check that we know which element is being inserted
9677   if (!isa<ConstantSDNode>(EltNo))
9678     return SDValue();
9679   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9680
9681   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9682   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9683   // vector elements.
9684   SmallVector<SDValue, 8> Ops;
9685   // Do not combine these two vectors if the output vector will not replace
9686   // the input vector.
9687   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9688     Ops.append(InVec.getNode()->op_begin(),
9689                InVec.getNode()->op_end());
9690   } else if (InVec.getOpcode() == ISD::UNDEF) {
9691     unsigned NElts = VT.getVectorNumElements();
9692     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9693   } else {
9694     return SDValue();
9695   }
9696
9697   // Insert the element
9698   if (Elt < Ops.size()) {
9699     // All the operands of BUILD_VECTOR must have the same type;
9700     // we enforce that here.
9701     EVT OpVT = Ops[0].getValueType();
9702     if (InVal.getValueType() != OpVT)
9703       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9704                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9705                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9706     Ops[Elt] = InVal;
9707   }
9708
9709   // Return the new vector
9710   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9711                      VT, &Ops[0], Ops.size());
9712 }
9713
9714 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9715   // (vextract (scalar_to_vector val, 0) -> val
9716   SDValue InVec = N->getOperand(0);
9717   EVT VT = InVec.getValueType();
9718   EVT NVT = N->getValueType(0);
9719
9720   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9721     // Check if the result type doesn't match the inserted element type. A
9722     // SCALAR_TO_VECTOR may truncate the inserted element and the
9723     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9724     SDValue InOp = InVec.getOperand(0);
9725     if (InOp.getValueType() != NVT) {
9726       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9727       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9728     }
9729     return InOp;
9730   }
9731
9732   SDValue EltNo = N->getOperand(1);
9733   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9734
9735   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9736   // We only perform this optimization before the op legalization phase because
9737   // we may introduce new vector instructions which are not backed by TD
9738   // patterns. For example on AVX, extracting elements from a wide vector
9739   // without using extract_subvector. However, if we can find an underlying
9740   // scalar value, then we can always use that.
9741   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9742       && ConstEltNo) {
9743     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9744     int NumElem = VT.getVectorNumElements();
9745     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9746     // Find the new index to extract from.
9747     int OrigElt = SVOp->getMaskElt(Elt);
9748
9749     // Extracting an undef index is undef.
9750     if (OrigElt == -1)
9751       return DAG.getUNDEF(NVT);
9752
9753     // Select the right vector half to extract from.
9754     SDValue SVInVec;
9755     if (OrigElt < NumElem) {
9756       SVInVec = InVec->getOperand(0);
9757     } else {
9758       SVInVec = InVec->getOperand(1);
9759       OrigElt -= NumElem;
9760     }
9761
9762     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9763       SDValue InOp = SVInVec.getOperand(OrigElt);
9764       if (InOp.getValueType() != NVT) {
9765         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9766         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9767       }
9768
9769       return InOp;
9770     }
9771
9772     // FIXME: We should handle recursing on other vector shuffles and
9773     // scalar_to_vector here as well.
9774
9775     if (!LegalOperations) {
9776       EVT IndexTy = TLI.getVectorIdxTy();
9777       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9778                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9779     }
9780   }
9781
9782   // Perform only after legalization to ensure build_vector / vector_shuffle
9783   // optimizations have already been done.
9784   if (!LegalOperations) return SDValue();
9785
9786   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9787   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9788   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9789
9790   if (ConstEltNo) {
9791     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9792     bool NewLoad = false;
9793     bool BCNumEltsChanged = false;
9794     EVT ExtVT = VT.getVectorElementType();
9795     EVT LVT = ExtVT;
9796
9797     // If the result of load has to be truncated, then it's not necessarily
9798     // profitable.
9799     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9800       return SDValue();
9801
9802     if (InVec.getOpcode() == ISD::BITCAST) {
9803       // Don't duplicate a load with other uses.
9804       if (!InVec.hasOneUse())
9805         return SDValue();
9806
9807       EVT BCVT = InVec.getOperand(0).getValueType();
9808       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9809         return SDValue();
9810       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9811         BCNumEltsChanged = true;
9812       InVec = InVec.getOperand(0);
9813       ExtVT = BCVT.getVectorElementType();
9814       NewLoad = true;
9815     }
9816
9817     LoadSDNode *LN0 = nullptr;
9818     const ShuffleVectorSDNode *SVN = nullptr;
9819     if (ISD::isNormalLoad(InVec.getNode())) {
9820       LN0 = cast<LoadSDNode>(InVec);
9821     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9822                InVec.getOperand(0).getValueType() == ExtVT &&
9823                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9824       // Don't duplicate a load with other uses.
9825       if (!InVec.hasOneUse())
9826         return SDValue();
9827
9828       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9829     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9830       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9831       // =>
9832       // (load $addr+1*size)
9833
9834       // Don't duplicate a load with other uses.
9835       if (!InVec.hasOneUse())
9836         return SDValue();
9837
9838       // If the bit convert changed the number of elements, it is unsafe
9839       // to examine the mask.
9840       if (BCNumEltsChanged)
9841         return SDValue();
9842
9843       // Select the input vector, guarding against out of range extract vector.
9844       unsigned NumElems = VT.getVectorNumElements();
9845       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9846       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9847
9848       if (InVec.getOpcode() == ISD::BITCAST) {
9849         // Don't duplicate a load with other uses.
9850         if (!InVec.hasOneUse())
9851           return SDValue();
9852
9853         InVec = InVec.getOperand(0);
9854       }
9855       if (ISD::isNormalLoad(InVec.getNode())) {
9856         LN0 = cast<LoadSDNode>(InVec);
9857         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9858       }
9859     }
9860
9861     // Make sure we found a non-volatile load and the extractelement is
9862     // the only use.
9863     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9864       return SDValue();
9865
9866     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9867     if (Elt == -1)
9868       return DAG.getUNDEF(LVT);
9869
9870     unsigned Align = LN0->getAlignment();
9871     if (NewLoad) {
9872       // Check the resultant load doesn't need a higher alignment than the
9873       // original load.
9874       unsigned NewAlign =
9875         TLI.getDataLayout()
9876             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9877
9878       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9879         return SDValue();
9880
9881       Align = NewAlign;
9882     }
9883
9884     SDValue NewPtr = LN0->getBasePtr();
9885     unsigned PtrOff = 0;
9886
9887     if (Elt) {
9888       PtrOff = LVT.getSizeInBits() * Elt / 8;
9889       EVT PtrType = NewPtr.getValueType();
9890       if (TLI.isBigEndian())
9891         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9892       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9893                            DAG.getConstant(PtrOff, PtrType));
9894     }
9895
9896     // The replacement we need to do here is a little tricky: we need to
9897     // replace an extractelement of a load with a load.
9898     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9899     // Note that this replacement assumes that the extractvalue is the only
9900     // use of the load; that's okay because we don't want to perform this
9901     // transformation in other cases anyway.
9902     SDValue Load;
9903     SDValue Chain;
9904     if (NVT.bitsGT(LVT)) {
9905       // If the result type of vextract is wider than the load, then issue an
9906       // extending load instead.
9907       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9908         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9909       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9910                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9911                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9912                             Align, LN0->getTBAAInfo());
9913       Chain = Load.getValue(1);
9914     } else {
9915       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9916                          LN0->getPointerInfo().getWithOffset(PtrOff),
9917                          LN0->isVolatile(), LN0->isNonTemporal(),
9918                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9919       Chain = Load.getValue(1);
9920       if (NVT.bitsLT(LVT))
9921         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9922       else
9923         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9924     }
9925     WorkListRemover DeadNodes(*this);
9926     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9927     SDValue To[] = { Load, Chain };
9928     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9929     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9930     // worklist explicitly as well.
9931     AddToWorkList(Load.getNode());
9932     AddUsersToWorkList(Load.getNode()); // Add users too
9933     // Make sure to revisit this node to clean it up; it will usually be dead.
9934     AddToWorkList(N);
9935     return SDValue(N, 0);
9936   }
9937
9938   return SDValue();
9939 }
9940
9941 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9942 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9943   // We perform this optimization post type-legalization because
9944   // the type-legalizer often scalarizes integer-promoted vectors.
9945   // Performing this optimization before may create bit-casts which
9946   // will be type-legalized to complex code sequences.
9947   // We perform this optimization only before the operation legalizer because we
9948   // may introduce illegal operations.
9949   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9950     return SDValue();
9951
9952   unsigned NumInScalars = N->getNumOperands();
9953   SDLoc dl(N);
9954   EVT VT = N->getValueType(0);
9955
9956   // Check to see if this is a BUILD_VECTOR of a bunch of values
9957   // which come from any_extend or zero_extend nodes. If so, we can create
9958   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9959   // optimizations. We do not handle sign-extend because we can't fill the sign
9960   // using shuffles.
9961   EVT SourceType = MVT::Other;
9962   bool AllAnyExt = true;
9963
9964   for (unsigned i = 0; i != NumInScalars; ++i) {
9965     SDValue In = N->getOperand(i);
9966     // Ignore undef inputs.
9967     if (In.getOpcode() == ISD::UNDEF) continue;
9968
9969     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9970     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9971
9972     // Abort if the element is not an extension.
9973     if (!ZeroExt && !AnyExt) {
9974       SourceType = MVT::Other;
9975       break;
9976     }
9977
9978     // The input is a ZeroExt or AnyExt. Check the original type.
9979     EVT InTy = In.getOperand(0).getValueType();
9980
9981     // Check that all of the widened source types are the same.
9982     if (SourceType == MVT::Other)
9983       // First time.
9984       SourceType = InTy;
9985     else if (InTy != SourceType) {
9986       // Multiple income types. Abort.
9987       SourceType = MVT::Other;
9988       break;
9989     }
9990
9991     // Check if all of the extends are ANY_EXTENDs.
9992     AllAnyExt &= AnyExt;
9993   }
9994
9995   // In order to have valid types, all of the inputs must be extended from the
9996   // same source type and all of the inputs must be any or zero extend.
9997   // Scalar sizes must be a power of two.
9998   EVT OutScalarTy = VT.getScalarType();
9999   bool ValidTypes = SourceType != MVT::Other &&
10000                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10001                  isPowerOf2_32(SourceType.getSizeInBits());
10002
10003   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10004   // turn into a single shuffle instruction.
10005   if (!ValidTypes)
10006     return SDValue();
10007
10008   bool isLE = TLI.isLittleEndian();
10009   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10010   assert(ElemRatio > 1 && "Invalid element size ratio");
10011   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10012                                DAG.getConstant(0, SourceType);
10013
10014   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10015   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10016
10017   // Populate the new build_vector
10018   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10019     SDValue Cast = N->getOperand(i);
10020     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10021             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10022             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10023     SDValue In;
10024     if (Cast.getOpcode() == ISD::UNDEF)
10025       In = DAG.getUNDEF(SourceType);
10026     else
10027       In = Cast->getOperand(0);
10028     unsigned Index = isLE ? (i * ElemRatio) :
10029                             (i * ElemRatio + (ElemRatio - 1));
10030
10031     assert(Index < Ops.size() && "Invalid index");
10032     Ops[Index] = In;
10033   }
10034
10035   // The type of the new BUILD_VECTOR node.
10036   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10037   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10038          "Invalid vector size");
10039   // Check if the new vector type is legal.
10040   if (!isTypeLegal(VecVT)) return SDValue();
10041
10042   // Make the new BUILD_VECTOR.
10043   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10044
10045   // The new BUILD_VECTOR node has the potential to be further optimized.
10046   AddToWorkList(BV.getNode());
10047   // Bitcast to the desired type.
10048   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10049 }
10050
10051 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10052   EVT VT = N->getValueType(0);
10053
10054   unsigned NumInScalars = N->getNumOperands();
10055   SDLoc dl(N);
10056
10057   EVT SrcVT = MVT::Other;
10058   unsigned Opcode = ISD::DELETED_NODE;
10059   unsigned NumDefs = 0;
10060
10061   for (unsigned i = 0; i != NumInScalars; ++i) {
10062     SDValue In = N->getOperand(i);
10063     unsigned Opc = In.getOpcode();
10064
10065     if (Opc == ISD::UNDEF)
10066       continue;
10067
10068     // If all scalar values are floats and converted from integers.
10069     if (Opcode == ISD::DELETED_NODE &&
10070         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10071       Opcode = Opc;
10072     }
10073
10074     if (Opc != Opcode)
10075       return SDValue();
10076
10077     EVT InVT = In.getOperand(0).getValueType();
10078
10079     // If all scalar values are typed differently, bail out. It's chosen to
10080     // simplify BUILD_VECTOR of integer types.
10081     if (SrcVT == MVT::Other)
10082       SrcVT = InVT;
10083     if (SrcVT != InVT)
10084       return SDValue();
10085     NumDefs++;
10086   }
10087
10088   // If the vector has just one element defined, it's not worth to fold it into
10089   // a vectorized one.
10090   if (NumDefs < 2)
10091     return SDValue();
10092
10093   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10094          && "Should only handle conversion from integer to float.");
10095   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10096
10097   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10098
10099   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10100     return SDValue();
10101
10102   SmallVector<SDValue, 8> Opnds;
10103   for (unsigned i = 0; i != NumInScalars; ++i) {
10104     SDValue In = N->getOperand(i);
10105
10106     if (In.getOpcode() == ISD::UNDEF)
10107       Opnds.push_back(DAG.getUNDEF(SrcVT));
10108     else
10109       Opnds.push_back(In.getOperand(0));
10110   }
10111   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10112                            &Opnds[0], Opnds.size());
10113   AddToWorkList(BV.getNode());
10114
10115   return DAG.getNode(Opcode, dl, VT, BV);
10116 }
10117
10118 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10119   unsigned NumInScalars = N->getNumOperands();
10120   SDLoc dl(N);
10121   EVT VT = N->getValueType(0);
10122
10123   // A vector built entirely of undefs is undef.
10124   if (ISD::allOperandsUndef(N))
10125     return DAG.getUNDEF(VT);
10126
10127   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10128   if (V.getNode())
10129     return V;
10130
10131   V = reduceBuildVecConvertToConvertBuildVec(N);
10132   if (V.getNode())
10133     return V;
10134
10135   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10136   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10137   // at most two distinct vectors, turn this into a shuffle node.
10138
10139   // May only combine to shuffle after legalize if shuffle is legal.
10140   if (LegalOperations &&
10141       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10142     return SDValue();
10143
10144   SDValue VecIn1, VecIn2;
10145   for (unsigned i = 0; i != NumInScalars; ++i) {
10146     // Ignore undef inputs.
10147     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10148
10149     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10150     // constant index, bail out.
10151     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10152         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10153       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10154       break;
10155     }
10156
10157     // We allow up to two distinct input vectors.
10158     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10159     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10160       continue;
10161
10162     if (!VecIn1.getNode()) {
10163       VecIn1 = ExtractedFromVec;
10164     } else if (!VecIn2.getNode()) {
10165       VecIn2 = ExtractedFromVec;
10166     } else {
10167       // Too many inputs.
10168       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10169       break;
10170     }
10171   }
10172
10173     // If everything is good, we can make a shuffle operation.
10174   if (VecIn1.getNode()) {
10175     SmallVector<int, 8> Mask;
10176     for (unsigned i = 0; i != NumInScalars; ++i) {
10177       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10178         Mask.push_back(-1);
10179         continue;
10180       }
10181
10182       // If extracting from the first vector, just use the index directly.
10183       SDValue Extract = N->getOperand(i);
10184       SDValue ExtVal = Extract.getOperand(1);
10185       if (Extract.getOperand(0) == VecIn1) {
10186         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10187         if (ExtIndex > VT.getVectorNumElements())
10188           return SDValue();
10189
10190         Mask.push_back(ExtIndex);
10191         continue;
10192       }
10193
10194       // Otherwise, use InIdx + VecSize
10195       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10196       Mask.push_back(Idx+NumInScalars);
10197     }
10198
10199     // We can't generate a shuffle node with mismatched input and output types.
10200     // Attempt to transform a single input vector to the correct type.
10201     if ((VT != VecIn1.getValueType())) {
10202       // We don't support shuffeling between TWO values of different types.
10203       if (VecIn2.getNode())
10204         return SDValue();
10205
10206       // We only support widening of vectors which are half the size of the
10207       // output registers. For example XMM->YMM widening on X86 with AVX.
10208       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10209         return SDValue();
10210
10211       // If the input vector type has a different base type to the output
10212       // vector type, bail out.
10213       if (VecIn1.getValueType().getVectorElementType() !=
10214           VT.getVectorElementType())
10215         return SDValue();
10216
10217       // Widen the input vector by adding undef values.
10218       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10219                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10220     }
10221
10222     // If VecIn2 is unused then change it to undef.
10223     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10224
10225     // Check that we were able to transform all incoming values to the same
10226     // type.
10227     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10228         VecIn1.getValueType() != VT)
10229           return SDValue();
10230
10231     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10232     if (!isTypeLegal(VT))
10233       return SDValue();
10234
10235     // Return the new VECTOR_SHUFFLE node.
10236     SDValue Ops[2];
10237     Ops[0] = VecIn1;
10238     Ops[1] = VecIn2;
10239     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10240   }
10241
10242   return SDValue();
10243 }
10244
10245 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10246   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10247   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10248   // inputs come from at most two distinct vectors, turn this into a shuffle
10249   // node.
10250
10251   // If we only have one input vector, we don't need to do any concatenation.
10252   if (N->getNumOperands() == 1)
10253     return N->getOperand(0);
10254
10255   // Check if all of the operands are undefs.
10256   EVT VT = N->getValueType(0);
10257   if (ISD::allOperandsUndef(N))
10258     return DAG.getUNDEF(VT);
10259
10260   // Optimize concat_vectors where one of the vectors is undef.
10261   if (N->getNumOperands() == 2 &&
10262       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10263     SDValue In = N->getOperand(0);
10264     assert(In.getValueType().isVector() && "Must concat vectors");
10265
10266     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10267     if (In->getOpcode() == ISD::BITCAST &&
10268         !In->getOperand(0)->getValueType(0).isVector()) {
10269       SDValue Scalar = In->getOperand(0);
10270       EVT SclTy = Scalar->getValueType(0);
10271
10272       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10273         return SDValue();
10274
10275       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10276                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10277       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10278         return SDValue();
10279
10280       SDLoc dl = SDLoc(N);
10281       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10282       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10283     }
10284   }
10285
10286   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10287   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10288   if (N->getNumOperands() == 2 &&
10289       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10290       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10291     EVT VT = N->getValueType(0);
10292     SDValue N0 = N->getOperand(0);
10293     SDValue N1 = N->getOperand(1);
10294     SmallVector<SDValue, 8> Opnds;
10295     unsigned BuildVecNumElts =  N0.getNumOperands();
10296
10297     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10298       Opnds.push_back(N0.getOperand(i));
10299     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10300       Opnds.push_back(N1.getOperand(i));
10301
10302     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10303                        Opnds.size());
10304   }
10305
10306   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10307   // nodes often generate nop CONCAT_VECTOR nodes.
10308   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10309   // place the incoming vectors at the exact same location.
10310   SDValue SingleSource = SDValue();
10311   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10312
10313   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10314     SDValue Op = N->getOperand(i);
10315
10316     if (Op.getOpcode() == ISD::UNDEF)
10317       continue;
10318
10319     // Check if this is the identity extract:
10320     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10321       return SDValue();
10322
10323     // Find the single incoming vector for the extract_subvector.
10324     if (SingleSource.getNode()) {
10325       if (Op.getOperand(0) != SingleSource)
10326         return SDValue();
10327     } else {
10328       SingleSource = Op.getOperand(0);
10329
10330       // Check the source type is the same as the type of the result.
10331       // If not, this concat may extend the vector, so we can not
10332       // optimize it away.
10333       if (SingleSource.getValueType() != N->getValueType(0))
10334         return SDValue();
10335     }
10336
10337     unsigned IdentityIndex = i * PartNumElem;
10338     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10339     // The extract index must be constant.
10340     if (!CS)
10341       return SDValue();
10342
10343     // Check that we are reading from the identity index.
10344     if (CS->getZExtValue() != IdentityIndex)
10345       return SDValue();
10346   }
10347
10348   if (SingleSource.getNode())
10349     return SingleSource;
10350
10351   return SDValue();
10352 }
10353
10354 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10355   EVT NVT = N->getValueType(0);
10356   SDValue V = N->getOperand(0);
10357
10358   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10359     // Combine:
10360     //    (extract_subvec (concat V1, V2, ...), i)
10361     // Into:
10362     //    Vi if possible
10363     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10364     // type.
10365     if (V->getOperand(0).getValueType() != NVT)
10366       return SDValue();
10367     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10368     unsigned NumElems = NVT.getVectorNumElements();
10369     assert((Idx % NumElems) == 0 &&
10370            "IDX in concat is not a multiple of the result vector length.");
10371     return V->getOperand(Idx / NumElems);
10372   }
10373
10374   // Skip bitcasting
10375   if (V->getOpcode() == ISD::BITCAST)
10376     V = V.getOperand(0);
10377
10378   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10379     SDLoc dl(N);
10380     // Handle only simple case where vector being inserted and vector
10381     // being extracted are of same type, and are half size of larger vectors.
10382     EVT BigVT = V->getOperand(0).getValueType();
10383     EVT SmallVT = V->getOperand(1).getValueType();
10384     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10385       return SDValue();
10386
10387     // Only handle cases where both indexes are constants with the same type.
10388     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10389     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10390
10391     if (InsIdx && ExtIdx &&
10392         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10393         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10394       // Combine:
10395       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10396       // Into:
10397       //    indices are equal or bit offsets are equal => V1
10398       //    otherwise => (extract_subvec V1, ExtIdx)
10399       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10400           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10401         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10402       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10403                          DAG.getNode(ISD::BITCAST, dl,
10404                                      N->getOperand(0).getValueType(),
10405                                      V->getOperand(0)), N->getOperand(1));
10406     }
10407   }
10408
10409   return SDValue();
10410 }
10411
10412 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10413 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10414   EVT VT = N->getValueType(0);
10415   unsigned NumElts = VT.getVectorNumElements();
10416
10417   SDValue N0 = N->getOperand(0);
10418   SDValue N1 = N->getOperand(1);
10419   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10420
10421   SmallVector<SDValue, 4> Ops;
10422   EVT ConcatVT = N0.getOperand(0).getValueType();
10423   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10424   unsigned NumConcats = NumElts / NumElemsPerConcat;
10425
10426   // Look at every vector that's inserted. We're looking for exact
10427   // subvector-sized copies from a concatenated vector
10428   for (unsigned I = 0; I != NumConcats; ++I) {
10429     // Make sure we're dealing with a copy.
10430     unsigned Begin = I * NumElemsPerConcat;
10431     bool AllUndef = true, NoUndef = true;
10432     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10433       if (SVN->getMaskElt(J) >= 0)
10434         AllUndef = false;
10435       else
10436         NoUndef = false;
10437     }
10438
10439     if (NoUndef) {
10440       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10441         return SDValue();
10442
10443       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10444         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10445           return SDValue();
10446
10447       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10448       if (FirstElt < N0.getNumOperands())
10449         Ops.push_back(N0.getOperand(FirstElt));
10450       else
10451         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10452
10453     } else if (AllUndef) {
10454       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10455     } else { // Mixed with general masks and undefs, can't do optimization.
10456       return SDValue();
10457     }
10458   }
10459
10460   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10461                      Ops.size());
10462 }
10463
10464 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10465   EVT VT = N->getValueType(0);
10466   unsigned NumElts = VT.getVectorNumElements();
10467
10468   SDValue N0 = N->getOperand(0);
10469   SDValue N1 = N->getOperand(1);
10470
10471   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10472
10473   // Canonicalize shuffle undef, undef -> undef
10474   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10475     return DAG.getUNDEF(VT);
10476
10477   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10478
10479   // Canonicalize shuffle v, v -> v, undef
10480   if (N0 == N1) {
10481     SmallVector<int, 8> NewMask;
10482     for (unsigned i = 0; i != NumElts; ++i) {
10483       int Idx = SVN->getMaskElt(i);
10484       if (Idx >= (int)NumElts) Idx -= NumElts;
10485       NewMask.push_back(Idx);
10486     }
10487     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10488                                 &NewMask[0]);
10489   }
10490
10491   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10492   if (N0.getOpcode() == ISD::UNDEF) {
10493     SmallVector<int, 8> NewMask;
10494     for (unsigned i = 0; i != NumElts; ++i) {
10495       int Idx = SVN->getMaskElt(i);
10496       if (Idx >= 0) {
10497         if (Idx >= (int)NumElts)
10498           Idx -= NumElts;
10499         else
10500           Idx = -1; // remove reference to lhs
10501       }
10502       NewMask.push_back(Idx);
10503     }
10504     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10505                                 &NewMask[0]);
10506   }
10507
10508   // Remove references to rhs if it is undef
10509   if (N1.getOpcode() == ISD::UNDEF) {
10510     bool Changed = false;
10511     SmallVector<int, 8> NewMask;
10512     for (unsigned i = 0; i != NumElts; ++i) {
10513       int Idx = SVN->getMaskElt(i);
10514       if (Idx >= (int)NumElts) {
10515         Idx = -1;
10516         Changed = true;
10517       }
10518       NewMask.push_back(Idx);
10519     }
10520     if (Changed)
10521       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10522   }
10523
10524   // If it is a splat, check if the argument vector is another splat or a
10525   // build_vector with all scalar elements the same.
10526   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10527     SDNode *V = N0.getNode();
10528
10529     // If this is a bit convert that changes the element type of the vector but
10530     // not the number of vector elements, look through it.  Be careful not to
10531     // look though conversions that change things like v4f32 to v2f64.
10532     if (V->getOpcode() == ISD::BITCAST) {
10533       SDValue ConvInput = V->getOperand(0);
10534       if (ConvInput.getValueType().isVector() &&
10535           ConvInput.getValueType().getVectorNumElements() == NumElts)
10536         V = ConvInput.getNode();
10537     }
10538
10539     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10540       assert(V->getNumOperands() == NumElts &&
10541              "BUILD_VECTOR has wrong number of operands");
10542       SDValue Base;
10543       bool AllSame = true;
10544       for (unsigned i = 0; i != NumElts; ++i) {
10545         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10546           Base = V->getOperand(i);
10547           break;
10548         }
10549       }
10550       // Splat of <u, u, u, u>, return <u, u, u, u>
10551       if (!Base.getNode())
10552         return N0;
10553       for (unsigned i = 0; i != NumElts; ++i) {
10554         if (V->getOperand(i) != Base) {
10555           AllSame = false;
10556           break;
10557         }
10558       }
10559       // Splat of <x, x, x, x>, return <x, x, x, x>
10560       if (AllSame)
10561         return N0;
10562     }
10563   }
10564
10565   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10566       Level < AfterLegalizeVectorOps &&
10567       (N1.getOpcode() == ISD::UNDEF ||
10568       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10569        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10570     SDValue V = partitionShuffleOfConcats(N, DAG);
10571
10572     if (V.getNode())
10573       return V;
10574   }
10575
10576   // If this shuffle node is simply a swizzle of another shuffle node,
10577   // and it reverses the swizzle of the previous shuffle then we can
10578   // optimize shuffle(shuffle(x, undef), undef) -> x.
10579   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10580       N1.getOpcode() == ISD::UNDEF) {
10581
10582     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10583
10584     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10585     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10586       return SDValue();
10587
10588     // The incoming shuffle must be of the same type as the result of the
10589     // current shuffle.
10590     assert(OtherSV->getOperand(0).getValueType() == VT &&
10591            "Shuffle types don't match");
10592
10593     for (unsigned i = 0; i != NumElts; ++i) {
10594       int Idx = SVN->getMaskElt(i);
10595       assert(Idx < (int)NumElts && "Index references undef operand");
10596       // Next, this index comes from the first value, which is the incoming
10597       // shuffle. Adopt the incoming index.
10598       if (Idx >= 0)
10599         Idx = OtherSV->getMaskElt(Idx);
10600
10601       // The combined shuffle must map each index to itself.
10602       if (Idx >= 0 && (unsigned)Idx != i)
10603         return SDValue();
10604     }
10605
10606     return OtherSV->getOperand(0);
10607   }
10608
10609   return SDValue();
10610 }
10611
10612 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10613   SDValue N0 = N->getOperand(0);
10614   SDValue N2 = N->getOperand(2);
10615
10616   // If the input vector is a concatenation, and the insert replaces
10617   // one of the halves, we can optimize into a single concat_vectors.
10618   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10619       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10620     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10621     EVT VT = N->getValueType(0);
10622
10623     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10624     // (concat_vectors Z, Y)
10625     if (InsIdx == 0)
10626       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10627                          N->getOperand(1), N0.getOperand(1));
10628
10629     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10630     // (concat_vectors X, Z)
10631     if (InsIdx == VT.getVectorNumElements()/2)
10632       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10633                          N0.getOperand(0), N->getOperand(1));
10634   }
10635
10636   return SDValue();
10637 }
10638
10639 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10640 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10641 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10642 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10643 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10644   EVT VT = N->getValueType(0);
10645   SDLoc dl(N);
10646   SDValue LHS = N->getOperand(0);
10647   SDValue RHS = N->getOperand(1);
10648   if (N->getOpcode() == ISD::AND) {
10649     if (RHS.getOpcode() == ISD::BITCAST)
10650       RHS = RHS.getOperand(0);
10651     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10652       SmallVector<int, 8> Indices;
10653       unsigned NumElts = RHS.getNumOperands();
10654       for (unsigned i = 0; i != NumElts; ++i) {
10655         SDValue Elt = RHS.getOperand(i);
10656         if (!isa<ConstantSDNode>(Elt))
10657           return SDValue();
10658
10659         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10660           Indices.push_back(i);
10661         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10662           Indices.push_back(NumElts);
10663         else
10664           return SDValue();
10665       }
10666
10667       // Let's see if the target supports this vector_shuffle.
10668       EVT RVT = RHS.getValueType();
10669       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10670         return SDValue();
10671
10672       // Return the new VECTOR_SHUFFLE node.
10673       EVT EltVT = RVT.getVectorElementType();
10674       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10675                                      DAG.getConstant(0, EltVT));
10676       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10677                                  RVT, &ZeroOps[0], ZeroOps.size());
10678       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10679       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10680       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10681     }
10682   }
10683
10684   return SDValue();
10685 }
10686
10687 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10688 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10689   assert(N->getValueType(0).isVector() &&
10690          "SimplifyVBinOp only works on vectors!");
10691
10692   SDValue LHS = N->getOperand(0);
10693   SDValue RHS = N->getOperand(1);
10694   SDValue Shuffle = XformToShuffleWithZero(N);
10695   if (Shuffle.getNode()) return Shuffle;
10696
10697   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10698   // this operation.
10699   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10700       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10701     // Check if both vectors are constants. If not bail out.
10702     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10703           cast<BuildVectorSDNode>(RHS)->isConstant()))
10704       return SDValue();
10705
10706     SmallVector<SDValue, 8> Ops;
10707     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10708       SDValue LHSOp = LHS.getOperand(i);
10709       SDValue RHSOp = RHS.getOperand(i);
10710
10711       // Can't fold divide by zero.
10712       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10713           N->getOpcode() == ISD::FDIV) {
10714         if ((RHSOp.getOpcode() == ISD::Constant &&
10715              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10716             (RHSOp.getOpcode() == ISD::ConstantFP &&
10717              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10718           break;
10719       }
10720
10721       EVT VT = LHSOp.getValueType();
10722       EVT RVT = RHSOp.getValueType();
10723       if (RVT != VT) {
10724         // Integer BUILD_VECTOR operands may have types larger than the element
10725         // size (e.g., when the element type is not legal).  Prior to type
10726         // legalization, the types may not match between the two BUILD_VECTORS.
10727         // Truncate one of the operands to make them match.
10728         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10729           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10730         } else {
10731           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10732           VT = RVT;
10733         }
10734       }
10735       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10736                                    LHSOp, RHSOp);
10737       if (FoldOp.getOpcode() != ISD::UNDEF &&
10738           FoldOp.getOpcode() != ISD::Constant &&
10739           FoldOp.getOpcode() != ISD::ConstantFP)
10740         break;
10741       Ops.push_back(FoldOp);
10742       AddToWorkList(FoldOp.getNode());
10743     }
10744
10745     if (Ops.size() == LHS.getNumOperands())
10746       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10747                          LHS.getValueType(), &Ops[0], Ops.size());
10748   }
10749
10750   return SDValue();
10751 }
10752
10753 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10754 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10755   assert(N->getValueType(0).isVector() &&
10756          "SimplifyVUnaryOp only works on vectors!");
10757
10758   SDValue N0 = N->getOperand(0);
10759
10760   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10761     return SDValue();
10762
10763   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10764   SmallVector<SDValue, 8> Ops;
10765   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10766     SDValue Op = N0.getOperand(i);
10767     if (Op.getOpcode() != ISD::UNDEF &&
10768         Op.getOpcode() != ISD::ConstantFP)
10769       break;
10770     EVT EltVT = Op.getValueType();
10771     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10772     if (FoldOp.getOpcode() != ISD::UNDEF &&
10773         FoldOp.getOpcode() != ISD::ConstantFP)
10774       break;
10775     Ops.push_back(FoldOp);
10776     AddToWorkList(FoldOp.getNode());
10777   }
10778
10779   if (Ops.size() != N0.getNumOperands())
10780     return SDValue();
10781
10782   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10783                      N0.getValueType(), &Ops[0], Ops.size());
10784 }
10785
10786 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10787                                     SDValue N1, SDValue N2){
10788   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10789
10790   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10791                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10792
10793   // If we got a simplified select_cc node back from SimplifySelectCC, then
10794   // break it down into a new SETCC node, and a new SELECT node, and then return
10795   // the SELECT node, since we were called with a SELECT node.
10796   if (SCC.getNode()) {
10797     // Check to see if we got a select_cc back (to turn into setcc/select).
10798     // Otherwise, just return whatever node we got back, like fabs.
10799     if (SCC.getOpcode() == ISD::SELECT_CC) {
10800       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10801                                   N0.getValueType(),
10802                                   SCC.getOperand(0), SCC.getOperand(1),
10803                                   SCC.getOperand(4));
10804       AddToWorkList(SETCC.getNode());
10805       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10806                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10807     }
10808
10809     return SCC;
10810   }
10811   return SDValue();
10812 }
10813
10814 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10815 /// are the two values being selected between, see if we can simplify the
10816 /// select.  Callers of this should assume that TheSelect is deleted if this
10817 /// returns true.  As such, they should return the appropriate thing (e.g. the
10818 /// node) back to the top-level of the DAG combiner loop to avoid it being
10819 /// looked at.
10820 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10821                                     SDValue RHS) {
10822
10823   // Cannot simplify select with vector condition
10824   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10825
10826   // If this is a select from two identical things, try to pull the operation
10827   // through the select.
10828   if (LHS.getOpcode() != RHS.getOpcode() ||
10829       !LHS.hasOneUse() || !RHS.hasOneUse())
10830     return false;
10831
10832   // If this is a load and the token chain is identical, replace the select
10833   // of two loads with a load through a select of the address to load from.
10834   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10835   // constants have been dropped into the constant pool.
10836   if (LHS.getOpcode() == ISD::LOAD) {
10837     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10838     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10839
10840     // Token chains must be identical.
10841     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10842         // Do not let this transformation reduce the number of volatile loads.
10843         LLD->isVolatile() || RLD->isVolatile() ||
10844         // If this is an EXTLOAD, the VT's must match.
10845         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10846         // If this is an EXTLOAD, the kind of extension must match.
10847         (LLD->getExtensionType() != RLD->getExtensionType() &&
10848          // The only exception is if one of the extensions is anyext.
10849          LLD->getExtensionType() != ISD::EXTLOAD &&
10850          RLD->getExtensionType() != ISD::EXTLOAD) ||
10851         // FIXME: this discards src value information.  This is
10852         // over-conservative. It would be beneficial to be able to remember
10853         // both potential memory locations.  Since we are discarding
10854         // src value info, don't do the transformation if the memory
10855         // locations are not in the default address space.
10856         LLD->getPointerInfo().getAddrSpace() != 0 ||
10857         RLD->getPointerInfo().getAddrSpace() != 0 ||
10858         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10859                                       LLD->getBasePtr().getValueType()))
10860       return false;
10861
10862     // Check that the select condition doesn't reach either load.  If so,
10863     // folding this will induce a cycle into the DAG.  If not, this is safe to
10864     // xform, so create a select of the addresses.
10865     SDValue Addr;
10866     if (TheSelect->getOpcode() == ISD::SELECT) {
10867       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10868       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10869           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10870         return false;
10871       // The loads must not depend on one another.
10872       if (LLD->isPredecessorOf(RLD) ||
10873           RLD->isPredecessorOf(LLD))
10874         return false;
10875       Addr = DAG.getSelect(SDLoc(TheSelect),
10876                            LLD->getBasePtr().getValueType(),
10877                            TheSelect->getOperand(0), LLD->getBasePtr(),
10878                            RLD->getBasePtr());
10879     } else {  // Otherwise SELECT_CC
10880       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10881       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10882
10883       if ((LLD->hasAnyUseOfValue(1) &&
10884            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10885           (RLD->hasAnyUseOfValue(1) &&
10886            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10887         return false;
10888
10889       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10890                          LLD->getBasePtr().getValueType(),
10891                          TheSelect->getOperand(0),
10892                          TheSelect->getOperand(1),
10893                          LLD->getBasePtr(), RLD->getBasePtr(),
10894                          TheSelect->getOperand(4));
10895     }
10896
10897     SDValue Load;
10898     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10899       Load = DAG.getLoad(TheSelect->getValueType(0),
10900                          SDLoc(TheSelect),
10901                          // FIXME: Discards pointer and TBAA info.
10902                          LLD->getChain(), Addr, MachinePointerInfo(),
10903                          LLD->isVolatile(), LLD->isNonTemporal(),
10904                          LLD->isInvariant(), LLD->getAlignment());
10905     } else {
10906       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10907                             RLD->getExtensionType() : LLD->getExtensionType(),
10908                             SDLoc(TheSelect),
10909                             TheSelect->getValueType(0),
10910                             // FIXME: Discards pointer and TBAA info.
10911                             LLD->getChain(), Addr, MachinePointerInfo(),
10912                             LLD->getMemoryVT(), LLD->isVolatile(),
10913                             LLD->isNonTemporal(), LLD->getAlignment());
10914     }
10915
10916     // Users of the select now use the result of the load.
10917     CombineTo(TheSelect, Load);
10918
10919     // Users of the old loads now use the new load's chain.  We know the
10920     // old-load value is dead now.
10921     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10922     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10923     return true;
10924   }
10925
10926   return false;
10927 }
10928
10929 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10930 /// where 'cond' is the comparison specified by CC.
10931 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10932                                       SDValue N2, SDValue N3,
10933                                       ISD::CondCode CC, bool NotExtCompare) {
10934   // (x ? y : y) -> y.
10935   if (N2 == N3) return N2;
10936
10937   EVT VT = N2.getValueType();
10938   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10939   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10940   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10941
10942   // Determine if the condition we're dealing with is constant
10943   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10944                               N0, N1, CC, DL, false);
10945   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10946   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10947
10948   // fold select_cc true, x, y -> x
10949   if (SCCC && !SCCC->isNullValue())
10950     return N2;
10951   // fold select_cc false, x, y -> y
10952   if (SCCC && SCCC->isNullValue())
10953     return N3;
10954
10955   // Check to see if we can simplify the select into an fabs node
10956   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10957     // Allow either -0.0 or 0.0
10958     if (CFP->getValueAPF().isZero()) {
10959       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10960       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10961           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10962           N2 == N3.getOperand(0))
10963         return DAG.getNode(ISD::FABS, DL, VT, N0);
10964
10965       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10966       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10967           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10968           N2.getOperand(0) == N3)
10969         return DAG.getNode(ISD::FABS, DL, VT, N3);
10970     }
10971   }
10972
10973   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10974   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10975   // in it.  This is a win when the constant is not otherwise available because
10976   // it replaces two constant pool loads with one.  We only do this if the FP
10977   // type is known to be legal, because if it isn't, then we are before legalize
10978   // types an we want the other legalization to happen first (e.g. to avoid
10979   // messing with soft float) and if the ConstantFP is not legal, because if
10980   // it is legal, we may not need to store the FP constant in a constant pool.
10981   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10982     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10983       if (TLI.isTypeLegal(N2.getValueType()) &&
10984           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10985            TargetLowering::Legal) &&
10986           // If both constants have multiple uses, then we won't need to do an
10987           // extra load, they are likely around in registers for other users.
10988           (TV->hasOneUse() || FV->hasOneUse())) {
10989         Constant *Elts[] = {
10990           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10991           const_cast<ConstantFP*>(TV->getConstantFPValue())
10992         };
10993         Type *FPTy = Elts[0]->getType();
10994         const DataLayout &TD = *TLI.getDataLayout();
10995
10996         // Create a ConstantArray of the two constants.
10997         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10998         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10999                                             TD.getPrefTypeAlignment(FPTy));
11000         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11001
11002         // Get the offsets to the 0 and 1 element of the array so that we can
11003         // select between them.
11004         SDValue Zero = DAG.getIntPtrConstant(0);
11005         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11006         SDValue One = DAG.getIntPtrConstant(EltSize);
11007
11008         SDValue Cond = DAG.getSetCC(DL,
11009                                     getSetCCResultType(N0.getValueType()),
11010                                     N0, N1, CC);
11011         AddToWorkList(Cond.getNode());
11012         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11013                                           Cond, One, Zero);
11014         AddToWorkList(CstOffset.getNode());
11015         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11016                             CstOffset);
11017         AddToWorkList(CPIdx.getNode());
11018         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11019                            MachinePointerInfo::getConstantPool(), false,
11020                            false, false, Alignment);
11021
11022       }
11023     }
11024
11025   // Check to see if we can perform the "gzip trick", transforming
11026   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11027   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11028       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11029        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11030     EVT XType = N0.getValueType();
11031     EVT AType = N2.getValueType();
11032     if (XType.bitsGE(AType)) {
11033       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11034       // single-bit constant.
11035       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11036         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11037         ShCtV = XType.getSizeInBits()-ShCtV-1;
11038         SDValue ShCt = DAG.getConstant(ShCtV,
11039                                        getShiftAmountTy(N0.getValueType()));
11040         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11041                                     XType, N0, ShCt);
11042         AddToWorkList(Shift.getNode());
11043
11044         if (XType.bitsGT(AType)) {
11045           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11046           AddToWorkList(Shift.getNode());
11047         }
11048
11049         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11050       }
11051
11052       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11053                                   XType, N0,
11054                                   DAG.getConstant(XType.getSizeInBits()-1,
11055                                          getShiftAmountTy(N0.getValueType())));
11056       AddToWorkList(Shift.getNode());
11057
11058       if (XType.bitsGT(AType)) {
11059         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11060         AddToWorkList(Shift.getNode());
11061       }
11062
11063       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11064     }
11065   }
11066
11067   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11068   // where y is has a single bit set.
11069   // A plaintext description would be, we can turn the SELECT_CC into an AND
11070   // when the condition can be materialized as an all-ones register.  Any
11071   // single bit-test can be materialized as an all-ones register with
11072   // shift-left and shift-right-arith.
11073   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11074       N0->getValueType(0) == VT &&
11075       N1C && N1C->isNullValue() &&
11076       N2C && N2C->isNullValue()) {
11077     SDValue AndLHS = N0->getOperand(0);
11078     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11079     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11080       // Shift the tested bit over the sign bit.
11081       APInt AndMask = ConstAndRHS->getAPIntValue();
11082       SDValue ShlAmt =
11083         DAG.getConstant(AndMask.countLeadingZeros(),
11084                         getShiftAmountTy(AndLHS.getValueType()));
11085       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11086
11087       // Now arithmetic right shift it all the way over, so the result is either
11088       // all-ones, or zero.
11089       SDValue ShrAmt =
11090         DAG.getConstant(AndMask.getBitWidth()-1,
11091                         getShiftAmountTy(Shl.getValueType()));
11092       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11093
11094       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11095     }
11096   }
11097
11098   // fold select C, 16, 0 -> shl C, 4
11099   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11100     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11101       TargetLowering::ZeroOrOneBooleanContent) {
11102
11103     // If the caller doesn't want us to simplify this into a zext of a compare,
11104     // don't do it.
11105     if (NotExtCompare && N2C->getAPIntValue() == 1)
11106       return SDValue();
11107
11108     // Get a SetCC of the condition
11109     // NOTE: Don't create a SETCC if it's not legal on this target.
11110     if (!LegalOperations ||
11111         TLI.isOperationLegal(ISD::SETCC,
11112           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11113       SDValue Temp, SCC;
11114       // cast from setcc result type to select result type
11115       if (LegalTypes) {
11116         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11117                             N0, N1, CC);
11118         if (N2.getValueType().bitsLT(SCC.getValueType()))
11119           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11120                                         N2.getValueType());
11121         else
11122           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11123                              N2.getValueType(), SCC);
11124       } else {
11125         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11126         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11127                            N2.getValueType(), SCC);
11128       }
11129
11130       AddToWorkList(SCC.getNode());
11131       AddToWorkList(Temp.getNode());
11132
11133       if (N2C->getAPIntValue() == 1)
11134         return Temp;
11135
11136       // shl setcc result by log2 n2c
11137       return DAG.getNode(
11138           ISD::SHL, DL, N2.getValueType(), Temp,
11139           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11140                           getShiftAmountTy(Temp.getValueType())));
11141     }
11142   }
11143
11144   // Check to see if this is the equivalent of setcc
11145   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11146   // otherwise, go ahead with the folds.
11147   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11148     EVT XType = N0.getValueType();
11149     if (!LegalOperations ||
11150         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11151       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11152       if (Res.getValueType() != VT)
11153         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11154       return Res;
11155     }
11156
11157     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11158     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11159         (!LegalOperations ||
11160          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11161       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11162       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11163                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11164                                        getShiftAmountTy(Ctlz.getValueType())));
11165     }
11166     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11167     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11168       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11169                                   XType, DAG.getConstant(0, XType), N0);
11170       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11171       return DAG.getNode(ISD::SRL, DL, XType,
11172                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11173                          DAG.getConstant(XType.getSizeInBits()-1,
11174                                          getShiftAmountTy(XType)));
11175     }
11176     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11177     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11178       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11179                                  DAG.getConstant(XType.getSizeInBits()-1,
11180                                          getShiftAmountTy(N0.getValueType())));
11181       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11182     }
11183   }
11184
11185   // Check to see if this is an integer abs.
11186   // select_cc setg[te] X,  0,  X, -X ->
11187   // select_cc setgt    X, -1,  X, -X ->
11188   // select_cc setl[te] X,  0, -X,  X ->
11189   // select_cc setlt    X,  1, -X,  X ->
11190   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11191   if (N1C) {
11192     ConstantSDNode *SubC = nullptr;
11193     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11194          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11195         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11196       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11197     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11198               (N1C->isOne() && CC == ISD::SETLT)) &&
11199              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11200       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11201
11202     EVT XType = N0.getValueType();
11203     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11204       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11205                                   N0,
11206                                   DAG.getConstant(XType.getSizeInBits()-1,
11207                                          getShiftAmountTy(N0.getValueType())));
11208       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11209                                 XType, N0, Shift);
11210       AddToWorkList(Shift.getNode());
11211       AddToWorkList(Add.getNode());
11212       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11213     }
11214   }
11215
11216   return SDValue();
11217 }
11218
11219 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11220 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11221                                    SDValue N1, ISD::CondCode Cond,
11222                                    SDLoc DL, bool foldBooleans) {
11223   TargetLowering::DAGCombinerInfo
11224     DagCombineInfo(DAG, Level, false, this);
11225   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11226 }
11227
11228 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11229 /// return a DAG expression to select that will generate the same value by
11230 /// multiplying by a magic number.  See:
11231 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11232 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11233   std::vector<SDNode*> Built;
11234   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11235
11236   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11237        ii != ee; ++ii)
11238     AddToWorkList(*ii);
11239   return S;
11240 }
11241
11242 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11243 /// return a DAG expression to select that will generate the same value by
11244 /// multiplying by a magic number.  See:
11245 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11246 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11247   std::vector<SDNode*> Built;
11248   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11249
11250   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11251        ii != ee; ++ii)
11252     AddToWorkList(*ii);
11253   return S;
11254 }
11255
11256 /// FindBaseOffset - Return true if base is a frame index, which is known not
11257 // to alias with anything but itself.  Provides base object and offset as
11258 // results.
11259 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11260                            const GlobalValue *&GV, const void *&CV) {
11261   // Assume it is a primitive operation.
11262   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11263
11264   // If it's an adding a simple constant then integrate the offset.
11265   if (Base.getOpcode() == ISD::ADD) {
11266     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11267       Base = Base.getOperand(0);
11268       Offset += C->getZExtValue();
11269     }
11270   }
11271
11272   // Return the underlying GlobalValue, and update the Offset.  Return false
11273   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11274   // by multiple nodes with different offsets.
11275   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11276     GV = G->getGlobal();
11277     Offset += G->getOffset();
11278     return false;
11279   }
11280
11281   // Return the underlying Constant value, and update the Offset.  Return false
11282   // for ConstantSDNodes since the same constant pool entry may be represented
11283   // by multiple nodes with different offsets.
11284   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11285     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11286                                          : (const void *)C->getConstVal();
11287     Offset += C->getOffset();
11288     return false;
11289   }
11290   // If it's any of the following then it can't alias with anything but itself.
11291   return isa<FrameIndexSDNode>(Base);
11292 }
11293
11294 /// isAlias - Return true if there is any possibility that the two addresses
11295 /// overlap.
11296 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11297                           const Value *SrcValue1, int SrcValueOffset1,
11298                           unsigned SrcValueAlign1,
11299                           const MDNode *TBAAInfo1,
11300                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11301                           const Value *SrcValue2, int SrcValueOffset2,
11302                           unsigned SrcValueAlign2,
11303                           const MDNode *TBAAInfo2) const {
11304   // If they are the same then they must be aliases.
11305   if (Ptr1 == Ptr2) return true;
11306
11307   // If they are both volatile then they cannot be reordered.
11308   if (IsVolatile1 && IsVolatile2) return true;
11309
11310   // Gather base node and offset information.
11311   SDValue Base1, Base2;
11312   int64_t Offset1, Offset2;
11313   const GlobalValue *GV1, *GV2;
11314   const void *CV1, *CV2;
11315   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11316   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11317
11318   // If they have a same base address then check to see if they overlap.
11319   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11320     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11321
11322   // It is possible for different frame indices to alias each other, mostly
11323   // when tail call optimization reuses return address slots for arguments.
11324   // To catch this case, look up the actual index of frame indices to compute
11325   // the real alias relationship.
11326   if (isFrameIndex1 && isFrameIndex2) {
11327     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11328     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11329     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11330     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11331   }
11332
11333   // Otherwise, if we know what the bases are, and they aren't identical, then
11334   // we know they cannot alias.
11335   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11336     return false;
11337
11338   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11339   // compared to the size and offset of the access, we may be able to prove they
11340   // do not alias.  This check is conservative for now to catch cases created by
11341   // splitting vector types.
11342   if ((SrcValueAlign1 == SrcValueAlign2) &&
11343       (SrcValueOffset1 != SrcValueOffset2) &&
11344       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11345     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11346     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11347
11348     // There is no overlap between these relatively aligned accesses of similar
11349     // size, return no alias.
11350     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11351       return false;
11352   }
11353
11354   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11355     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11356 #ifndef NDEBUG
11357   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11358       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11359     UseAA = false;
11360 #endif
11361   if (UseAA && SrcValue1 && SrcValue2) {
11362     // Use alias analysis information.
11363     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11364     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11365     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11366     AliasAnalysis::AliasResult AAResult =
11367       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11368                                        UseTBAA ? TBAAInfo1 : nullptr),
11369                AliasAnalysis::Location(SrcValue2, Overlap2,
11370                                        UseTBAA ? TBAAInfo2 : nullptr));
11371     if (AAResult == AliasAnalysis::NoAlias)
11372       return false;
11373   }
11374
11375   // Otherwise we have to assume they alias.
11376   return true;
11377 }
11378
11379 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11380   SDValue Ptr0, Ptr1;
11381   int64_t Size0, Size1;
11382   bool IsVolatile0, IsVolatile1;
11383   const Value *SrcValue0, *SrcValue1;
11384   int SrcValueOffset0, SrcValueOffset1;
11385   unsigned SrcValueAlign0, SrcValueAlign1;
11386   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11387   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11388                 SrcValueAlign0, SrcTBAAInfo0);
11389   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11390                 SrcValueAlign1, SrcTBAAInfo1);
11391   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11392                  SrcValueAlign0, SrcTBAAInfo0,
11393                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11394                  SrcValueAlign1, SrcTBAAInfo1);
11395 }
11396
11397 /// FindAliasInfo - Extracts the relevant alias information from the memory
11398 /// node.  Returns true if the operand was a nonvolatile load.
11399 bool DAGCombiner::FindAliasInfo(SDNode *N,
11400                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11401                                 const Value *&SrcValue,
11402                                 int &SrcValueOffset,
11403                                 unsigned &SrcValueAlign,
11404                                 const MDNode *&TBAAInfo) const {
11405   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11406
11407   Ptr = LS->getBasePtr();
11408   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11409   IsVolatile = LS->isVolatile();
11410   SrcValue = LS->getSrcValue();
11411   SrcValueOffset = LS->getSrcValueOffset();
11412   SrcValueAlign = LS->getOriginalAlignment();
11413   TBAAInfo = LS->getTBAAInfo();
11414   return isa<LoadSDNode>(LS) && !IsVolatile;
11415 }
11416
11417 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11418 /// looking for aliasing nodes and adding them to the Aliases vector.
11419 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11420                                    SmallVectorImpl<SDValue> &Aliases) {
11421   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11422   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11423
11424   // Get alias information for node.
11425   SDValue Ptr;
11426   int64_t Size;
11427   bool IsVolatile;
11428   const Value *SrcValue;
11429   int SrcValueOffset;
11430   unsigned SrcValueAlign;
11431   const MDNode *SrcTBAAInfo;
11432   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11433                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11434
11435   // Starting off.
11436   Chains.push_back(OriginalChain);
11437   unsigned Depth = 0;
11438
11439   // Look at each chain and determine if it is an alias.  If so, add it to the
11440   // aliases list.  If not, then continue up the chain looking for the next
11441   // candidate.
11442   while (!Chains.empty()) {
11443     SDValue Chain = Chains.back();
11444     Chains.pop_back();
11445
11446     // For TokenFactor nodes, look at each operand and only continue up the
11447     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11448     // find more and revert to original chain since the xform is unlikely to be
11449     // profitable.
11450     //
11451     // FIXME: The depth check could be made to return the last non-aliasing
11452     // chain we found before we hit a tokenfactor rather than the original
11453     // chain.
11454     if (Depth > 6 || Aliases.size() == 2) {
11455       Aliases.clear();
11456       Aliases.push_back(OriginalChain);
11457       return;
11458     }
11459
11460     // Don't bother if we've been before.
11461     if (!Visited.insert(Chain.getNode()))
11462       continue;
11463
11464     switch (Chain.getOpcode()) {
11465     case ISD::EntryToken:
11466       // Entry token is ideal chain operand, but handled in FindBetterChain.
11467       break;
11468
11469     case ISD::LOAD:
11470     case ISD::STORE: {
11471       // Get alias information for Chain.
11472       SDValue OpPtr;
11473       int64_t OpSize;
11474       bool OpIsVolatile;
11475       const Value *OpSrcValue;
11476       int OpSrcValueOffset;
11477       unsigned OpSrcValueAlign;
11478       const MDNode *OpSrcTBAAInfo;
11479       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11480                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11481                                     OpSrcValueAlign,
11482                                     OpSrcTBAAInfo);
11483
11484       // If chain is alias then stop here.
11485       if (!(IsLoad && IsOpLoad) &&
11486           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11487                   SrcValueAlign, SrcTBAAInfo,
11488                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11489                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11490         Aliases.push_back(Chain);
11491       } else {
11492         // Look further up the chain.
11493         Chains.push_back(Chain.getOperand(0));
11494         ++Depth;
11495       }
11496       break;
11497     }
11498
11499     case ISD::TokenFactor:
11500       // We have to check each of the operands of the token factor for "small"
11501       // token factors, so we queue them up.  Adding the operands to the queue
11502       // (stack) in reverse order maintains the original order and increases the
11503       // likelihood that getNode will find a matching token factor (CSE.)
11504       if (Chain.getNumOperands() > 16) {
11505         Aliases.push_back(Chain);
11506         break;
11507       }
11508       for (unsigned n = Chain.getNumOperands(); n;)
11509         Chains.push_back(Chain.getOperand(--n));
11510       ++Depth;
11511       break;
11512
11513     default:
11514       // For all other instructions we will just have to take what we can get.
11515       Aliases.push_back(Chain);
11516       break;
11517     }
11518   }
11519
11520   // We need to be careful here to also search for aliases through the
11521   // value operand of a store, etc. Consider the following situation:
11522   //   Token1 = ...
11523   //   L1 = load Token1, %52
11524   //   S1 = store Token1, L1, %51
11525   //   L2 = load Token1, %52+8
11526   //   S2 = store Token1, L2, %51+8
11527   //   Token2 = Token(S1, S2)
11528   //   L3 = load Token2, %53
11529   //   S3 = store Token2, L3, %52
11530   //   L4 = load Token2, %53+8
11531   //   S4 = store Token2, L4, %52+8
11532   // If we search for aliases of S3 (which loads address %52), and we look
11533   // only through the chain, then we'll miss the trivial dependence on L1
11534   // (which also loads from %52). We then might change all loads and
11535   // stores to use Token1 as their chain operand, which could result in
11536   // copying %53 into %52 before copying %52 into %51 (which should
11537   // happen first).
11538   //
11539   // The problem is, however, that searching for such data dependencies
11540   // can become expensive, and the cost is not directly related to the
11541   // chain depth. Instead, we'll rule out such configurations here by
11542   // insisting that we've visited all chain users (except for users
11543   // of the original chain, which is not necessary). When doing this,
11544   // we need to look through nodes we don't care about (otherwise, things
11545   // like register copies will interfere with trivial cases).
11546
11547   SmallVector<const SDNode *, 16> Worklist;
11548   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11549        IE = Visited.end(); I != IE; ++I)
11550     if (*I != OriginalChain.getNode())
11551       Worklist.push_back(*I);
11552
11553   while (!Worklist.empty()) {
11554     const SDNode *M = Worklist.pop_back_val();
11555
11556     // We have already visited M, and want to make sure we've visited any uses
11557     // of M that we care about. For uses that we've not visisted, and don't
11558     // care about, queue them to the worklist.
11559
11560     for (SDNode::use_iterator UI = M->use_begin(),
11561          UIE = M->use_end(); UI != UIE; ++UI)
11562       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11563         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11564           // We've not visited this use, and we care about it (it could have an
11565           // ordering dependency with the original node).
11566           Aliases.clear();
11567           Aliases.push_back(OriginalChain);
11568           return;
11569         }
11570
11571         // We've not visited this use, but we don't care about it. Mark it as
11572         // visited and enqueue it to the worklist.
11573         Worklist.push_back(*UI);
11574       }
11575   }
11576 }
11577
11578 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11579 /// for a better chain (aliasing node.)
11580 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11581   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11582
11583   // Accumulate all the aliases to this node.
11584   GatherAllAliases(N, OldChain, Aliases);
11585
11586   // If no operands then chain to entry token.
11587   if (Aliases.size() == 0)
11588     return DAG.getEntryNode();
11589
11590   // If a single operand then chain to it.  We don't need to revisit it.
11591   if (Aliases.size() == 1)
11592     return Aliases[0];
11593
11594   // Construct a custom tailored token factor.
11595   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11596                      &Aliases[0], Aliases.size());
11597 }
11598
11599 // SelectionDAG::Combine - This is the entry point for the file.
11600 //
11601 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11602                            CodeGenOpt::Level OptLevel) {
11603   /// run - This is the main entry point to this class.
11604   ///
11605   DAGCombiner(*this, AA, OptLevel).Run(Level);
11606 }