[DAG] Improved target independent vector shuffle folding logic.
[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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.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 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306
307     SDValue XformToShuffleWithZero(SDNode *N);
308     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309
310     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311
312     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316                              SDValue N3, ISD::CondCode CC,
317                              bool NotExtCompare = false);
318     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319                           SDLoc DL, bool foldBooleans = true);
320
321     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322                            SDValue &CC) const;
323     bool isOneUseSetCC(SDValue N) const;
324
325     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326                                          unsigned HiOp);
327     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329     SDValue BuildSDIV(SDNode *N);
330     SDValue BuildSDIVPow2(SDNode *N);
331     SDValue BuildUDIV(SDNode *N);
332     SDValue BuildReciprocalEstimate(SDValue Op);
333     SDValue BuildRsqrtEstimate(SDValue Op);
334     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
335     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
336     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
337                                bool DemandHighBits = true);
338     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
339     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
340                               SDValue InnerPos, SDValue InnerNeg,
341                               unsigned PosOpcode, unsigned NegOpcode,
342                               SDLoc DL);
343     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
344     SDValue ReduceLoadWidth(SDNode *N);
345     SDValue ReduceLoadOpStoreWidth(SDNode *N);
346     SDValue TransformFPLoadStorePair(SDNode *N);
347     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
348     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
349
350     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
351
352     /// Walk up chain skipping non-aliasing memory nodes,
353     /// looking for aliasing nodes and adding them to the Aliases vector.
354     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
355                           SmallVectorImpl<SDValue> &Aliases);
356
357     /// Return true if there is any possibility that the two addresses overlap.
358     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
359
360     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
361     /// chain (aliasing node.)
362     SDValue FindBetterChain(SDNode *N, SDValue Chain);
363
364     /// Merge consecutive store operations into a wide store.
365     /// This optimization uses wide integers or vectors when possible.
366     /// \return True if some memory operations were changed.
367     bool MergeConsecutiveStores(StoreSDNode *N);
368
369     /// \brief Try to transform a truncation where C is a constant:
370     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
371     ///
372     /// \p N needs to be a truncation and its first operand an AND. Other
373     /// requirements are checked by the function (e.g. that trunc is
374     /// single-use) and if missed an empty SDValue is returned.
375     SDValue distributeTruncateThroughAnd(SDNode *N);
376
377   public:
378     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
379         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
380           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
381       AttributeSet FnAttrs =
382           DAG.getMachineFunction().getFunction()->getAttributes();
383       ForCodeSize =
384           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
385                                Attribute::OptimizeForSize) ||
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
387     }
388
389     /// Runs the dag combiner on all nodes in the work list
390     void Run(CombineLevel AtLevel);
391
392     SelectionDAG &getDAG() const { return DAG; }
393
394     /// Returns a type large enough to hold any valid shift amount - before type
395     /// legalization these can be huge.
396     EVT getShiftAmountTy(EVT LHSTy) {
397       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
398       if (LHSTy.isVector())
399         return LHSTy;
400       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
401                         : TLI.getPointerTy();
402     }
403
404     /// This method returns true if we are running before type legalization or
405     /// if the specified VT is legal.
406     bool isTypeLegal(const EVT &VT) {
407       if (!LegalTypes) return true;
408       return TLI.isTypeLegal(VT);
409     }
410
411     /// Convenience wrapper around TargetLowering::getSetCCResultType
412     EVT getSetCCResultType(EVT VT) const {
413       return TLI.getSetCCResultType(*DAG.getContext(), VT);
414     }
415   };
416 }
417
418
419 namespace {
420 /// This class is a DAGUpdateListener that removes any deleted
421 /// nodes from the worklist.
422 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
423   DAGCombiner &DC;
424 public:
425   explicit WorklistRemover(DAGCombiner &dc)
426     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
427
428   void NodeDeleted(SDNode *N, SDNode *E) override {
429     DC.removeFromWorklist(N);
430   }
431 };
432 }
433
434 //===----------------------------------------------------------------------===//
435 //  TargetLowering::DAGCombinerInfo implementation
436 //===----------------------------------------------------------------------===//
437
438 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
439   ((DAGCombiner*)DC)->AddToWorklist(N);
440 }
441
442 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
443   ((DAGCombiner*)DC)->removeFromWorklist(N);
444 }
445
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
448   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
449 }
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
454 }
455
456
457 SDValue TargetLowering::DAGCombinerInfo::
458 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
459   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
460 }
461
462 void TargetLowering::DAGCombinerInfo::
463 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
464   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
465 }
466
467 //===----------------------------------------------------------------------===//
468 // Helper Functions
469 //===----------------------------------------------------------------------===//
470
471 void DAGCombiner::deleteAndRecombine(SDNode *N) {
472   removeFromWorklist(N);
473
474   // If the operands of this node are only used by the node, they will now be
475   // dead. Make sure to re-visit them and recursively delete dead nodes.
476   for (const SDValue &Op : N->ops())
477     // For an operand generating multiple values, one of the values may
478     // become dead allowing further simplification (e.g. split index
479     // arithmetic from an indexed load).
480     if (Op->hasOneUse() || Op->getNumValues() > 1)
481       AddToWorklist(Op.getNode());
482
483   DAG.DeleteNode(N);
484 }
485
486 /// Return 1 if we can compute the negated form of the specified expression for
487 /// the same cost as the expression itself, or 2 if we can compute the negated
488 /// form more cheaply than the expression itself.
489 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
490                                const TargetLowering &TLI,
491                                const TargetOptions *Options,
492                                unsigned Depth = 0) {
493   // fneg is removable even if it has multiple uses.
494   if (Op.getOpcode() == ISD::FNEG) return 2;
495
496   // Don't allow anything with multiple uses.
497   if (!Op.hasOneUse()) return 0;
498
499   // Don't recurse exponentially.
500   if (Depth > 6) return 0;
501
502   switch (Op.getOpcode()) {
503   default: return false;
504   case ISD::ConstantFP:
505     // Don't invert constant FP values after legalize.  The negated constant
506     // isn't necessarily legal.
507     return LegalOperations ? 0 : 1;
508   case ISD::FADD:
509     // FIXME: determine better conditions for this xform.
510     if (!Options->UnsafeFPMath) return 0;
511
512     // After operation legalization, it might not be legal to create new FSUBs.
513     if (LegalOperations &&
514         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
515       return 0;
516
517     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
518     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
519                                     Options, Depth + 1))
520       return V;
521     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
522     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
523                               Depth + 1);
524   case ISD::FSUB:
525     // We can't turn -(A-B) into B-A when we honor signed zeros.
526     if (!Options->UnsafeFPMath) return 0;
527
528     // fold (fneg (fsub A, B)) -> (fsub B, A)
529     return 1;
530
531   case ISD::FMUL:
532   case ISD::FDIV:
533     if (Options->HonorSignDependentRoundingFPMath()) return 0;
534
535     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
536     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
537                                     Options, Depth + 1))
538       return V;
539
540     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
541                               Depth + 1);
542
543   case ISD::FP_EXTEND:
544   case ISD::FP_ROUND:
545   case ISD::FSIN:
546     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
547                               Depth + 1);
548   }
549 }
550
551 /// If isNegatibleForFree returns true, return the newly negated expression.
552 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
553                                     bool LegalOperations, unsigned Depth = 0) {
554   const TargetOptions &Options = DAG.getTarget().Options;
555   // fneg is removable even if it has multiple uses.
556   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
557
558   // Don't allow anything with multiple uses.
559   assert(Op.hasOneUse() && "Unknown reuse!");
560
561   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
562   switch (Op.getOpcode()) {
563   default: llvm_unreachable("Unknown code");
564   case ISD::ConstantFP: {
565     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
566     V.changeSign();
567     return DAG.getConstantFP(V, Op.getValueType());
568   }
569   case ISD::FADD:
570     // FIXME: determine better conditions for this xform.
571     assert(Options.UnsafeFPMath);
572
573     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
574     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
575                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
576       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
577                          GetNegatedExpression(Op.getOperand(0), DAG,
578                                               LegalOperations, Depth+1),
579                          Op.getOperand(1));
580     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
582                        GetNegatedExpression(Op.getOperand(1), DAG,
583                                             LegalOperations, Depth+1),
584                        Op.getOperand(0));
585   case ISD::FSUB:
586     // We can't turn -(A-B) into B-A when we honor signed zeros.
587     assert(Options.UnsafeFPMath);
588
589     // fold (fneg (fsub 0, B)) -> B
590     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
591       if (N0CFP->getValueAPF().isZero())
592         return Op.getOperand(1);
593
594     // fold (fneg (fsub A, B)) -> (fsub B, A)
595     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
596                        Op.getOperand(1), Op.getOperand(0));
597
598   case ISD::FMUL:
599   case ISD::FDIV:
600     assert(!Options.HonorSignDependentRoundingFPMath());
601
602     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
603     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
604                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
605       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606                          GetNegatedExpression(Op.getOperand(0), DAG,
607                                               LegalOperations, Depth+1),
608                          Op.getOperand(1));
609
610     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        Op.getOperand(0),
613                        GetNegatedExpression(Op.getOperand(1), DAG,
614                                             LegalOperations, Depth+1));
615
616   case ISD::FP_EXTEND:
617   case ISD::FSIN:
618     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
619                        GetNegatedExpression(Op.getOperand(0), DAG,
620                                             LegalOperations, Depth+1));
621   case ISD::FP_ROUND:
622       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
623                          GetNegatedExpression(Op.getOperand(0), DAG,
624                                               LegalOperations, Depth+1),
625                          Op.getOperand(1));
626   }
627 }
628
629 // Return true if this node is a setcc, or is a select_cc
630 // that selects between the target values used for true and false, making it
631 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
632 // the appropriate nodes based on the type of node we are checking. This
633 // simplifies life a bit for the callers.
634 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
635                                     SDValue &CC) const {
636   if (N.getOpcode() == ISD::SETCC) {
637     LHS = N.getOperand(0);
638     RHS = N.getOperand(1);
639     CC  = N.getOperand(2);
640     return true;
641   }
642
643   if (N.getOpcode() != ISD::SELECT_CC ||
644       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
645       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
646     return false;
647
648   LHS = N.getOperand(0);
649   RHS = N.getOperand(1);
650   CC  = N.getOperand(4);
651   return true;
652 }
653
654 /// Return true if this is a SetCC-equivalent operation with only one use.
655 /// If this is true, it allows the users to invert the operation for free when
656 /// it is profitable to do so.
657 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
658   SDValue N0, N1, N2;
659   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
660     return true;
661   return false;
662 }
663
664 /// Returns true if N is a BUILD_VECTOR node whose
665 /// elements are all the same constant or undefined.
666 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
667   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
668   if (!C)
669     return false;
670
671   APInt SplatUndef;
672   unsigned SplatBitSize;
673   bool HasAnyUndefs;
674   EVT EltVT = N->getValueType(0).getVectorElementType();
675   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
676                              HasAnyUndefs) &&
677           EltVT.getSizeInBits() >= SplatBitSize);
678 }
679
680 // \brief Returns the SDNode if it is a constant BuildVector or constant.
681 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
682   if (isa<ConstantSDNode>(N))
683     return N.getNode();
684   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
685   if (BV && BV->isConstant())
686     return BV;
687   return nullptr;
688 }
689
690 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
691 // int.
692 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
693   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
694     return CN;
695
696   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
697     BitVector UndefElements;
698     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
699
700     // BuildVectors can truncate their operands. Ignore that case here.
701     // FIXME: We blindly ignore splats which include undef which is overly
702     // pessimistic.
703     if (CN && UndefElements.none() &&
704         CN->getValueType(0) == N.getValueType().getScalarType())
705       return CN;
706   }
707
708   return nullptr;
709 }
710
711 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
712 // float.
713 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
714   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
715     return CN;
716
717   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
718     BitVector UndefElements;
719     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
720
721     if (CN && UndefElements.none())
722       return CN;
723   }
724
725   return nullptr;
726 }
727
728 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
729                                     SDValue N0, SDValue N1) {
730   EVT VT = N0.getValueType();
731   if (N0.getOpcode() == Opc) {
732     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
733       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
734         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
735         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
736         if (!OpNode.getNode())
737           return SDValue();
738         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
739       }
740       if (N0.hasOneUse()) {
741         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
742         // use
743         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
744         if (!OpNode.getNode())
745           return SDValue();
746         AddToWorklist(OpNode.getNode());
747         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
748       }
749     }
750   }
751
752   if (N1.getOpcode() == Opc) {
753     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
754       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
755         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
756         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
757         if (!OpNode.getNode())
758           return SDValue();
759         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
760       }
761       if (N1.hasOneUse()) {
762         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
763         // use
764         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
765         if (!OpNode.getNode())
766           return SDValue();
767         AddToWorklist(OpNode.getNode());
768         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
769       }
770     }
771   }
772
773   return SDValue();
774 }
775
776 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
777                                bool AddTo) {
778   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
779   ++NodesCombined;
780   DEBUG(dbgs() << "\nReplacing.1 ";
781         N->dump(&DAG);
782         dbgs() << "\nWith: ";
783         To[0].getNode()->dump(&DAG);
784         dbgs() << " and " << NumTo-1 << " other values\n";
785         for (unsigned i = 0, e = NumTo; i != e; ++i)
786           assert((!To[i].getNode() ||
787                   N->getValueType(i) == To[i].getValueType()) &&
788                  "Cannot combine value to value of different type!"));
789   WorklistRemover DeadNodes(*this);
790   DAG.ReplaceAllUsesWith(N, To);
791   if (AddTo) {
792     // Push the new nodes and any users onto the worklist
793     for (unsigned i = 0, e = NumTo; i != e; ++i) {
794       if (To[i].getNode()) {
795         AddToWorklist(To[i].getNode());
796         AddUsersToWorklist(To[i].getNode());
797       }
798     }
799   }
800
801   // Finally, if the node is now dead, remove it from the graph.  The node
802   // may not be dead if the replacement process recursively simplified to
803   // something else needing this node.
804   if (N->use_empty())
805     deleteAndRecombine(N);
806   return SDValue(N, 0);
807 }
808
809 void DAGCombiner::
810 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
811   // Replace all uses.  If any nodes become isomorphic to other nodes and
812   // are deleted, make sure to remove them from our worklist.
813   WorklistRemover DeadNodes(*this);
814   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
815
816   // Push the new node and any (possibly new) users onto the worklist.
817   AddToWorklist(TLO.New.getNode());
818   AddUsersToWorklist(TLO.New.getNode());
819
820   // Finally, if the node is now dead, remove it from the graph.  The node
821   // may not be dead if the replacement process recursively simplified to
822   // something else needing this node.
823   if (TLO.Old.getNode()->use_empty())
824     deleteAndRecombine(TLO.Old.getNode());
825 }
826
827 /// Check the specified integer node value to see if it can be simplified or if
828 /// things it uses can be simplified by bit propagation. If so, return true.
829 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
830   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
831   APInt KnownZero, KnownOne;
832   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
833     return false;
834
835   // Revisit the node.
836   AddToWorklist(Op.getNode());
837
838   // Replace the old value with the new one.
839   ++NodesCombined;
840   DEBUG(dbgs() << "\nReplacing.2 ";
841         TLO.Old.getNode()->dump(&DAG);
842         dbgs() << "\nWith: ";
843         TLO.New.getNode()->dump(&DAG);
844         dbgs() << '\n');
845
846   CommitTargetLoweringOpt(TLO);
847   return true;
848 }
849
850 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
851   SDLoc dl(Load);
852   EVT VT = Load->getValueType(0);
853   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
854
855   DEBUG(dbgs() << "\nReplacing.9 ";
856         Load->dump(&DAG);
857         dbgs() << "\nWith: ";
858         Trunc.getNode()->dump(&DAG);
859         dbgs() << '\n');
860   WorklistRemover DeadNodes(*this);
861   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
862   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
863   deleteAndRecombine(Load);
864   AddToWorklist(Trunc.getNode());
865 }
866
867 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
868   Replace = false;
869   SDLoc dl(Op);
870   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
871     EVT MemVT = LD->getMemoryVT();
872     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
873       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
874                                                   : ISD::EXTLOAD)
875       : LD->getExtensionType();
876     Replace = true;
877     return DAG.getExtLoad(ExtType, dl, PVT,
878                           LD->getChain(), LD->getBasePtr(),
879                           MemVT, LD->getMemOperand());
880   }
881
882   unsigned Opc = Op.getOpcode();
883   switch (Opc) {
884   default: break;
885   case ISD::AssertSext:
886     return DAG.getNode(ISD::AssertSext, dl, PVT,
887                        SExtPromoteOperand(Op.getOperand(0), PVT),
888                        Op.getOperand(1));
889   case ISD::AssertZext:
890     return DAG.getNode(ISD::AssertZext, dl, PVT,
891                        ZExtPromoteOperand(Op.getOperand(0), PVT),
892                        Op.getOperand(1));
893   case ISD::Constant: {
894     unsigned ExtOpc =
895       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
896     return DAG.getNode(ExtOpc, dl, PVT, Op);
897   }
898   }
899
900   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
901     return SDValue();
902   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
903 }
904
905 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
906   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
907     return SDValue();
908   EVT OldVT = Op.getValueType();
909   SDLoc dl(Op);
910   bool Replace = false;
911   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
912   if (!NewOp.getNode())
913     return SDValue();
914   AddToWorklist(NewOp.getNode());
915
916   if (Replace)
917     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
918   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
919                      DAG.getValueType(OldVT));
920 }
921
922 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
923   EVT OldVT = Op.getValueType();
924   SDLoc dl(Op);
925   bool Replace = false;
926   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
927   if (!NewOp.getNode())
928     return SDValue();
929   AddToWorklist(NewOp.getNode());
930
931   if (Replace)
932     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
933   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
934 }
935
936 /// Promote the specified integer binary operation if the target indicates it is
937 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
938 /// i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
940   if (!LegalOperations)
941     return SDValue();
942
943   EVT VT = Op.getValueType();
944   if (VT.isVector() || !VT.isInteger())
945     return SDValue();
946
947   // If operation type is 'undesirable', e.g. i16 on x86, consider
948   // promoting it.
949   unsigned Opc = Op.getOpcode();
950   if (TLI.isTypeDesirableForOp(Opc, VT))
951     return SDValue();
952
953   EVT PVT = VT;
954   // Consult target whether it is a good idea to promote this operation and
955   // what's the right type to promote it to.
956   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957     assert(PVT != VT && "Don't know what type to promote to!");
958
959     bool Replace0 = false;
960     SDValue N0 = Op.getOperand(0);
961     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
962     if (!NN0.getNode())
963       return SDValue();
964
965     bool Replace1 = false;
966     SDValue N1 = Op.getOperand(1);
967     SDValue NN1;
968     if (N0 == N1)
969       NN1 = NN0;
970     else {
971       NN1 = PromoteOperand(N1, PVT, Replace1);
972       if (!NN1.getNode())
973         return SDValue();
974     }
975
976     AddToWorklist(NN0.getNode());
977     if (NN1.getNode())
978       AddToWorklist(NN1.getNode());
979
980     if (Replace0)
981       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
982     if (Replace1)
983       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
984
985     DEBUG(dbgs() << "\nPromoting ";
986           Op.getNode()->dump(&DAG));
987     SDLoc dl(Op);
988     return DAG.getNode(ISD::TRUNCATE, dl, VT,
989                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
990   }
991   return SDValue();
992 }
993
994 /// Promote the specified integer shift operation if the target indicates it is
995 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
996 /// i32 since i16 instructions are longer.
997 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
998   if (!LegalOperations)
999     return SDValue();
1000
1001   EVT VT = Op.getValueType();
1002   if (VT.isVector() || !VT.isInteger())
1003     return SDValue();
1004
1005   // If operation type is 'undesirable', e.g. i16 on x86, consider
1006   // promoting it.
1007   unsigned Opc = Op.getOpcode();
1008   if (TLI.isTypeDesirableForOp(Opc, VT))
1009     return SDValue();
1010
1011   EVT PVT = VT;
1012   // Consult target whether it is a good idea to promote this operation and
1013   // what's the right type to promote it to.
1014   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015     assert(PVT != VT && "Don't know what type to promote to!");
1016
1017     bool Replace = false;
1018     SDValue N0 = Op.getOperand(0);
1019     if (Opc == ISD::SRA)
1020       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1021     else if (Opc == ISD::SRL)
1022       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1023     else
1024       N0 = PromoteOperand(N0, PVT, Replace);
1025     if (!N0.getNode())
1026       return SDValue();
1027
1028     AddToWorklist(N0.getNode());
1029     if (Replace)
1030       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1031
1032     DEBUG(dbgs() << "\nPromoting ";
1033           Op.getNode()->dump(&DAG));
1034     SDLoc dl(Op);
1035     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1036                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1037   }
1038   return SDValue();
1039 }
1040
1041 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1042   if (!LegalOperations)
1043     return SDValue();
1044
1045   EVT VT = Op.getValueType();
1046   if (VT.isVector() || !VT.isInteger())
1047     return SDValue();
1048
1049   // If operation type is 'undesirable', e.g. i16 on x86, consider
1050   // promoting it.
1051   unsigned Opc = Op.getOpcode();
1052   if (TLI.isTypeDesirableForOp(Opc, VT))
1053     return SDValue();
1054
1055   EVT PVT = VT;
1056   // Consult target whether it is a good idea to promote this operation and
1057   // what's the right type to promote it to.
1058   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059     assert(PVT != VT && "Don't know what type to promote to!");
1060     // fold (aext (aext x)) -> (aext x)
1061     // fold (aext (zext x)) -> (zext x)
1062     // fold (aext (sext x)) -> (sext x)
1063     DEBUG(dbgs() << "\nPromoting ";
1064           Op.getNode()->dump(&DAG));
1065     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1066   }
1067   return SDValue();
1068 }
1069
1070 bool DAGCombiner::PromoteLoad(SDValue Op) {
1071   if (!LegalOperations)
1072     return false;
1073
1074   EVT VT = Op.getValueType();
1075   if (VT.isVector() || !VT.isInteger())
1076     return false;
1077
1078   // If operation type is 'undesirable', e.g. i16 on x86, consider
1079   // promoting it.
1080   unsigned Opc = Op.getOpcode();
1081   if (TLI.isTypeDesirableForOp(Opc, VT))
1082     return false;
1083
1084   EVT PVT = VT;
1085   // Consult target whether it is a good idea to promote this operation and
1086   // what's the right type to promote it to.
1087   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1088     assert(PVT != VT && "Don't know what type to promote to!");
1089
1090     SDLoc dl(Op);
1091     SDNode *N = Op.getNode();
1092     LoadSDNode *LD = cast<LoadSDNode>(N);
1093     EVT MemVT = LD->getMemoryVT();
1094     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1095       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1096                                                   : ISD::EXTLOAD)
1097       : LD->getExtensionType();
1098     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1099                                    LD->getChain(), LD->getBasePtr(),
1100                                    MemVT, LD->getMemOperand());
1101     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1102
1103     DEBUG(dbgs() << "\nPromoting ";
1104           N->dump(&DAG);
1105           dbgs() << "\nTo: ";
1106           Result.getNode()->dump(&DAG);
1107           dbgs() << '\n');
1108     WorklistRemover DeadNodes(*this);
1109     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1110     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1111     deleteAndRecombine(N);
1112     AddToWorklist(Result.getNode());
1113     return true;
1114   }
1115   return false;
1116 }
1117
1118 /// \brief Recursively delete a node which has no uses and any operands for
1119 /// which it is the only use.
1120 ///
1121 /// Note that this both deletes the nodes and removes them from the worklist.
1122 /// It also adds any nodes who have had a user deleted to the worklist as they
1123 /// may now have only one use and subject to other combines.
1124 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1125   if (!N->use_empty())
1126     return false;
1127
1128   SmallSetVector<SDNode *, 16> Nodes;
1129   Nodes.insert(N);
1130   do {
1131     N = Nodes.pop_back_val();
1132     if (!N)
1133       continue;
1134
1135     if (N->use_empty()) {
1136       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1137         Nodes.insert(N->getOperand(i).getNode());
1138
1139       removeFromWorklist(N);
1140       DAG.DeleteNode(N);
1141     } else {
1142       AddToWorklist(N);
1143     }
1144   } while (!Nodes.empty());
1145   return true;
1146 }
1147
1148 //===----------------------------------------------------------------------===//
1149 //  Main DAG Combiner implementation
1150 //===----------------------------------------------------------------------===//
1151
1152 void DAGCombiner::Run(CombineLevel AtLevel) {
1153   // set the instance variables, so that the various visit routines may use it.
1154   Level = AtLevel;
1155   LegalOperations = Level >= AfterLegalizeVectorOps;
1156   LegalTypes = Level >= AfterLegalizeTypes;
1157
1158   // Early exit if this basic block is in an optnone function.
1159   AttributeSet FnAttrs =
1160     DAG.getMachineFunction().getFunction()->getAttributes();
1161   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1162                            Attribute::OptimizeNone))
1163     return;
1164
1165   // Add all the dag nodes to the worklist.
1166   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1167        E = DAG.allnodes_end(); I != E; ++I)
1168     AddToWorklist(I);
1169
1170   // Create a dummy node (which is not added to allnodes), that adds a reference
1171   // to the root node, preventing it from being deleted, and tracking any
1172   // changes of the root.
1173   HandleSDNode Dummy(DAG.getRoot());
1174
1175   // while the worklist isn't empty, find a node and
1176   // try and combine it.
1177   while (!WorklistMap.empty()) {
1178     SDNode *N;
1179     // The Worklist holds the SDNodes in order, but it may contain null entries.
1180     do {
1181       N = Worklist.pop_back_val();
1182     } while (!N);
1183
1184     bool GoodWorklistEntry = WorklistMap.erase(N);
1185     (void)GoodWorklistEntry;
1186     assert(GoodWorklistEntry &&
1187            "Found a worklist entry without a corresponding map entry!");
1188
1189     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1190     // N is deleted from the DAG, since they too may now be dead or may have a
1191     // reduced number of uses, allowing other xforms.
1192     if (recursivelyDeleteUnusedNodes(N))
1193       continue;
1194
1195     WorklistRemover DeadNodes(*this);
1196
1197     // If this combine is running after legalizing the DAG, re-legalize any
1198     // nodes pulled off the worklist.
1199     if (Level == AfterLegalizeDAG) {
1200       SmallSetVector<SDNode *, 16> UpdatedNodes;
1201       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1202
1203       for (SDNode *LN : UpdatedNodes) {
1204         AddToWorklist(LN);
1205         AddUsersToWorklist(LN);
1206       }
1207       if (!NIsValid)
1208         continue;
1209     }
1210
1211     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1212
1213     // Add any operands of the new node which have not yet been combined to the
1214     // worklist as well. Because the worklist uniques things already, this
1215     // won't repeatedly process the same operand.
1216     CombinedNodes.insert(N);
1217     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1219         AddToWorklist(N->getOperand(i).getNode());
1220
1221     SDValue RV = combine(N);
1222
1223     if (!RV.getNode())
1224       continue;
1225
1226     ++NodesCombined;
1227
1228     // If we get back the same node we passed in, rather than a new node or
1229     // zero, we know that the node must have defined multiple values and
1230     // CombineTo was used.  Since CombineTo takes care of the worklist
1231     // mechanics for us, we have no work to do in this case.
1232     if (RV.getNode() == N)
1233       continue;
1234
1235     assert(N->getOpcode() != ISD::DELETED_NODE &&
1236            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1237            "Node was deleted but visit returned new node!");
1238
1239     DEBUG(dbgs() << " ... into: ";
1240           RV.getNode()->dump(&DAG));
1241
1242     // Transfer debug value.
1243     DAG.TransferDbgValues(SDValue(N, 0), RV);
1244     if (N->getNumValues() == RV.getNode()->getNumValues())
1245       DAG.ReplaceAllUsesWith(N, RV.getNode());
1246     else {
1247       assert(N->getValueType(0) == RV.getValueType() &&
1248              N->getNumValues() == 1 && "Type mismatch");
1249       SDValue OpV = RV;
1250       DAG.ReplaceAllUsesWith(N, &OpV);
1251     }
1252
1253     // Push the new node and any users onto the worklist
1254     AddToWorklist(RV.getNode());
1255     AddUsersToWorklist(RV.getNode());
1256
1257     // Finally, if the node is now dead, remove it from the graph.  The node
1258     // may not be dead if the replacement process recursively simplified to
1259     // something else needing this node. This will also take care of adding any
1260     // operands which have lost a user to the worklist.
1261     recursivelyDeleteUnusedNodes(N);
1262   }
1263
1264   // If the root changed (e.g. it was a dead load, update the root).
1265   DAG.setRoot(Dummy.getValue());
1266   DAG.RemoveDeadNodes();
1267 }
1268
1269 SDValue DAGCombiner::visit(SDNode *N) {
1270   switch (N->getOpcode()) {
1271   default: break;
1272   case ISD::TokenFactor:        return visitTokenFactor(N);
1273   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1274   case ISD::ADD:                return visitADD(N);
1275   case ISD::SUB:                return visitSUB(N);
1276   case ISD::ADDC:               return visitADDC(N);
1277   case ISD::SUBC:               return visitSUBC(N);
1278   case ISD::ADDE:               return visitADDE(N);
1279   case ISD::SUBE:               return visitSUBE(N);
1280   case ISD::MUL:                return visitMUL(N);
1281   case ISD::SDIV:               return visitSDIV(N);
1282   case ISD::UDIV:               return visitUDIV(N);
1283   case ISD::SREM:               return visitSREM(N);
1284   case ISD::UREM:               return visitUREM(N);
1285   case ISD::MULHU:              return visitMULHU(N);
1286   case ISD::MULHS:              return visitMULHS(N);
1287   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1288   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1289   case ISD::SMULO:              return visitSMULO(N);
1290   case ISD::UMULO:              return visitUMULO(N);
1291   case ISD::SDIVREM:            return visitSDIVREM(N);
1292   case ISD::UDIVREM:            return visitUDIVREM(N);
1293   case ISD::AND:                return visitAND(N);
1294   case ISD::OR:                 return visitOR(N);
1295   case ISD::XOR:                return visitXOR(N);
1296   case ISD::SHL:                return visitSHL(N);
1297   case ISD::SRA:                return visitSRA(N);
1298   case ISD::SRL:                return visitSRL(N);
1299   case ISD::ROTR:
1300   case ISD::ROTL:               return visitRotate(N);
1301   case ISD::CTLZ:               return visitCTLZ(N);
1302   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1303   case ISD::CTTZ:               return visitCTTZ(N);
1304   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1305   case ISD::CTPOP:              return visitCTPOP(N);
1306   case ISD::SELECT:             return visitSELECT(N);
1307   case ISD::VSELECT:            return visitVSELECT(N);
1308   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1309   case ISD::SETCC:              return visitSETCC(N);
1310   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1311   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1312   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1313   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1314   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1315   case ISD::BITCAST:            return visitBITCAST(N);
1316   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1317   case ISD::FADD:               return visitFADD(N);
1318   case ISD::FSUB:               return visitFSUB(N);
1319   case ISD::FMUL:               return visitFMUL(N);
1320   case ISD::FMA:                return visitFMA(N);
1321   case ISD::FDIV:               return visitFDIV(N);
1322   case ISD::FREM:               return visitFREM(N);
1323   case ISD::FSQRT:              return visitFSQRT(N);
1324   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1325   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1326   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1327   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1328   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1329   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1330   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1331   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1332   case ISD::FNEG:               return visitFNEG(N);
1333   case ISD::FABS:               return visitFABS(N);
1334   case ISD::FFLOOR:             return visitFFLOOR(N);
1335   case ISD::FMINNUM:            return visitFMINNUM(N);
1336   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1337   case ISD::FCEIL:              return visitFCEIL(N);
1338   case ISD::FTRUNC:             return visitFTRUNC(N);
1339   case ISD::BRCOND:             return visitBRCOND(N);
1340   case ISD::BR_CC:              return visitBR_CC(N);
1341   case ISD::LOAD:               return visitLOAD(N);
1342   case ISD::STORE:              return visitSTORE(N);
1343   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1344   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1345   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1346   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1347   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1348   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1349   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1350   }
1351   return SDValue();
1352 }
1353
1354 SDValue DAGCombiner::combine(SDNode *N) {
1355   SDValue RV = visit(N);
1356
1357   // If nothing happened, try a target-specific DAG combine.
1358   if (!RV.getNode()) {
1359     assert(N->getOpcode() != ISD::DELETED_NODE &&
1360            "Node was deleted but visit returned NULL!");
1361
1362     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1363         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1364
1365       // Expose the DAG combiner to the target combiner impls.
1366       TargetLowering::DAGCombinerInfo
1367         DagCombineInfo(DAG, Level, false, this);
1368
1369       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1370     }
1371   }
1372
1373   // If nothing happened still, try promoting the operation.
1374   if (!RV.getNode()) {
1375     switch (N->getOpcode()) {
1376     default: break;
1377     case ISD::ADD:
1378     case ISD::SUB:
1379     case ISD::MUL:
1380     case ISD::AND:
1381     case ISD::OR:
1382     case ISD::XOR:
1383       RV = PromoteIntBinOp(SDValue(N, 0));
1384       break;
1385     case ISD::SHL:
1386     case ISD::SRA:
1387     case ISD::SRL:
1388       RV = PromoteIntShiftOp(SDValue(N, 0));
1389       break;
1390     case ISD::SIGN_EXTEND:
1391     case ISD::ZERO_EXTEND:
1392     case ISD::ANY_EXTEND:
1393       RV = PromoteExtend(SDValue(N, 0));
1394       break;
1395     case ISD::LOAD:
1396       if (PromoteLoad(SDValue(N, 0)))
1397         RV = SDValue(N, 0);
1398       break;
1399     }
1400   }
1401
1402   // If N is a commutative binary node, try commuting it to enable more
1403   // sdisel CSE.
1404   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1405       N->getNumValues() == 1) {
1406     SDValue N0 = N->getOperand(0);
1407     SDValue N1 = N->getOperand(1);
1408
1409     // Constant operands are canonicalized to RHS.
1410     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1411       SDValue Ops[] = {N1, N0};
1412       SDNode *CSENode;
1413       if (const BinaryWithFlagsSDNode *BinNode =
1414               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1415         CSENode = DAG.getNodeIfExists(
1416             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1417             BinNode->hasNoSignedWrap(), BinNode->isExact());
1418       } else {
1419         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1420       }
1421       if (CSENode)
1422         return SDValue(CSENode, 0);
1423     }
1424   }
1425
1426   return RV;
1427 }
1428
1429 /// Given a node, return its input chain if it has one, otherwise return a null
1430 /// sd operand.
1431 static SDValue getInputChainForNode(SDNode *N) {
1432   if (unsigned NumOps = N->getNumOperands()) {
1433     if (N->getOperand(0).getValueType() == MVT::Other)
1434       return N->getOperand(0);
1435     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1436       return N->getOperand(NumOps-1);
1437     for (unsigned i = 1; i < NumOps-1; ++i)
1438       if (N->getOperand(i).getValueType() == MVT::Other)
1439         return N->getOperand(i);
1440   }
1441   return SDValue();
1442 }
1443
1444 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1445   // If N has two operands, where one has an input chain equal to the other,
1446   // the 'other' chain is redundant.
1447   if (N->getNumOperands() == 2) {
1448     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1449       return N->getOperand(0);
1450     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1451       return N->getOperand(1);
1452   }
1453
1454   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1455   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1456   SmallPtrSet<SDNode*, 16> SeenOps;
1457   bool Changed = false;             // If we should replace this token factor.
1458
1459   // Start out with this token factor.
1460   TFs.push_back(N);
1461
1462   // Iterate through token factors.  The TFs grows when new token factors are
1463   // encountered.
1464   for (unsigned i = 0; i < TFs.size(); ++i) {
1465     SDNode *TF = TFs[i];
1466
1467     // Check each of the operands.
1468     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1469       SDValue Op = TF->getOperand(i);
1470
1471       switch (Op.getOpcode()) {
1472       case ISD::EntryToken:
1473         // Entry tokens don't need to be added to the list. They are
1474         // rededundant.
1475         Changed = true;
1476         break;
1477
1478       case ISD::TokenFactor:
1479         if (Op.hasOneUse() &&
1480             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1481           // Queue up for processing.
1482           TFs.push_back(Op.getNode());
1483           // Clean up in case the token factor is removed.
1484           AddToWorklist(Op.getNode());
1485           Changed = true;
1486           break;
1487         }
1488         // Fall thru
1489
1490       default:
1491         // Only add if it isn't already in the list.
1492         if (SeenOps.insert(Op.getNode()))
1493           Ops.push_back(Op);
1494         else
1495           Changed = true;
1496         break;
1497       }
1498     }
1499   }
1500
1501   SDValue Result;
1502
1503   // If we've change things around then replace token factor.
1504   if (Changed) {
1505     if (Ops.empty()) {
1506       // The entry token is the only possible outcome.
1507       Result = DAG.getEntryNode();
1508     } else {
1509       // New and improved token factor.
1510       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1511     }
1512
1513     // Don't add users to work list.
1514     return CombineTo(N, Result, false);
1515   }
1516
1517   return Result;
1518 }
1519
1520 /// MERGE_VALUES can always be eliminated.
1521 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1522   WorklistRemover DeadNodes(*this);
1523   // Replacing results may cause a different MERGE_VALUES to suddenly
1524   // be CSE'd with N, and carry its uses with it. Iterate until no
1525   // uses remain, to ensure that the node can be safely deleted.
1526   // First add the users of this node to the work list so that they
1527   // can be tried again once they have new operands.
1528   AddUsersToWorklist(N);
1529   do {
1530     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1531       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1532   } while (!N->use_empty());
1533   deleteAndRecombine(N);
1534   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1535 }
1536
1537 SDValue DAGCombiner::visitADD(SDNode *N) {
1538   SDValue N0 = N->getOperand(0);
1539   SDValue N1 = N->getOperand(1);
1540   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1541   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542   EVT VT = N0.getValueType();
1543
1544   // fold vector ops
1545   if (VT.isVector()) {
1546     SDValue FoldedVOp = SimplifyVBinOp(N);
1547     if (FoldedVOp.getNode()) return FoldedVOp;
1548
1549     // fold (add x, 0) -> x, vector edition
1550     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1551       return N0;
1552     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1553       return N1;
1554   }
1555
1556   // fold (add x, undef) -> undef
1557   if (N0.getOpcode() == ISD::UNDEF)
1558     return N0;
1559   if (N1.getOpcode() == ISD::UNDEF)
1560     return N1;
1561   // fold (add c1, c2) -> c1+c2
1562   if (N0C && N1C)
1563     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1564   // canonicalize constant to RHS
1565   if (N0C && !N1C)
1566     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1567   // fold (add x, 0) -> x
1568   if (N1C && N1C->isNullValue())
1569     return N0;
1570   // fold (add Sym, c) -> Sym+c
1571   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1572     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1573         GA->getOpcode() == ISD::GlobalAddress)
1574       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1575                                   GA->getOffset() +
1576                                     (uint64_t)N1C->getSExtValue());
1577   // fold ((c1-A)+c2) -> (c1+c2)-A
1578   if (N1C && N0.getOpcode() == ISD::SUB)
1579     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1580       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1581                          DAG.getConstant(N1C->getAPIntValue()+
1582                                          N0C->getAPIntValue(), VT),
1583                          N0.getOperand(1));
1584   // reassociate add
1585   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1586   if (RADD.getNode())
1587     return RADD;
1588   // fold ((0-A) + B) -> B-A
1589   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1590       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1591     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1592   // fold (A + (0-B)) -> A-B
1593   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1594       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1595     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1596   // fold (A+(B-A)) -> B
1597   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1598     return N1.getOperand(0);
1599   // fold ((B-A)+A) -> B
1600   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1601     return N0.getOperand(0);
1602   // fold (A+(B-(A+C))) to (B-C)
1603   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1604       N0 == N1.getOperand(1).getOperand(0))
1605     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1606                        N1.getOperand(1).getOperand(1));
1607   // fold (A+(B-(C+A))) to (B-C)
1608   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609       N0 == N1.getOperand(1).getOperand(1))
1610     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611                        N1.getOperand(1).getOperand(0));
1612   // fold (A+((B-A)+or-C)) to (B+or-C)
1613   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1614       N1.getOperand(0).getOpcode() == ISD::SUB &&
1615       N0 == N1.getOperand(0).getOperand(1))
1616     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1617                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1618
1619   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1620   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1621     SDValue N00 = N0.getOperand(0);
1622     SDValue N01 = N0.getOperand(1);
1623     SDValue N10 = N1.getOperand(0);
1624     SDValue N11 = N1.getOperand(1);
1625
1626     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1627       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1628                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1629                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1630   }
1631
1632   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1633     return SDValue(N, 0);
1634
1635   // fold (a+b) -> (a|b) iff a and b share no bits.
1636   if (VT.isInteger() && !VT.isVector()) {
1637     APInt LHSZero, LHSOne;
1638     APInt RHSZero, RHSOne;
1639     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1640
1641     if (LHSZero.getBoolValue()) {
1642       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1643
1644       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1645       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1646       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1647         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1648           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1649       }
1650     }
1651   }
1652
1653   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1654   if (N1.getOpcode() == ISD::SHL &&
1655       N1.getOperand(0).getOpcode() == ISD::SUB)
1656     if (ConstantSDNode *C =
1657           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1658       if (C->getAPIntValue() == 0)
1659         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1660                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1661                                        N1.getOperand(0).getOperand(1),
1662                                        N1.getOperand(1)));
1663   if (N0.getOpcode() == ISD::SHL &&
1664       N0.getOperand(0).getOpcode() == ISD::SUB)
1665     if (ConstantSDNode *C =
1666           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1667       if (C->getAPIntValue() == 0)
1668         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1669                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670                                        N0.getOperand(0).getOperand(1),
1671                                        N0.getOperand(1)));
1672
1673   if (N1.getOpcode() == ISD::AND) {
1674     SDValue AndOp0 = N1.getOperand(0);
1675     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1676     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1677     unsigned DestBits = VT.getScalarType().getSizeInBits();
1678
1679     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1680     // and similar xforms where the inner op is either ~0 or 0.
1681     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1682       SDLoc DL(N);
1683       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1684     }
1685   }
1686
1687   // add (sext i1), X -> sub X, (zext i1)
1688   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1689       N0.getOperand(0).getValueType() == MVT::i1 &&
1690       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1691     SDLoc DL(N);
1692     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1693     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1694   }
1695
1696   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1697   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1698     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1699     if (TN->getVT() == MVT::i1) {
1700       SDLoc DL(N);
1701       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1702                                  DAG.getConstant(1, VT));
1703       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1704     }
1705   }
1706
1707   return SDValue();
1708 }
1709
1710 SDValue DAGCombiner::visitADDC(SDNode *N) {
1711   SDValue N0 = N->getOperand(0);
1712   SDValue N1 = N->getOperand(1);
1713   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715   EVT VT = N0.getValueType();
1716
1717   // If the flag result is dead, turn this into an ADD.
1718   if (!N->hasAnyUseOfValue(1))
1719     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1720                      DAG.getNode(ISD::CARRY_FALSE,
1721                                  SDLoc(N), MVT::Glue));
1722
1723   // canonicalize constant to RHS.
1724   if (N0C && !N1C)
1725     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1726
1727   // fold (addc x, 0) -> x + no carry out
1728   if (N1C && N1C->isNullValue())
1729     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1730                                         SDLoc(N), MVT::Glue));
1731
1732   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1733   APInt LHSZero, LHSOne;
1734   APInt RHSZero, RHSOne;
1735   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1736
1737   if (LHSZero.getBoolValue()) {
1738     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1739
1740     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1741     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1742     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1743       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1744                        DAG.getNode(ISD::CARRY_FALSE,
1745                                    SDLoc(N), MVT::Glue));
1746   }
1747
1748   return SDValue();
1749 }
1750
1751 SDValue DAGCombiner::visitADDE(SDNode *N) {
1752   SDValue N0 = N->getOperand(0);
1753   SDValue N1 = N->getOperand(1);
1754   SDValue CarryIn = N->getOperand(2);
1755   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1757
1758   // canonicalize constant to RHS
1759   if (N0C && !N1C)
1760     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1761                        N1, N0, CarryIn);
1762
1763   // fold (adde x, y, false) -> (addc x, y)
1764   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1765     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1766
1767   return SDValue();
1768 }
1769
1770 // Since it may not be valid to emit a fold to zero for vector initializers
1771 // check if we can before folding.
1772 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1773                              SelectionDAG &DAG,
1774                              bool LegalOperations, bool LegalTypes) {
1775   if (!VT.isVector())
1776     return DAG.getConstant(0, VT);
1777   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1778     return DAG.getConstant(0, VT);
1779   return SDValue();
1780 }
1781
1782 SDValue DAGCombiner::visitSUB(SDNode *N) {
1783   SDValue N0 = N->getOperand(0);
1784   SDValue N1 = N->getOperand(1);
1785   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1786   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1787   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1788     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1789   EVT VT = N0.getValueType();
1790
1791   // fold vector ops
1792   if (VT.isVector()) {
1793     SDValue FoldedVOp = SimplifyVBinOp(N);
1794     if (FoldedVOp.getNode()) return FoldedVOp;
1795
1796     // fold (sub x, 0) -> x, vector edition
1797     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1798       return N0;
1799   }
1800
1801   // fold (sub x, x) -> 0
1802   // FIXME: Refactor this and xor and other similar operations together.
1803   if (N0 == N1)
1804     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1805   // fold (sub c1, c2) -> c1-c2
1806   if (N0C && N1C)
1807     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1808   // fold (sub x, c) -> (add x, -c)
1809   if (N1C)
1810     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1811                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1812   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1813   if (N0C && N0C->isAllOnesValue())
1814     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1815   // fold A-(A-B) -> B
1816   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1817     return N1.getOperand(1);
1818   // fold (A+B)-A -> B
1819   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1820     return N0.getOperand(1);
1821   // fold (A+B)-B -> A
1822   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1823     return N0.getOperand(0);
1824   // fold C2-(A+C1) -> (C2-C1)-A
1825   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1826     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1827                                    VT);
1828     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1829                        N1.getOperand(0));
1830   }
1831   // fold ((A+(B+or-C))-B) -> A+or-C
1832   if (N0.getOpcode() == ISD::ADD &&
1833       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1834        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1835       N0.getOperand(1).getOperand(0) == N1)
1836     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1837                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1838   // fold ((A+(C+B))-B) -> A+C
1839   if (N0.getOpcode() == ISD::ADD &&
1840       N0.getOperand(1).getOpcode() == ISD::ADD &&
1841       N0.getOperand(1).getOperand(1) == N1)
1842     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1843                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1844   // fold ((A-(B-C))-C) -> A-B
1845   if (N0.getOpcode() == ISD::SUB &&
1846       N0.getOperand(1).getOpcode() == ISD::SUB &&
1847       N0.getOperand(1).getOperand(1) == N1)
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1850
1851   // If either operand of a sub is undef, the result is undef
1852   if (N0.getOpcode() == ISD::UNDEF)
1853     return N0;
1854   if (N1.getOpcode() == ISD::UNDEF)
1855     return N1;
1856
1857   // If the relocation model supports it, consider symbol offsets.
1858   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1859     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1860       // fold (sub Sym, c) -> Sym-c
1861       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1862         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1863                                     GA->getOffset() -
1864                                       (uint64_t)N1C->getSExtValue());
1865       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1866       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1867         if (GA->getGlobal() == GB->getGlobal())
1868           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1869                                  VT);
1870     }
1871
1872   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1873   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1874     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1875     if (TN->getVT() == MVT::i1) {
1876       SDLoc DL(N);
1877       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1878                                  DAG.getConstant(1, VT));
1879       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1880     }
1881   }
1882
1883   return SDValue();
1884 }
1885
1886 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1887   SDValue N0 = N->getOperand(0);
1888   SDValue N1 = N->getOperand(1);
1889   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1890   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891   EVT VT = N0.getValueType();
1892
1893   // If the flag result is dead, turn this into an SUB.
1894   if (!N->hasAnyUseOfValue(1))
1895     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1896                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1897                                  MVT::Glue));
1898
1899   // fold (subc x, x) -> 0 + no borrow
1900   if (N0 == N1)
1901     return CombineTo(N, DAG.getConstant(0, VT),
1902                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1903                                  MVT::Glue));
1904
1905   // fold (subc x, 0) -> x + no borrow
1906   if (N1C && N1C->isNullValue())
1907     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1908                                         MVT::Glue));
1909
1910   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1911   if (N0C && N0C->isAllOnesValue())
1912     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1913                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1914                                  MVT::Glue));
1915
1916   return SDValue();
1917 }
1918
1919 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1920   SDValue N0 = N->getOperand(0);
1921   SDValue N1 = N->getOperand(1);
1922   SDValue CarryIn = N->getOperand(2);
1923
1924   // fold (sube x, y, false) -> (subc x, y)
1925   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1926     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1927
1928   return SDValue();
1929 }
1930
1931 SDValue DAGCombiner::visitMUL(SDNode *N) {
1932   SDValue N0 = N->getOperand(0);
1933   SDValue N1 = N->getOperand(1);
1934   EVT VT = N0.getValueType();
1935
1936   // fold (mul x, undef) -> 0
1937   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1938     return DAG.getConstant(0, VT);
1939
1940   bool N0IsConst = false;
1941   bool N1IsConst = false;
1942   APInt ConstValue0, ConstValue1;
1943   // fold vector ops
1944   if (VT.isVector()) {
1945     SDValue FoldedVOp = SimplifyVBinOp(N);
1946     if (FoldedVOp.getNode()) return FoldedVOp;
1947
1948     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1949     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1950   } else {
1951     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1952     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1953                             : APInt();
1954     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1955     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1956                             : APInt();
1957   }
1958
1959   // fold (mul c1, c2) -> c1*c2
1960   if (N0IsConst && N1IsConst)
1961     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1962
1963   // canonicalize constant to RHS
1964   if (N0IsConst && !N1IsConst)
1965     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1966   // fold (mul x, 0) -> 0
1967   if (N1IsConst && ConstValue1 == 0)
1968     return N1;
1969   // We require a splat of the entire scalar bit width for non-contiguous
1970   // bit patterns.
1971   bool IsFullSplat =
1972     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1973   // fold (mul x, 1) -> x
1974   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1975     return N0;
1976   // fold (mul x, -1) -> 0-x
1977   if (N1IsConst && ConstValue1.isAllOnesValue())
1978     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979                        DAG.getConstant(0, VT), N0);
1980   // fold (mul x, (1 << c)) -> x << c
1981   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1982     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1983                        DAG.getConstant(ConstValue1.logBase2(),
1984                                        getShiftAmountTy(N0.getValueType())));
1985   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1986   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1987     unsigned Log2Val = (-ConstValue1).logBase2();
1988     // FIXME: If the input is something that is easily negated (e.g. a
1989     // single-use add), we should put the negate there.
1990     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1991                        DAG.getConstant(0, VT),
1992                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1993                             DAG.getConstant(Log2Val,
1994                                       getShiftAmountTy(N0.getValueType()))));
1995   }
1996
1997   APInt Val;
1998   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1999   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2000       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2002     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2003                              N1, N0.getOperand(1));
2004     AddToWorklist(C3.getNode());
2005     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2006                        N0.getOperand(0), C3);
2007   }
2008
2009   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2010   // use.
2011   {
2012     SDValue Sh(nullptr,0), Y(nullptr,0);
2013     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2014     if (N0.getOpcode() == ISD::SHL &&
2015         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2016                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2017         N0.getNode()->hasOneUse()) {
2018       Sh = N0; Y = N1;
2019     } else if (N1.getOpcode() == ISD::SHL &&
2020                isa<ConstantSDNode>(N1.getOperand(1)) &&
2021                N1.getNode()->hasOneUse()) {
2022       Sh = N1; Y = N0;
2023     }
2024
2025     if (Sh.getNode()) {
2026       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2027                                 Sh.getOperand(0), Y);
2028       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2029                          Mul, Sh.getOperand(1));
2030     }
2031   }
2032
2033   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2034   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2035       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036                      isa<ConstantSDNode>(N0.getOperand(1))))
2037     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2038                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2039                                    N0.getOperand(0), N1),
2040                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2041                                    N0.getOperand(1), N1));
2042
2043   // reassociate mul
2044   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2045   if (RMUL.getNode())
2046     return RMUL;
2047
2048   return SDValue();
2049 }
2050
2051 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2052   SDValue N0 = N->getOperand(0);
2053   SDValue N1 = N->getOperand(1);
2054   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2055   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2056   EVT VT = N->getValueType(0);
2057
2058   // fold vector ops
2059   if (VT.isVector()) {
2060     SDValue FoldedVOp = SimplifyVBinOp(N);
2061     if (FoldedVOp.getNode()) return FoldedVOp;
2062   }
2063
2064   // fold (sdiv c1, c2) -> c1/c2
2065   if (N0C && N1C && !N1C->isNullValue())
2066     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2067   // fold (sdiv X, 1) -> X
2068   if (N1C && N1C->getAPIntValue() == 1LL)
2069     return N0;
2070   // fold (sdiv X, -1) -> 0-X
2071   if (N1C && N1C->isAllOnesValue())
2072     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2073                        DAG.getConstant(0, VT), N0);
2074   // If we know the sign bits of both operands are zero, strength reduce to a
2075   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2076   if (!VT.isVector()) {
2077     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2079                          N0, N1);
2080   }
2081
2082   // fold (sdiv X, pow2) -> simple ops after legalize
2083   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2084                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2085     // If dividing by powers of two is cheap, then don't perform the following
2086     // fold.
2087     if (TLI.isPow2SDivCheap())
2088       return SDValue();
2089
2090     // Target-specific implementation of sdiv x, pow2.
2091     SDValue Res = BuildSDIVPow2(N);
2092     if (Res.getNode())
2093       return Res;
2094
2095     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2096
2097     // Splat the sign bit into the register
2098     SDValue SGN =
2099         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2100                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2101                                     getShiftAmountTy(N0.getValueType())));
2102     AddToWorklist(SGN.getNode());
2103
2104     // Add (N0 < 0) ? abs2 - 1 : 0;
2105     SDValue SRL =
2106         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2107                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2108                                     getShiftAmountTy(SGN.getValueType())));
2109     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2110     AddToWorklist(SRL.getNode());
2111     AddToWorklist(ADD.getNode());    // Divide by pow2
2112     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2113                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2114
2115     // If we're dividing by a positive value, we're done.  Otherwise, we must
2116     // negate the result.
2117     if (N1C->getAPIntValue().isNonNegative())
2118       return SRA;
2119
2120     AddToWorklist(SRA.getNode());
2121     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2122   }
2123
2124   // if integer divide is expensive and we satisfy the requirements, emit an
2125   // alternate sequence.
2126   if (N1C && !TLI.isIntDivCheap()) {
2127     SDValue Op = BuildSDIV(N);
2128     if (Op.getNode()) return Op;
2129   }
2130
2131   // undef / X -> 0
2132   if (N0.getOpcode() == ISD::UNDEF)
2133     return DAG.getConstant(0, VT);
2134   // X / undef -> undef
2135   if (N1.getOpcode() == ISD::UNDEF)
2136     return N1;
2137
2138   return SDValue();
2139 }
2140
2141 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2142   SDValue N0 = N->getOperand(0);
2143   SDValue N1 = N->getOperand(1);
2144   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146   EVT VT = N->getValueType(0);
2147
2148   // fold vector ops
2149   if (VT.isVector()) {
2150     SDValue FoldedVOp = SimplifyVBinOp(N);
2151     if (FoldedVOp.getNode()) return FoldedVOp;
2152   }
2153
2154   // fold (udiv c1, c2) -> c1/c2
2155   if (N0C && N1C && !N1C->isNullValue())
2156     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2157   // fold (udiv x, (1 << c)) -> x >>u c
2158   if (N1C && N1C->getAPIntValue().isPowerOf2())
2159     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2160                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2161                                        getShiftAmountTy(N0.getValueType())));
2162   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2163   if (N1.getOpcode() == ISD::SHL) {
2164     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2165       if (SHC->getAPIntValue().isPowerOf2()) {
2166         EVT ADDVT = N1.getOperand(1).getValueType();
2167         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2168                                   N1.getOperand(1),
2169                                   DAG.getConstant(SHC->getAPIntValue()
2170                                                                   .logBase2(),
2171                                                   ADDVT));
2172         AddToWorklist(Add.getNode());
2173         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2174       }
2175     }
2176   }
2177   // fold (udiv x, c) -> alternate
2178   if (N1C && !TLI.isIntDivCheap()) {
2179     SDValue Op = BuildUDIV(N);
2180     if (Op.getNode()) return Op;
2181   }
2182
2183   // undef / X -> 0
2184   if (N0.getOpcode() == ISD::UNDEF)
2185     return DAG.getConstant(0, VT);
2186   // X / undef -> undef
2187   if (N1.getOpcode() == ISD::UNDEF)
2188     return N1;
2189
2190   return SDValue();
2191 }
2192
2193 SDValue DAGCombiner::visitSREM(SDNode *N) {
2194   SDValue N0 = N->getOperand(0);
2195   SDValue N1 = N->getOperand(1);
2196   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2197   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2198   EVT VT = N->getValueType(0);
2199
2200   // fold (srem c1, c2) -> c1%c2
2201   if (N0C && N1C && !N1C->isNullValue())
2202     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2203   // If we know the sign bits of both operands are zero, strength reduce to a
2204   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2205   if (!VT.isVector()) {
2206     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2207       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2208   }
2209
2210   // If X/C can be simplified by the division-by-constant logic, lower
2211   // X%C to the equivalent of X-X/C*C.
2212   if (N1C && !N1C->isNullValue()) {
2213     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2214     AddToWorklist(Div.getNode());
2215     SDValue OptimizedDiv = combine(Div.getNode());
2216     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2217       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2218                                 OptimizedDiv, N1);
2219       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2220       AddToWorklist(Mul.getNode());
2221       return Sub;
2222     }
2223   }
2224
2225   // undef % X -> 0
2226   if (N0.getOpcode() == ISD::UNDEF)
2227     return DAG.getConstant(0, VT);
2228   // X % undef -> undef
2229   if (N1.getOpcode() == ISD::UNDEF)
2230     return N1;
2231
2232   return SDValue();
2233 }
2234
2235 SDValue DAGCombiner::visitUREM(SDNode *N) {
2236   SDValue N0 = N->getOperand(0);
2237   SDValue N1 = N->getOperand(1);
2238   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240   EVT VT = N->getValueType(0);
2241
2242   // fold (urem c1, c2) -> c1%c2
2243   if (N0C && N1C && !N1C->isNullValue())
2244     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2245   // fold (urem x, pow2) -> (and x, pow2-1)
2246   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2247     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2248                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2249   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2250   if (N1.getOpcode() == ISD::SHL) {
2251     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2252       if (SHC->getAPIntValue().isPowerOf2()) {
2253         SDValue Add =
2254           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2255                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2256                                  VT));
2257         AddToWorklist(Add.getNode());
2258         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2259       }
2260     }
2261   }
2262
2263   // If X/C can be simplified by the division-by-constant logic, lower
2264   // X%C to the equivalent of X-X/C*C.
2265   if (N1C && !N1C->isNullValue()) {
2266     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2267     AddToWorklist(Div.getNode());
2268     SDValue OptimizedDiv = combine(Div.getNode());
2269     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2270       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2271                                 OptimizedDiv, N1);
2272       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2273       AddToWorklist(Mul.getNode());
2274       return Sub;
2275     }
2276   }
2277
2278   // undef % X -> 0
2279   if (N0.getOpcode() == ISD::UNDEF)
2280     return DAG.getConstant(0, VT);
2281   // X % undef -> undef
2282   if (N1.getOpcode() == ISD::UNDEF)
2283     return N1;
2284
2285   return SDValue();
2286 }
2287
2288 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2289   SDValue N0 = N->getOperand(0);
2290   SDValue N1 = N->getOperand(1);
2291   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292   EVT VT = N->getValueType(0);
2293   SDLoc DL(N);
2294
2295   // fold (mulhs x, 0) -> 0
2296   if (N1C && N1C->isNullValue())
2297     return N1;
2298   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2299   if (N1C && N1C->getAPIntValue() == 1)
2300     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2301                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2302                                        getShiftAmountTy(N0.getValueType())));
2303   // fold (mulhs x, undef) -> 0
2304   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2305     return DAG.getConstant(0, VT);
2306
2307   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2308   // plus a shift.
2309   if (VT.isSimple() && !VT.isVector()) {
2310     MVT Simple = VT.getSimpleVT();
2311     unsigned SimpleSize = Simple.getSizeInBits();
2312     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2315       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2316       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2317       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2318             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2319       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2320     }
2321   }
2322
2323   return SDValue();
2324 }
2325
2326 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2327   SDValue N0 = N->getOperand(0);
2328   SDValue N1 = N->getOperand(1);
2329   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2330   EVT VT = N->getValueType(0);
2331   SDLoc DL(N);
2332
2333   // fold (mulhu x, 0) -> 0
2334   if (N1C && N1C->isNullValue())
2335     return N1;
2336   // fold (mulhu x, 1) -> 0
2337   if (N1C && N1C->getAPIntValue() == 1)
2338     return DAG.getConstant(0, N0.getValueType());
2339   // fold (mulhu x, undef) -> 0
2340   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2341     return DAG.getConstant(0, VT);
2342
2343   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2344   // plus a shift.
2345   if (VT.isSimple() && !VT.isVector()) {
2346     MVT Simple = VT.getSimpleVT();
2347     unsigned SimpleSize = Simple.getSizeInBits();
2348     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2349     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2350       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2351       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2352       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2353       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2354             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2355       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2356     }
2357   }
2358
2359   return SDValue();
2360 }
2361
2362 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2363 /// give the opcodes for the two computations that are being performed. Return
2364 /// true if a simplification was made.
2365 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2366                                                 unsigned HiOp) {
2367   // If the high half is not needed, just compute the low half.
2368   bool HiExists = N->hasAnyUseOfValue(1);
2369   if (!HiExists &&
2370       (!LegalOperations ||
2371        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2372     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2373     return CombineTo(N, Res, Res);
2374   }
2375
2376   // If the low half is not needed, just compute the high half.
2377   bool LoExists = N->hasAnyUseOfValue(0);
2378   if (!LoExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2382     return CombineTo(N, Res, Res);
2383   }
2384
2385   // If both halves are used, return as it is.
2386   if (LoExists && HiExists)
2387     return SDValue();
2388
2389   // If the two computed results can be simplified separately, separate them.
2390   if (LoExists) {
2391     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2392     AddToWorklist(Lo.getNode());
2393     SDValue LoOpt = combine(Lo.getNode());
2394     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2395         (!LegalOperations ||
2396          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2397       return CombineTo(N, LoOpt, LoOpt);
2398   }
2399
2400   if (HiExists) {
2401     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2402     AddToWorklist(Hi.getNode());
2403     SDValue HiOpt = combine(Hi.getNode());
2404     if (HiOpt.getNode() && HiOpt != Hi &&
2405         (!LegalOperations ||
2406          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2407       return CombineTo(N, HiOpt, HiOpt);
2408   }
2409
2410   return SDValue();
2411 }
2412
2413 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2414   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2415   if (Res.getNode()) return Res;
2416
2417   EVT VT = N->getValueType(0);
2418   SDLoc DL(N);
2419
2420   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2421   // plus a shift.
2422   if (VT.isSimple() && !VT.isVector()) {
2423     MVT Simple = VT.getSimpleVT();
2424     unsigned SimpleSize = Simple.getSizeInBits();
2425     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2426     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2427       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2428       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2429       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2430       // Compute the high part as N1.
2431       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2432             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2433       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2434       // Compute the low part as N0.
2435       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2436       return CombineTo(N, Lo, Hi);
2437     }
2438   }
2439
2440   return SDValue();
2441 }
2442
2443 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2444   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2445   if (Res.getNode()) return Res;
2446
2447   EVT VT = N->getValueType(0);
2448   SDLoc DL(N);
2449
2450   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2451   // plus a shift.
2452   if (VT.isSimple() && !VT.isVector()) {
2453     MVT Simple = VT.getSimpleVT();
2454     unsigned SimpleSize = Simple.getSizeInBits();
2455     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2458       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2459       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460       // Compute the high part as N1.
2461       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464       // Compute the low part as N0.
2465       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466       return CombineTo(N, Lo, Hi);
2467     }
2468   }
2469
2470   return SDValue();
2471 }
2472
2473 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2474   // (smulo x, 2) -> (saddo x, x)
2475   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2476     if (C2->getAPIntValue() == 2)
2477       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2478                          N->getOperand(0), N->getOperand(0));
2479
2480   return SDValue();
2481 }
2482
2483 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2484   // (umulo x, 2) -> (uaddo x, x)
2485   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2486     if (C2->getAPIntValue() == 2)
2487       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2488                          N->getOperand(0), N->getOperand(0));
2489
2490   return SDValue();
2491 }
2492
2493 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2494   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2495   if (Res.getNode()) return Res;
2496
2497   return SDValue();
2498 }
2499
2500 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2501   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2502   if (Res.getNode()) return Res;
2503
2504   return SDValue();
2505 }
2506
2507 /// If this is a binary operator with two operands of the same opcode, try to
2508 /// simplify it.
2509 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2510   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2511   EVT VT = N0.getValueType();
2512   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2513
2514   // Bail early if none of these transforms apply.
2515   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2516
2517   // For each of OP in AND/OR/XOR:
2518   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2519   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2520   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2521   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2522   //
2523   // do not sink logical op inside of a vector extend, since it may combine
2524   // into a vsetcc.
2525   EVT Op0VT = N0.getOperand(0).getValueType();
2526   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2527        N0.getOpcode() == ISD::SIGN_EXTEND ||
2528        // Avoid infinite looping with PromoteIntBinOp.
2529        (N0.getOpcode() == ISD::ANY_EXTEND &&
2530         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2531        (N0.getOpcode() == ISD::TRUNCATE &&
2532         (!TLI.isZExtFree(VT, Op0VT) ||
2533          !TLI.isTruncateFree(Op0VT, VT)) &&
2534         TLI.isTypeLegal(Op0VT))) &&
2535       !VT.isVector() &&
2536       Op0VT == N1.getOperand(0).getValueType() &&
2537       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2538     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2539                                  N0.getOperand(0).getValueType(),
2540                                  N0.getOperand(0), N1.getOperand(0));
2541     AddToWorklist(ORNode.getNode());
2542     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2543   }
2544
2545   // For each of OP in SHL/SRL/SRA/AND...
2546   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2547   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2548   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2549   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2550        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2551       N0.getOperand(1) == N1.getOperand(1)) {
2552     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2553                                  N0.getOperand(0).getValueType(),
2554                                  N0.getOperand(0), N1.getOperand(0));
2555     AddToWorklist(ORNode.getNode());
2556     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2557                        ORNode, N0.getOperand(1));
2558   }
2559
2560   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2561   // Only perform this optimization after type legalization and before
2562   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2563   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2564   // we don't want to undo this promotion.
2565   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2566   // on scalars.
2567   if ((N0.getOpcode() == ISD::BITCAST ||
2568        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2569       Level == AfterLegalizeTypes) {
2570     SDValue In0 = N0.getOperand(0);
2571     SDValue In1 = N1.getOperand(0);
2572     EVT In0Ty = In0.getValueType();
2573     EVT In1Ty = In1.getValueType();
2574     SDLoc DL(N);
2575     // If both incoming values are integers, and the original types are the
2576     // same.
2577     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2578       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2579       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2580       AddToWorklist(Op.getNode());
2581       return BC;
2582     }
2583   }
2584
2585   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2586   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2587   // If both shuffles use the same mask, and both shuffle within a single
2588   // vector, then it is worthwhile to move the swizzle after the operation.
2589   // The type-legalizer generates this pattern when loading illegal
2590   // vector types from memory. In many cases this allows additional shuffle
2591   // optimizations.
2592   // There are other cases where moving the shuffle after the xor/and/or
2593   // is profitable even if shuffles don't perform a swizzle.
2594   // If both shuffles use the same mask, and both shuffles have the same first
2595   // or second operand, then it might still be profitable to move the shuffle
2596   // after the xor/and/or operation.
2597   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2598     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2599     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2600
2601     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2602            "Inputs to shuffles are not the same type");
2603
2604     // Check that both shuffles use the same mask. The masks are known to be of
2605     // the same length because the result vector type is the same.
2606     // Check also that shuffles have only one use to avoid introducing extra
2607     // instructions.
2608     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2609         SVN0->getMask().equals(SVN1->getMask())) {
2610       SDValue ShOp = N0->getOperand(1);
2611
2612       // Don't try to fold this node if it requires introducing a
2613       // build vector of all zeros that might be illegal at this stage.
2614       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2615         if (!LegalTypes)
2616           ShOp = DAG.getConstant(0, VT);
2617         else
2618           ShOp = SDValue();
2619       }
2620
2621       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2622       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2623       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2624       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2625         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2626                                       N0->getOperand(0), N1->getOperand(0));
2627         AddToWorklist(NewNode.getNode());
2628         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2629                                     &SVN0->getMask()[0]);
2630       }
2631
2632       // Don't try to fold this node if it requires introducing a
2633       // build vector of all zeros that might be illegal at this stage.
2634       ShOp = N0->getOperand(0);
2635       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2636         if (!LegalTypes)
2637           ShOp = DAG.getConstant(0, VT);
2638         else
2639           ShOp = SDValue();
2640       }
2641
2642       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2643       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2644       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2645       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2646         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2647                                       N0->getOperand(1), N1->getOperand(1));
2648         AddToWorklist(NewNode.getNode());
2649         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2650                                     &SVN0->getMask()[0]);
2651       }
2652     }
2653   }
2654
2655   return SDValue();
2656 }
2657
2658 SDValue DAGCombiner::visitAND(SDNode *N) {
2659   SDValue N0 = N->getOperand(0);
2660   SDValue N1 = N->getOperand(1);
2661   SDValue LL, LR, RL, RR, CC0, CC1;
2662   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2663   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2664   EVT VT = N1.getValueType();
2665   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2666
2667   // fold vector ops
2668   if (VT.isVector()) {
2669     SDValue FoldedVOp = SimplifyVBinOp(N);
2670     if (FoldedVOp.getNode()) return FoldedVOp;
2671
2672     // fold (and x, 0) -> 0, vector edition
2673     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2674       // do not return N0, because undef node may exist in N0
2675       return DAG.getConstant(
2676           APInt::getNullValue(
2677               N0.getValueType().getScalarType().getSizeInBits()),
2678           N0.getValueType());
2679     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2680       // do not return N1, because undef node may exist in N1
2681       return DAG.getConstant(
2682           APInt::getNullValue(
2683               N1.getValueType().getScalarType().getSizeInBits()),
2684           N1.getValueType());
2685
2686     // fold (and x, -1) -> x, vector edition
2687     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2688       return N1;
2689     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2690       return N0;
2691   }
2692
2693   // fold (and x, undef) -> 0
2694   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2695     return DAG.getConstant(0, VT);
2696   // fold (and c1, c2) -> c1&c2
2697   if (N0C && N1C)
2698     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2699   // canonicalize constant to RHS
2700   if (N0C && !N1C)
2701     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2702   // fold (and x, -1) -> x
2703   if (N1C && N1C->isAllOnesValue())
2704     return N0;
2705   // if (and x, c) is known to be zero, return 0
2706   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2707                                    APInt::getAllOnesValue(BitWidth)))
2708     return DAG.getConstant(0, VT);
2709   // reassociate and
2710   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2711   if (RAND.getNode())
2712     return RAND;
2713   // fold (and (or x, C), D) -> D if (C & D) == D
2714   if (N1C && N0.getOpcode() == ISD::OR)
2715     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2716       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2717         return N1;
2718   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2719   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2720     SDValue N0Op0 = N0.getOperand(0);
2721     APInt Mask = ~N1C->getAPIntValue();
2722     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2723     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2724       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2725                                  N0.getValueType(), N0Op0);
2726
2727       // Replace uses of the AND with uses of the Zero extend node.
2728       CombineTo(N, Zext);
2729
2730       // We actually want to replace all uses of the any_extend with the
2731       // zero_extend, to avoid duplicating things.  This will later cause this
2732       // AND to be folded.
2733       CombineTo(N0.getNode(), Zext);
2734       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2735     }
2736   }
2737   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2738   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2739   // already be zero by virtue of the width of the base type of the load.
2740   //
2741   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2742   // more cases.
2743   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2744        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2745       N0.getOpcode() == ISD::LOAD) {
2746     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2747                                          N0 : N0.getOperand(0) );
2748
2749     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2750     // This can be a pure constant or a vector splat, in which case we treat the
2751     // vector as a scalar and use the splat value.
2752     APInt Constant = APInt::getNullValue(1);
2753     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2754       Constant = C->getAPIntValue();
2755     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2756       APInt SplatValue, SplatUndef;
2757       unsigned SplatBitSize;
2758       bool HasAnyUndefs;
2759       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2760                                              SplatBitSize, HasAnyUndefs);
2761       if (IsSplat) {
2762         // Undef bits can contribute to a possible optimisation if set, so
2763         // set them.
2764         SplatValue |= SplatUndef;
2765
2766         // The splat value may be something like "0x00FFFFFF", which means 0 for
2767         // the first vector value and FF for the rest, repeating. We need a mask
2768         // that will apply equally to all members of the vector, so AND all the
2769         // lanes of the constant together.
2770         EVT VT = Vector->getValueType(0);
2771         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2772
2773         // If the splat value has been compressed to a bitlength lower
2774         // than the size of the vector lane, we need to re-expand it to
2775         // the lane size.
2776         if (BitWidth > SplatBitSize)
2777           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2778                SplatBitSize < BitWidth;
2779                SplatBitSize = SplatBitSize * 2)
2780             SplatValue |= SplatValue.shl(SplatBitSize);
2781
2782         Constant = APInt::getAllOnesValue(BitWidth);
2783         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2784           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2785       }
2786     }
2787
2788     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2789     // actually legal and isn't going to get expanded, else this is a false
2790     // optimisation.
2791     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2792                                                     Load->getMemoryVT());
2793
2794     // Resize the constant to the same size as the original memory access before
2795     // extension. If it is still the AllOnesValue then this AND is completely
2796     // unneeded.
2797     Constant =
2798       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2799
2800     bool B;
2801     switch (Load->getExtensionType()) {
2802     default: B = false; break;
2803     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2804     case ISD::ZEXTLOAD:
2805     case ISD::NON_EXTLOAD: B = true; break;
2806     }
2807
2808     if (B && Constant.isAllOnesValue()) {
2809       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2810       // preserve semantics once we get rid of the AND.
2811       SDValue NewLoad(Load, 0);
2812       if (Load->getExtensionType() == ISD::EXTLOAD) {
2813         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2814                               Load->getValueType(0), SDLoc(Load),
2815                               Load->getChain(), Load->getBasePtr(),
2816                               Load->getOffset(), Load->getMemoryVT(),
2817                               Load->getMemOperand());
2818         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2819         if (Load->getNumValues() == 3) {
2820           // PRE/POST_INC loads have 3 values.
2821           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2822                            NewLoad.getValue(2) };
2823           CombineTo(Load, To, 3, true);
2824         } else {
2825           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2826         }
2827       }
2828
2829       // Fold the AND away, taking care not to fold to the old load node if we
2830       // replaced it.
2831       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2832
2833       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2834     }
2835   }
2836   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2837   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2838     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2839     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2840
2841     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2842         LL.getValueType().isInteger()) {
2843       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2844       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2845         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2846                                      LR.getValueType(), LL, RL);
2847         AddToWorklist(ORNode.getNode());
2848         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2849       }
2850       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2851       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2852         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2853                                       LR.getValueType(), LL, RL);
2854         AddToWorklist(ANDNode.getNode());
2855         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2856       }
2857       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2858       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2859         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2860                                      LR.getValueType(), LL, RL);
2861         AddToWorklist(ORNode.getNode());
2862         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2863       }
2864     }
2865     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2866     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2867         Op0 == Op1 && LL.getValueType().isInteger() &&
2868       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2869                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2870                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2871                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2872       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2873                                     LL, DAG.getConstant(1, LL.getValueType()));
2874       AddToWorklist(ADDNode.getNode());
2875       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2876                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2877     }
2878     // canonicalize equivalent to ll == rl
2879     if (LL == RR && LR == RL) {
2880       Op1 = ISD::getSetCCSwappedOperands(Op1);
2881       std::swap(RL, RR);
2882     }
2883     if (LL == RL && LR == RR) {
2884       bool isInteger = LL.getValueType().isInteger();
2885       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2886       if (Result != ISD::SETCC_INVALID &&
2887           (!LegalOperations ||
2888            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2889             TLI.isOperationLegal(ISD::SETCC,
2890                             getSetCCResultType(N0.getSimpleValueType())))))
2891         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2892                             LL, LR, Result);
2893     }
2894   }
2895
2896   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2897   if (N0.getOpcode() == N1.getOpcode()) {
2898     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2899     if (Tmp.getNode()) return Tmp;
2900   }
2901
2902   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2903   // fold (and (sra)) -> (and (srl)) when possible.
2904   if (!VT.isVector() &&
2905       SimplifyDemandedBits(SDValue(N, 0)))
2906     return SDValue(N, 0);
2907
2908   // fold (zext_inreg (extload x)) -> (zextload x)
2909   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2910     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2911     EVT MemVT = LN0->getMemoryVT();
2912     // If we zero all the possible extended bits, then we can turn this into
2913     // a zextload if we are running before legalize or the operation is legal.
2914     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2915     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2916                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2917         ((!LegalOperations && !LN0->isVolatile()) ||
2918          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2919       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2920                                        LN0->getChain(), LN0->getBasePtr(),
2921                                        MemVT, LN0->getMemOperand());
2922       AddToWorklist(N);
2923       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2924       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2925     }
2926   }
2927   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2928   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2929       N0.hasOneUse()) {
2930     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2931     EVT MemVT = LN0->getMemoryVT();
2932     // If we zero all the possible extended bits, then we can turn this into
2933     // a zextload if we are running before legalize or the operation is legal.
2934     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2935     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2936                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2937         ((!LegalOperations && !LN0->isVolatile()) ||
2938          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2939       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2940                                        LN0->getChain(), LN0->getBasePtr(),
2941                                        MemVT, LN0->getMemOperand());
2942       AddToWorklist(N);
2943       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2944       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2945     }
2946   }
2947
2948   // fold (and (load x), 255) -> (zextload x, i8)
2949   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2950   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2951   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2952               (N0.getOpcode() == ISD::ANY_EXTEND &&
2953                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2954     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2955     LoadSDNode *LN0 = HasAnyExt
2956       ? cast<LoadSDNode>(N0.getOperand(0))
2957       : cast<LoadSDNode>(N0);
2958     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2959         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2960       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2961       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2962         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2963         EVT LoadedVT = LN0->getMemoryVT();
2964
2965         if (ExtVT == LoadedVT &&
2966             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2967           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2968
2969           SDValue NewLoad =
2970             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2972                            LN0->getMemOperand());
2973           AddToWorklist(N);
2974           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2975           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2976         }
2977
2978         // Do not change the width of a volatile load.
2979         // Do not generate loads of non-round integer types since these can
2980         // be expensive (and would be wrong if the type is not byte sized).
2981         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2982             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2983           EVT PtrType = LN0->getOperand(1).getValueType();
2984
2985           unsigned Alignment = LN0->getAlignment();
2986           SDValue NewPtr = LN0->getBasePtr();
2987
2988           // For big endian targets, we need to add an offset to the pointer
2989           // to load the correct bytes.  For little endian systems, we merely
2990           // need to read fewer bytes from the same pointer.
2991           if (TLI.isBigEndian()) {
2992             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2993             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2994             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2995             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2996                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2997             Alignment = MinAlign(Alignment, PtrOff);
2998           }
2999
3000           AddToWorklist(NewPtr.getNode());
3001
3002           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3003           SDValue Load =
3004             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3005                            LN0->getChain(), NewPtr,
3006                            LN0->getPointerInfo(),
3007                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3008                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3009           AddToWorklist(N);
3010           CombineTo(LN0, Load, Load.getValue(1));
3011           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3012         }
3013       }
3014     }
3015   }
3016
3017   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3018       VT.getSizeInBits() <= 64) {
3019     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3020       APInt ADDC = ADDI->getAPIntValue();
3021       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3023         // immediate for an add, but it is legal if its top c2 bits are set,
3024         // transform the ADD so the immediate doesn't need to be materialized
3025         // in a register.
3026         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3027           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3028                                              SRLI->getZExtValue());
3029           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3030             ADDC |= Mask;
3031             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3032               SDValue NewAdd =
3033                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3034                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3035               CombineTo(N0.getNode(), NewAdd);
3036               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3037             }
3038           }
3039         }
3040       }
3041     }
3042   }
3043
3044   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3045   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3046     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3047                                        N0.getOperand(1), false);
3048     if (BSwap.getNode())
3049       return BSwap;
3050   }
3051
3052   return SDValue();
3053 }
3054
3055 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3056 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3057                                         bool DemandHighBits) {
3058   if (!LegalOperations)
3059     return SDValue();
3060
3061   EVT VT = N->getValueType(0);
3062   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3063     return SDValue();
3064   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3065     return SDValue();
3066
3067   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3068   bool LookPassAnd0 = false;
3069   bool LookPassAnd1 = false;
3070   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3071       std::swap(N0, N1);
3072   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3073       std::swap(N0, N1);
3074   if (N0.getOpcode() == ISD::AND) {
3075     if (!N0.getNode()->hasOneUse())
3076       return SDValue();
3077     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078     if (!N01C || N01C->getZExtValue() != 0xFF00)
3079       return SDValue();
3080     N0 = N0.getOperand(0);
3081     LookPassAnd0 = true;
3082   }
3083
3084   if (N1.getOpcode() == ISD::AND) {
3085     if (!N1.getNode()->hasOneUse())
3086       return SDValue();
3087     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3088     if (!N11C || N11C->getZExtValue() != 0xFF)
3089       return SDValue();
3090     N1 = N1.getOperand(0);
3091     LookPassAnd1 = true;
3092   }
3093
3094   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3095     std::swap(N0, N1);
3096   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3097     return SDValue();
3098   if (!N0.getNode()->hasOneUse() ||
3099       !N1.getNode()->hasOneUse())
3100     return SDValue();
3101
3102   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3104   if (!N01C || !N11C)
3105     return SDValue();
3106   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3107     return SDValue();
3108
3109   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3110   SDValue N00 = N0->getOperand(0);
3111   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3112     if (!N00.getNode()->hasOneUse())
3113       return SDValue();
3114     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3115     if (!N001C || N001C->getZExtValue() != 0xFF)
3116       return SDValue();
3117     N00 = N00.getOperand(0);
3118     LookPassAnd0 = true;
3119   }
3120
3121   SDValue N10 = N1->getOperand(0);
3122   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3123     if (!N10.getNode()->hasOneUse())
3124       return SDValue();
3125     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3126     if (!N101C || N101C->getZExtValue() != 0xFF00)
3127       return SDValue();
3128     N10 = N10.getOperand(0);
3129     LookPassAnd1 = true;
3130   }
3131
3132   if (N00 != N10)
3133     return SDValue();
3134
3135   // Make sure everything beyond the low halfword gets set to zero since the SRL
3136   // 16 will clear the top bits.
3137   unsigned OpSizeInBits = VT.getSizeInBits();
3138   if (DemandHighBits && OpSizeInBits > 16) {
3139     // If the left-shift isn't masked out then the only way this is a bswap is
3140     // if all bits beyond the low 8 are 0. In that case the entire pattern
3141     // reduces to a left shift anyway: leave it for other parts of the combiner.
3142     if (!LookPassAnd0)
3143       return SDValue();
3144
3145     // However, if the right shift isn't masked out then it might be because
3146     // it's not needed. See if we can spot that too.
3147     if (!LookPassAnd1 &&
3148         !DAG.MaskedValueIsZero(
3149             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3150       return SDValue();
3151   }
3152
3153   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3154   if (OpSizeInBits > 16)
3155     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3156                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3157   return Res;
3158 }
3159
3160 /// Return true if the specified node is an element that makes up a 32-bit
3161 /// packed halfword byteswap.
3162 /// ((x & 0x000000ff) << 8) |
3163 /// ((x & 0x0000ff00) >> 8) |
3164 /// ((x & 0x00ff0000) << 8) |
3165 /// ((x & 0xff000000) >> 8)
3166 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3167   if (!N.getNode()->hasOneUse())
3168     return false;
3169
3170   unsigned Opc = N.getOpcode();
3171   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3172     return false;
3173
3174   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3175   if (!N1C)
3176     return false;
3177
3178   unsigned Num;
3179   switch (N1C->getZExtValue()) {
3180   default:
3181     return false;
3182   case 0xFF:       Num = 0; break;
3183   case 0xFF00:     Num = 1; break;
3184   case 0xFF0000:   Num = 2; break;
3185   case 0xFF000000: Num = 3; break;
3186   }
3187
3188   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3189   SDValue N0 = N.getOperand(0);
3190   if (Opc == ISD::AND) {
3191     if (Num == 0 || Num == 2) {
3192       // (x >> 8) & 0xff
3193       // (x >> 8) & 0xff0000
3194       if (N0.getOpcode() != ISD::SRL)
3195         return false;
3196       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3197       if (!C || C->getZExtValue() != 8)
3198         return false;
3199     } else {
3200       // (x << 8) & 0xff00
3201       // (x << 8) & 0xff000000
3202       if (N0.getOpcode() != ISD::SHL)
3203         return false;
3204       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205       if (!C || C->getZExtValue() != 8)
3206         return false;
3207     }
3208   } else if (Opc == ISD::SHL) {
3209     // (x & 0xff) << 8
3210     // (x & 0xff0000) << 8
3211     if (Num != 0 && Num != 2)
3212       return false;
3213     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3214     if (!C || C->getZExtValue() != 8)
3215       return false;
3216   } else { // Opc == ISD::SRL
3217     // (x & 0xff00) >> 8
3218     // (x & 0xff000000) >> 8
3219     if (Num != 1 && Num != 3)
3220       return false;
3221     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222     if (!C || C->getZExtValue() != 8)
3223       return false;
3224   }
3225
3226   if (Parts[Num])
3227     return false;
3228
3229   Parts[Num] = N0.getOperand(0).getNode();
3230   return true;
3231 }
3232
3233 /// Match a 32-bit packed halfword bswap. That is
3234 /// ((x & 0x000000ff) << 8) |
3235 /// ((x & 0x0000ff00) >> 8) |
3236 /// ((x & 0x00ff0000) << 8) |
3237 /// ((x & 0xff000000) >> 8)
3238 /// => (rotl (bswap x), 16)
3239 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3240   if (!LegalOperations)
3241     return SDValue();
3242
3243   EVT VT = N->getValueType(0);
3244   if (VT != MVT::i32)
3245     return SDValue();
3246   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3247     return SDValue();
3248
3249   // Look for either
3250   // (or (or (and), (and)), (or (and), (and)))
3251   // (or (or (or (and), (and)), (and)), (and))
3252   if (N0.getOpcode() != ISD::OR)
3253     return SDValue();
3254   SDValue N00 = N0.getOperand(0);
3255   SDValue N01 = N0.getOperand(1);
3256   SDNode *Parts[4] = {};
3257
3258   if (N1.getOpcode() == ISD::OR &&
3259       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3260     // (or (or (and), (and)), (or (and), (and)))
3261     SDValue N000 = N00.getOperand(0);
3262     if (!isBSwapHWordElement(N000, Parts))
3263       return SDValue();
3264
3265     SDValue N001 = N00.getOperand(1);
3266     if (!isBSwapHWordElement(N001, Parts))
3267       return SDValue();
3268     SDValue N010 = N01.getOperand(0);
3269     if (!isBSwapHWordElement(N010, Parts))
3270       return SDValue();
3271     SDValue N011 = N01.getOperand(1);
3272     if (!isBSwapHWordElement(N011, Parts))
3273       return SDValue();
3274   } else {
3275     // (or (or (or (and), (and)), (and)), (and))
3276     if (!isBSwapHWordElement(N1, Parts))
3277       return SDValue();
3278     if (!isBSwapHWordElement(N01, Parts))
3279       return SDValue();
3280     if (N00.getOpcode() != ISD::OR)
3281       return SDValue();
3282     SDValue N000 = N00.getOperand(0);
3283     if (!isBSwapHWordElement(N000, Parts))
3284       return SDValue();
3285     SDValue N001 = N00.getOperand(1);
3286     if (!isBSwapHWordElement(N001, Parts))
3287       return SDValue();
3288   }
3289
3290   // Make sure the parts are all coming from the same node.
3291   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3292     return SDValue();
3293
3294   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3295                               SDValue(Parts[0],0));
3296
3297   // Result of the bswap should be rotated by 16. If it's not legal, then
3298   // do  (x << 16) | (x >> 16).
3299   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3300   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3301     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3302   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3303     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3304   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3305                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3306                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3307 }
3308
3309 SDValue DAGCombiner::visitOR(SDNode *N) {
3310   SDValue N0 = N->getOperand(0);
3311   SDValue N1 = N->getOperand(1);
3312   SDValue LL, LR, RL, RR, CC0, CC1;
3313   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3314   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3315   EVT VT = N1.getValueType();
3316
3317   // fold vector ops
3318   if (VT.isVector()) {
3319     SDValue FoldedVOp = SimplifyVBinOp(N);
3320     if (FoldedVOp.getNode()) return FoldedVOp;
3321
3322     // fold (or x, 0) -> x, vector edition
3323     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3324       return N1;
3325     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3326       return N0;
3327
3328     // fold (or x, -1) -> -1, vector edition
3329     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3330       // do not return N0, because undef node may exist in N0
3331       return DAG.getConstant(
3332           APInt::getAllOnesValue(
3333               N0.getValueType().getScalarType().getSizeInBits()),
3334           N0.getValueType());
3335     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3336       // do not return N1, because undef node may exist in N1
3337       return DAG.getConstant(
3338           APInt::getAllOnesValue(
3339               N1.getValueType().getScalarType().getSizeInBits()),
3340           N1.getValueType());
3341
3342     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3343     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3344     // Do this only if the resulting shuffle is legal.
3345     if (isa<ShuffleVectorSDNode>(N0) &&
3346         isa<ShuffleVectorSDNode>(N1) &&
3347         // Avoid folding a node with illegal type.
3348         TLI.isTypeLegal(VT) &&
3349         N0->getOperand(1) == N1->getOperand(1) &&
3350         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3351       bool CanFold = true;
3352       unsigned NumElts = VT.getVectorNumElements();
3353       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3354       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3355       // We construct two shuffle masks:
3356       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3357       // and N1 as the second operand.
3358       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3359       // and N0 as the second operand.
3360       // We do this because OR is commutable and therefore there might be
3361       // two ways to fold this node into a shuffle.
3362       SmallVector<int,4> Mask1;
3363       SmallVector<int,4> Mask2;
3364
3365       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3366         int M0 = SV0->getMaskElt(i);
3367         int M1 = SV1->getMaskElt(i);
3368
3369         // Both shuffle indexes are undef. Propagate Undef.
3370         if (M0 < 0 && M1 < 0) {
3371           Mask1.push_back(M0);
3372           Mask2.push_back(M0);
3373           continue;
3374         }
3375
3376         if (M0 < 0 || M1 < 0 ||
3377             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3378             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3379           CanFold = false;
3380           break;
3381         }
3382
3383         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3384         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3385       }
3386
3387       if (CanFold) {
3388         // Fold this sequence only if the resulting shuffle is 'legal'.
3389         if (TLI.isShuffleMaskLegal(Mask1, VT))
3390           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3391                                       N1->getOperand(0), &Mask1[0]);
3392         if (TLI.isShuffleMaskLegal(Mask2, VT))
3393           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3394                                       N0->getOperand(0), &Mask2[0]);
3395       }
3396     }
3397   }
3398
3399   // fold (or x, undef) -> -1
3400   if (!LegalOperations &&
3401       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3402     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3403     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3404   }
3405   // fold (or c1, c2) -> c1|c2
3406   if (N0C && N1C)
3407     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3408   // canonicalize constant to RHS
3409   if (N0C && !N1C)
3410     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3411   // fold (or x, 0) -> x
3412   if (N1C && N1C->isNullValue())
3413     return N0;
3414   // fold (or x, -1) -> -1
3415   if (N1C && N1C->isAllOnesValue())
3416     return N1;
3417   // fold (or x, c) -> c iff (x & ~c) == 0
3418   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3419     return N1;
3420
3421   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3422   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3423   if (BSwap.getNode())
3424     return BSwap;
3425   BSwap = MatchBSwapHWordLow(N, N0, N1);
3426   if (BSwap.getNode())
3427     return BSwap;
3428
3429   // reassociate or
3430   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3431   if (ROR.getNode())
3432     return ROR;
3433   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3434   // iff (c1 & c2) == 0.
3435   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3436              isa<ConstantSDNode>(N0.getOperand(1))) {
3437     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3438     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3439       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3440       if (!COR.getNode())
3441         return SDValue();
3442       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3443                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3444                                      N0.getOperand(0), N1), COR);
3445     }
3446   }
3447   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3448   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3449     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3450     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3451
3452     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3453         LL.getValueType().isInteger()) {
3454       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3455       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3456       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3457           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3458         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3459                                      LR.getValueType(), LL, RL);
3460         AddToWorklist(ORNode.getNode());
3461         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3462       }
3463       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3464       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3465       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3466           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3467         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3468                                       LR.getValueType(), LL, RL);
3469         AddToWorklist(ANDNode.getNode());
3470         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3471       }
3472     }
3473     // canonicalize equivalent to ll == rl
3474     if (LL == RR && LR == RL) {
3475       Op1 = ISD::getSetCCSwappedOperands(Op1);
3476       std::swap(RL, RR);
3477     }
3478     if (LL == RL && LR == RR) {
3479       bool isInteger = LL.getValueType().isInteger();
3480       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3481       if (Result != ISD::SETCC_INVALID &&
3482           (!LegalOperations ||
3483            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3484             TLI.isOperationLegal(ISD::SETCC,
3485               getSetCCResultType(N0.getValueType())))))
3486         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3487                             LL, LR, Result);
3488     }
3489   }
3490
3491   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3492   if (N0.getOpcode() == N1.getOpcode()) {
3493     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3494     if (Tmp.getNode()) return Tmp;
3495   }
3496
3497   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3498   if (N0.getOpcode() == ISD::AND &&
3499       N1.getOpcode() == ISD::AND &&
3500       N0.getOperand(1).getOpcode() == ISD::Constant &&
3501       N1.getOperand(1).getOpcode() == ISD::Constant &&
3502       // Don't increase # computations.
3503       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3504     // We can only do this xform if we know that bits from X that are set in C2
3505     // but not in C1 are already zero.  Likewise for Y.
3506     const APInt &LHSMask =
3507       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3508     const APInt &RHSMask =
3509       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3510
3511     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3512         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3513       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3514                               N0.getOperand(0), N1.getOperand(0));
3515       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3516                          DAG.getConstant(LHSMask | RHSMask, VT));
3517     }
3518   }
3519
3520   // See if this is some rotate idiom.
3521   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3522     return SDValue(Rot, 0);
3523
3524   // Simplify the operands using demanded-bits information.
3525   if (!VT.isVector() &&
3526       SimplifyDemandedBits(SDValue(N, 0)))
3527     return SDValue(N, 0);
3528
3529   return SDValue();
3530 }
3531
3532 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3533 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3534   if (Op.getOpcode() == ISD::AND) {
3535     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3536       Mask = Op.getOperand(1);
3537       Op = Op.getOperand(0);
3538     } else {
3539       return false;
3540     }
3541   }
3542
3543   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3544     Shift = Op;
3545     return true;
3546   }
3547
3548   return false;
3549 }
3550
3551 // Return true if we can prove that, whenever Neg and Pos are both in the
3552 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3553 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3554 //
3555 //     (or (shift1 X, Neg), (shift2 X, Pos))
3556 //
3557 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3558 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3559 // to consider shift amounts with defined behavior.
3560 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3561   // If OpSize is a power of 2 then:
3562   //
3563   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3564   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3565   //
3566   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3567   // for the stronger condition:
3568   //
3569   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3570   //
3571   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3572   // we can just replace Neg with Neg' for the rest of the function.
3573   //
3574   // In other cases we check for the even stronger condition:
3575   //
3576   //     Neg == OpSize - Pos                                    [B]
3577   //
3578   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3579   // behavior if Pos == 0 (and consequently Neg == OpSize).
3580   //
3581   // We could actually use [A] whenever OpSize is a power of 2, but the
3582   // only extra cases that it would match are those uninteresting ones
3583   // where Neg and Pos are never in range at the same time.  E.g. for
3584   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3585   // as well as (sub 32, Pos), but:
3586   //
3587   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3588   //
3589   // always invokes undefined behavior for 32-bit X.
3590   //
3591   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3592   unsigned MaskLoBits = 0;
3593   if (Neg.getOpcode() == ISD::AND &&
3594       isPowerOf2_64(OpSize) &&
3595       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3596       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3597     Neg = Neg.getOperand(0);
3598     MaskLoBits = Log2_64(OpSize);
3599   }
3600
3601   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3602   if (Neg.getOpcode() != ISD::SUB)
3603     return 0;
3604   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3605   if (!NegC)
3606     return 0;
3607   SDValue NegOp1 = Neg.getOperand(1);
3608
3609   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3610   // Pos'.  The truncation is redundant for the purpose of the equality.
3611   if (MaskLoBits &&
3612       Pos.getOpcode() == ISD::AND &&
3613       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3614       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3615     Pos = Pos.getOperand(0);
3616
3617   // The condition we need is now:
3618   //
3619   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3620   //
3621   // If NegOp1 == Pos then we need:
3622   //
3623   //              OpSize & Mask == NegC & Mask
3624   //
3625   // (because "x & Mask" is a truncation and distributes through subtraction).
3626   APInt Width;
3627   if (Pos == NegOp1)
3628     Width = NegC->getAPIntValue();
3629   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3630   // Then the condition we want to prove becomes:
3631   //
3632   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3633   //
3634   // which, again because "x & Mask" is a truncation, becomes:
3635   //
3636   //                NegC & Mask == (OpSize - PosC) & Mask
3637   //              OpSize & Mask == (NegC + PosC) & Mask
3638   else if (Pos.getOpcode() == ISD::ADD &&
3639            Pos.getOperand(0) == NegOp1 &&
3640            Pos.getOperand(1).getOpcode() == ISD::Constant)
3641     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3642              NegC->getAPIntValue());
3643   else
3644     return false;
3645
3646   // Now we just need to check that OpSize & Mask == Width & Mask.
3647   if (MaskLoBits)
3648     // Opsize & Mask is 0 since Mask is Opsize - 1.
3649     return Width.getLoBits(MaskLoBits) == 0;
3650   return Width == OpSize;
3651 }
3652
3653 // A subroutine of MatchRotate used once we have found an OR of two opposite
3654 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3655 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3656 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3657 // Neg with outer conversions stripped away.
3658 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3659                                        SDValue Neg, SDValue InnerPos,
3660                                        SDValue InnerNeg, unsigned PosOpcode,
3661                                        unsigned NegOpcode, SDLoc DL) {
3662   // fold (or (shl x, (*ext y)),
3663   //          (srl x, (*ext (sub 32, y)))) ->
3664   //   (rotl x, y) or (rotr x, (sub 32, y))
3665   //
3666   // fold (or (shl x, (*ext (sub 32, y))),
3667   //          (srl x, (*ext y))) ->
3668   //   (rotr x, y) or (rotl x, (sub 32, y))
3669   EVT VT = Shifted.getValueType();
3670   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3671     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3672     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3673                        HasPos ? Pos : Neg).getNode();
3674   }
3675
3676   return nullptr;
3677 }
3678
3679 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3680 // idioms for rotate, and if the target supports rotation instructions, generate
3681 // a rot[lr].
3682 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3683   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3684   EVT VT = LHS.getValueType();
3685   if (!TLI.isTypeLegal(VT)) return nullptr;
3686
3687   // The target must have at least one rotate flavor.
3688   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3689   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3690   if (!HasROTL && !HasROTR) return nullptr;
3691
3692   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3693   SDValue LHSShift;   // The shift.
3694   SDValue LHSMask;    // AND value if any.
3695   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3696     return nullptr; // Not part of a rotate.
3697
3698   SDValue RHSShift;   // The shift.
3699   SDValue RHSMask;    // AND value if any.
3700   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3701     return nullptr; // Not part of a rotate.
3702
3703   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3704     return nullptr;   // Not shifting the same value.
3705
3706   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3707     return nullptr;   // Shifts must disagree.
3708
3709   // Canonicalize shl to left side in a shl/srl pair.
3710   if (RHSShift.getOpcode() == ISD::SHL) {
3711     std::swap(LHS, RHS);
3712     std::swap(LHSShift, RHSShift);
3713     std::swap(LHSMask , RHSMask );
3714   }
3715
3716   unsigned OpSizeInBits = VT.getSizeInBits();
3717   SDValue LHSShiftArg = LHSShift.getOperand(0);
3718   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3719   SDValue RHSShiftArg = RHSShift.getOperand(0);
3720   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3721
3722   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3723   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3724   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3725       RHSShiftAmt.getOpcode() == ISD::Constant) {
3726     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3727     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3728     if ((LShVal + RShVal) != OpSizeInBits)
3729       return nullptr;
3730
3731     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3732                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3733
3734     // If there is an AND of either shifted operand, apply it to the result.
3735     if (LHSMask.getNode() || RHSMask.getNode()) {
3736       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3737
3738       if (LHSMask.getNode()) {
3739         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3740         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3741       }
3742       if (RHSMask.getNode()) {
3743         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3744         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3745       }
3746
3747       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3748     }
3749
3750     return Rot.getNode();
3751   }
3752
3753   // If there is a mask here, and we have a variable shift, we can't be sure
3754   // that we're masking out the right stuff.
3755   if (LHSMask.getNode() || RHSMask.getNode())
3756     return nullptr;
3757
3758   // If the shift amount is sign/zext/any-extended just peel it off.
3759   SDValue LExtOp0 = LHSShiftAmt;
3760   SDValue RExtOp0 = RHSShiftAmt;
3761   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3762        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3763        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3764        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3765       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3769     LExtOp0 = LHSShiftAmt.getOperand(0);
3770     RExtOp0 = RHSShiftAmt.getOperand(0);
3771   }
3772
3773   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3774                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3775   if (TryL)
3776     return TryL;
3777
3778   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3779                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3780   if (TryR)
3781     return TryR;
3782
3783   return nullptr;
3784 }
3785
3786 SDValue DAGCombiner::visitXOR(SDNode *N) {
3787   SDValue N0 = N->getOperand(0);
3788   SDValue N1 = N->getOperand(1);
3789   SDValue LHS, RHS, CC;
3790   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3791   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3792   EVT VT = N0.getValueType();
3793
3794   // fold vector ops
3795   if (VT.isVector()) {
3796     SDValue FoldedVOp = SimplifyVBinOp(N);
3797     if (FoldedVOp.getNode()) return FoldedVOp;
3798
3799     // fold (xor x, 0) -> x, vector edition
3800     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3801       return N1;
3802     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3803       return N0;
3804   }
3805
3806   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3807   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3808     return DAG.getConstant(0, VT);
3809   // fold (xor x, undef) -> undef
3810   if (N0.getOpcode() == ISD::UNDEF)
3811     return N0;
3812   if (N1.getOpcode() == ISD::UNDEF)
3813     return N1;
3814   // fold (xor c1, c2) -> c1^c2
3815   if (N0C && N1C)
3816     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3817   // canonicalize constant to RHS
3818   if (N0C && !N1C)
3819     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3820   // fold (xor x, 0) -> x
3821   if (N1C && N1C->isNullValue())
3822     return N0;
3823   // reassociate xor
3824   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3825   if (RXOR.getNode())
3826     return RXOR;
3827
3828   // fold !(x cc y) -> (x !cc y)
3829   if (N1C && N1C->getAPIntValue().isAllOnesValue() &&
3830       isSetCCEquivalent(N0, LHS, RHS, CC)) {
3831     bool isInt = LHS.getValueType().isInteger();
3832     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3833                                                isInt);
3834
3835     if (!LegalOperations ||
3836         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3837       switch (N0.getOpcode()) {
3838       default:
3839         llvm_unreachable("Unhandled SetCC Equivalent!");
3840       case ISD::SETCC:
3841         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3842       case ISD::SELECT_CC:
3843         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3844                                N0.getOperand(3), NotCC);
3845       }
3846     }
3847   }
3848
3849   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3850   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3851       N0.getNode()->hasOneUse() &&
3852       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3853     SDValue V = N0.getOperand(0);
3854     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3855                     DAG.getConstant(1, V.getValueType()));
3856     AddToWorklist(V.getNode());
3857     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3858   }
3859
3860   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3861   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3862       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3863     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3864     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3865       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3866       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3867       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3868       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3869       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3870     }
3871   }
3872   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3873   if (N1C && N1C->isAllOnesValue() &&
3874       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3875     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3876     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3877       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3878       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3879       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3880       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3881       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3882     }
3883   }
3884   // fold (xor (and x, y), y) -> (and (not x), y)
3885   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3886       N0->getOperand(1) == N1) {
3887     SDValue X = N0->getOperand(0);
3888     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3889     AddToWorklist(NotX.getNode());
3890     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3891   }
3892   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3893   if (N1C && N0.getOpcode() == ISD::XOR) {
3894     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3895     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3896     if (N00C)
3897       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3898                          DAG.getConstant(N1C->getAPIntValue() ^
3899                                          N00C->getAPIntValue(), VT));
3900     if (N01C)
3901       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3902                          DAG.getConstant(N1C->getAPIntValue() ^
3903                                          N01C->getAPIntValue(), VT));
3904   }
3905   // fold (xor x, x) -> 0
3906   if (N0 == N1)
3907     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3908
3909   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3910   if (N0.getOpcode() == N1.getOpcode()) {
3911     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3912     if (Tmp.getNode()) return Tmp;
3913   }
3914
3915   // Simplify the expression using non-local knowledge.
3916   if (!VT.isVector() &&
3917       SimplifyDemandedBits(SDValue(N, 0)))
3918     return SDValue(N, 0);
3919
3920   return SDValue();
3921 }
3922
3923 /// Handle transforms common to the three shifts, when the shift amount is a
3924 /// constant.
3925 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3926   // We can't and shouldn't fold opaque constants.
3927   if (Amt->isOpaque())
3928     return SDValue();
3929
3930   SDNode *LHS = N->getOperand(0).getNode();
3931   if (!LHS->hasOneUse()) return SDValue();
3932
3933   // We want to pull some binops through shifts, so that we have (and (shift))
3934   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3935   // thing happens with address calculations, so it's important to canonicalize
3936   // it.
3937   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3938
3939   switch (LHS->getOpcode()) {
3940   default: return SDValue();
3941   case ISD::OR:
3942   case ISD::XOR:
3943     HighBitSet = false; // We can only transform sra if the high bit is clear.
3944     break;
3945   case ISD::AND:
3946     HighBitSet = true;  // We can only transform sra if the high bit is set.
3947     break;
3948   case ISD::ADD:
3949     if (N->getOpcode() != ISD::SHL)
3950       return SDValue(); // only shl(add) not sr[al](add).
3951     HighBitSet = false; // We can only transform sra if the high bit is clear.
3952     break;
3953   }
3954
3955   // We require the RHS of the binop to be a constant and not opaque as well.
3956   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3957   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3958
3959   // FIXME: disable this unless the input to the binop is a shift by a constant.
3960   // If it is not a shift, it pessimizes some common cases like:
3961   //
3962   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3963   //    int bar(int *X, int i) { return X[i & 255]; }
3964   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3965   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3966        BinOpLHSVal->getOpcode() != ISD::SRA &&
3967        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3968       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3969     return SDValue();
3970
3971   EVT VT = N->getValueType(0);
3972
3973   // If this is a signed shift right, and the high bit is modified by the
3974   // logical operation, do not perform the transformation. The highBitSet
3975   // boolean indicates the value of the high bit of the constant which would
3976   // cause it to be modified for this operation.
3977   if (N->getOpcode() == ISD::SRA) {
3978     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3979     if (BinOpRHSSignSet != HighBitSet)
3980       return SDValue();
3981   }
3982
3983   if (!TLI.isDesirableToCommuteWithShift(LHS))
3984     return SDValue();
3985
3986   // Fold the constants, shifting the binop RHS by the shift amount.
3987   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3988                                N->getValueType(0),
3989                                LHS->getOperand(1), N->getOperand(1));
3990   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3991
3992   // Create the new shift.
3993   SDValue NewShift = DAG.getNode(N->getOpcode(),
3994                                  SDLoc(LHS->getOperand(0)),
3995                                  VT, LHS->getOperand(0), N->getOperand(1));
3996
3997   // Create the new binop.
3998   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3999 }
4000
4001 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4002   assert(N->getOpcode() == ISD::TRUNCATE);
4003   assert(N->getOperand(0).getOpcode() == ISD::AND);
4004
4005   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4006   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4007     SDValue N01 = N->getOperand(0).getOperand(1);
4008
4009     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4010       EVT TruncVT = N->getValueType(0);
4011       SDValue N00 = N->getOperand(0).getOperand(0);
4012       APInt TruncC = N01C->getAPIntValue();
4013       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4014
4015       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4016                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4017                          DAG.getConstant(TruncC, TruncVT));
4018     }
4019   }
4020
4021   return SDValue();
4022 }
4023
4024 SDValue DAGCombiner::visitRotate(SDNode *N) {
4025   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4026   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4027       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4028     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4029     if (NewOp1.getNode())
4030       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4031                          N->getOperand(0), NewOp1);
4032   }
4033   return SDValue();
4034 }
4035
4036 SDValue DAGCombiner::visitSHL(SDNode *N) {
4037   SDValue N0 = N->getOperand(0);
4038   SDValue N1 = N->getOperand(1);
4039   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4040   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4041   EVT VT = N0.getValueType();
4042   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4043
4044   // fold vector ops
4045   if (VT.isVector()) {
4046     SDValue FoldedVOp = SimplifyVBinOp(N);
4047     if (FoldedVOp.getNode()) return FoldedVOp;
4048
4049     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4050     // If setcc produces all-one true value then:
4051     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4052     if (N1CV && N1CV->isConstant()) {
4053       if (N0.getOpcode() == ISD::AND) {
4054         SDValue N00 = N0->getOperand(0);
4055         SDValue N01 = N0->getOperand(1);
4056         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4057
4058         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4059             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4060                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4061           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4062           if (C.getNode())
4063             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4064         }
4065       } else {
4066         N1C = isConstOrConstSplat(N1);
4067       }
4068     }
4069   }
4070
4071   // fold (shl c1, c2) -> c1<<c2
4072   if (N0C && N1C)
4073     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4074   // fold (shl 0, x) -> 0
4075   if (N0C && N0C->isNullValue())
4076     return N0;
4077   // fold (shl x, c >= size(x)) -> undef
4078   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4079     return DAG.getUNDEF(VT);
4080   // fold (shl x, 0) -> x
4081   if (N1C && N1C->isNullValue())
4082     return N0;
4083   // fold (shl undef, x) -> 0
4084   if (N0.getOpcode() == ISD::UNDEF)
4085     return DAG.getConstant(0, VT);
4086   // if (shl x, c) is known to be zero, return 0
4087   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4088                             APInt::getAllOnesValue(OpSizeInBits)))
4089     return DAG.getConstant(0, VT);
4090   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4091   if (N1.getOpcode() == ISD::TRUNCATE &&
4092       N1.getOperand(0).getOpcode() == ISD::AND) {
4093     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4094     if (NewOp1.getNode())
4095       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4096   }
4097
4098   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4099     return SDValue(N, 0);
4100
4101   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4102   if (N1C && N0.getOpcode() == ISD::SHL) {
4103     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4104       uint64_t c1 = N0C1->getZExtValue();
4105       uint64_t c2 = N1C->getZExtValue();
4106       if (c1 + c2 >= OpSizeInBits)
4107         return DAG.getConstant(0, VT);
4108       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4109                          DAG.getConstant(c1 + c2, N1.getValueType()));
4110     }
4111   }
4112
4113   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4114   // For this to be valid, the second form must not preserve any of the bits
4115   // that are shifted out by the inner shift in the first form.  This means
4116   // the outer shift size must be >= the number of bits added by the ext.
4117   // As a corollary, we don't care what kind of ext it is.
4118   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4119               N0.getOpcode() == ISD::ANY_EXTEND ||
4120               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4121       N0.getOperand(0).getOpcode() == ISD::SHL) {
4122     SDValue N0Op0 = N0.getOperand(0);
4123     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4124       uint64_t c1 = N0Op0C1->getZExtValue();
4125       uint64_t c2 = N1C->getZExtValue();
4126       EVT InnerShiftVT = N0Op0.getValueType();
4127       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4128       if (c2 >= OpSizeInBits - InnerShiftSize) {
4129         if (c1 + c2 >= OpSizeInBits)
4130           return DAG.getConstant(0, VT);
4131         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4132                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4133                                        N0Op0->getOperand(0)),
4134                            DAG.getConstant(c1 + c2, N1.getValueType()));
4135       }
4136     }
4137   }
4138
4139   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4140   // Only fold this if the inner zext has no other uses to avoid increasing
4141   // the total number of instructions.
4142   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4143       N0.getOperand(0).getOpcode() == ISD::SRL) {
4144     SDValue N0Op0 = N0.getOperand(0);
4145     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4146       uint64_t c1 = N0Op0C1->getZExtValue();
4147       if (c1 < VT.getScalarSizeInBits()) {
4148         uint64_t c2 = N1C->getZExtValue();
4149         if (c1 == c2) {
4150           SDValue NewOp0 = N0.getOperand(0);
4151           EVT CountVT = NewOp0.getOperand(1).getValueType();
4152           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4153                                        NewOp0, DAG.getConstant(c2, CountVT));
4154           AddToWorklist(NewSHL.getNode());
4155           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4156         }
4157       }
4158     }
4159   }
4160
4161   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4162   //                               (and (srl x, (sub c1, c2), MASK)
4163   // Only fold this if the inner shift has no other uses -- if it does, folding
4164   // this will increase the total number of instructions.
4165   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4166     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4167       uint64_t c1 = N0C1->getZExtValue();
4168       if (c1 < OpSizeInBits) {
4169         uint64_t c2 = N1C->getZExtValue();
4170         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4171         SDValue Shift;
4172         if (c2 > c1) {
4173           Mask = Mask.shl(c2 - c1);
4174           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4175                               DAG.getConstant(c2 - c1, N1.getValueType()));
4176         } else {
4177           Mask = Mask.lshr(c1 - c2);
4178           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4179                               DAG.getConstant(c1 - c2, N1.getValueType()));
4180         }
4181         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4182                            DAG.getConstant(Mask, VT));
4183       }
4184     }
4185   }
4186   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4187   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4188     unsigned BitSize = VT.getScalarSizeInBits();
4189     SDValue HiBitsMask =
4190       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4191                                             BitSize - N1C->getZExtValue()), VT);
4192     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4193                        HiBitsMask);
4194   }
4195
4196   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4197   // Variant of version done on multiply, except mul by a power of 2 is turned
4198   // into a shift.
4199   APInt Val;
4200   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4201       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4202        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4203     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4204     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4205     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4206   }
4207
4208   if (N1C) {
4209     SDValue NewSHL = visitShiftByConstant(N, N1C);
4210     if (NewSHL.getNode())
4211       return NewSHL;
4212   }
4213
4214   return SDValue();
4215 }
4216
4217 SDValue DAGCombiner::visitSRA(SDNode *N) {
4218   SDValue N0 = N->getOperand(0);
4219   SDValue N1 = N->getOperand(1);
4220   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4221   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4222   EVT VT = N0.getValueType();
4223   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4224
4225   // fold vector ops
4226   if (VT.isVector()) {
4227     SDValue FoldedVOp = SimplifyVBinOp(N);
4228     if (FoldedVOp.getNode()) return FoldedVOp;
4229
4230     N1C = isConstOrConstSplat(N1);
4231   }
4232
4233   // fold (sra c1, c2) -> (sra c1, c2)
4234   if (N0C && N1C)
4235     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4236   // fold (sra 0, x) -> 0
4237   if (N0C && N0C->isNullValue())
4238     return N0;
4239   // fold (sra -1, x) -> -1
4240   if (N0C && N0C->isAllOnesValue())
4241     return N0;
4242   // fold (sra x, (setge c, size(x))) -> undef
4243   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4244     return DAG.getUNDEF(VT);
4245   // fold (sra x, 0) -> x
4246   if (N1C && N1C->isNullValue())
4247     return N0;
4248   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4249   // sext_inreg.
4250   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4251     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4252     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4253     if (VT.isVector())
4254       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4255                                ExtVT, VT.getVectorNumElements());
4256     if ((!LegalOperations ||
4257          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4258       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4259                          N0.getOperand(0), DAG.getValueType(ExtVT));
4260   }
4261
4262   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4263   if (N1C && N0.getOpcode() == ISD::SRA) {
4264     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4265       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4266       if (Sum >= OpSizeInBits)
4267         Sum = OpSizeInBits - 1;
4268       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4269                          DAG.getConstant(Sum, N1.getValueType()));
4270     }
4271   }
4272
4273   // fold (sra (shl X, m), (sub result_size, n))
4274   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4275   // result_size - n != m.
4276   // If truncate is free for the target sext(shl) is likely to result in better
4277   // code.
4278   if (N0.getOpcode() == ISD::SHL && N1C) {
4279     // Get the two constanst of the shifts, CN0 = m, CN = n.
4280     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4281     if (N01C) {
4282       LLVMContext &Ctx = *DAG.getContext();
4283       // Determine what the truncate's result bitsize and type would be.
4284       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4285
4286       if (VT.isVector())
4287         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4288
4289       // Determine the residual right-shift amount.
4290       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4291
4292       // If the shift is not a no-op (in which case this should be just a sign
4293       // extend already), the truncated to type is legal, sign_extend is legal
4294       // on that type, and the truncate to that type is both legal and free,
4295       // perform the transform.
4296       if ((ShiftAmt > 0) &&
4297           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4298           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4299           TLI.isTruncateFree(VT, TruncVT)) {
4300
4301           SDValue Amt = DAG.getConstant(ShiftAmt,
4302               getShiftAmountTy(N0.getOperand(0).getValueType()));
4303           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4304                                       N0.getOperand(0), Amt);
4305           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4306                                       Shift);
4307           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4308                              N->getValueType(0), Trunc);
4309       }
4310     }
4311   }
4312
4313   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4314   if (N1.getOpcode() == ISD::TRUNCATE &&
4315       N1.getOperand(0).getOpcode() == ISD::AND) {
4316     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4317     if (NewOp1.getNode())
4318       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4319   }
4320
4321   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4322   //      if c1 is equal to the number of bits the trunc removes
4323   if (N0.getOpcode() == ISD::TRUNCATE &&
4324       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4325        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4326       N0.getOperand(0).hasOneUse() &&
4327       N0.getOperand(0).getOperand(1).hasOneUse() &&
4328       N1C) {
4329     SDValue N0Op0 = N0.getOperand(0);
4330     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4331       unsigned LargeShiftVal = LargeShift->getZExtValue();
4332       EVT LargeVT = N0Op0.getValueType();
4333
4334       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4335         SDValue Amt =
4336           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4337                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4338         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4339                                   N0Op0.getOperand(0), Amt);
4340         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4341       }
4342     }
4343   }
4344
4345   // Simplify, based on bits shifted out of the LHS.
4346   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4347     return SDValue(N, 0);
4348
4349
4350   // If the sign bit is known to be zero, switch this to a SRL.
4351   if (DAG.SignBitIsZero(N0))
4352     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4353
4354   if (N1C) {
4355     SDValue NewSRA = visitShiftByConstant(N, N1C);
4356     if (NewSRA.getNode())
4357       return NewSRA;
4358   }
4359
4360   return SDValue();
4361 }
4362
4363 SDValue DAGCombiner::visitSRL(SDNode *N) {
4364   SDValue N0 = N->getOperand(0);
4365   SDValue N1 = N->getOperand(1);
4366   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4367   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4368   EVT VT = N0.getValueType();
4369   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4370
4371   // fold vector ops
4372   if (VT.isVector()) {
4373     SDValue FoldedVOp = SimplifyVBinOp(N);
4374     if (FoldedVOp.getNode()) return FoldedVOp;
4375
4376     N1C = isConstOrConstSplat(N1);
4377   }
4378
4379   // fold (srl c1, c2) -> c1 >>u c2
4380   if (N0C && N1C)
4381     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4382   // fold (srl 0, x) -> 0
4383   if (N0C && N0C->isNullValue())
4384     return N0;
4385   // fold (srl x, c >= size(x)) -> undef
4386   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4387     return DAG.getUNDEF(VT);
4388   // fold (srl x, 0) -> x
4389   if (N1C && N1C->isNullValue())
4390     return N0;
4391   // if (srl x, c) is known to be zero, return 0
4392   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4393                                    APInt::getAllOnesValue(OpSizeInBits)))
4394     return DAG.getConstant(0, VT);
4395
4396   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4397   if (N1C && N0.getOpcode() == ISD::SRL) {
4398     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4399       uint64_t c1 = N01C->getZExtValue();
4400       uint64_t c2 = N1C->getZExtValue();
4401       if (c1 + c2 >= OpSizeInBits)
4402         return DAG.getConstant(0, VT);
4403       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4404                          DAG.getConstant(c1 + c2, N1.getValueType()));
4405     }
4406   }
4407
4408   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4409   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4410       N0.getOperand(0).getOpcode() == ISD::SRL &&
4411       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4412     uint64_t c1 =
4413       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4414     uint64_t c2 = N1C->getZExtValue();
4415     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4416     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4417     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4418     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4419     if (c1 + OpSizeInBits == InnerShiftSize) {
4420       if (c1 + c2 >= InnerShiftSize)
4421         return DAG.getConstant(0, VT);
4422       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4423                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4424                                      N0.getOperand(0)->getOperand(0),
4425                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4426     }
4427   }
4428
4429   // fold (srl (shl x, c), c) -> (and x, cst2)
4430   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4431     unsigned BitSize = N0.getScalarValueSizeInBits();
4432     if (BitSize <= 64) {
4433       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4434       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4435                          DAG.getConstant(~0ULL >> ShAmt, VT));
4436     }
4437   }
4438
4439   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4440   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4441     // Shifting in all undef bits?
4442     EVT SmallVT = N0.getOperand(0).getValueType();
4443     unsigned BitSize = SmallVT.getScalarSizeInBits();
4444     if (N1C->getZExtValue() >= BitSize)
4445       return DAG.getUNDEF(VT);
4446
4447     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4448       uint64_t ShiftAmt = N1C->getZExtValue();
4449       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4450                                        N0.getOperand(0),
4451                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4452       AddToWorklist(SmallShift.getNode());
4453       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4454       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4455                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4456                          DAG.getConstant(Mask, VT));
4457     }
4458   }
4459
4460   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4461   // bit, which is unmodified by sra.
4462   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4463     if (N0.getOpcode() == ISD::SRA)
4464       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4465   }
4466
4467   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4468   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4469       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4470     APInt KnownZero, KnownOne;
4471     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4472
4473     // If any of the input bits are KnownOne, then the input couldn't be all
4474     // zeros, thus the result of the srl will always be zero.
4475     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4476
4477     // If all of the bits input the to ctlz node are known to be zero, then
4478     // the result of the ctlz is "32" and the result of the shift is one.
4479     APInt UnknownBits = ~KnownZero;
4480     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4481
4482     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4483     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4484       // Okay, we know that only that the single bit specified by UnknownBits
4485       // could be set on input to the CTLZ node. If this bit is set, the SRL
4486       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4487       // to an SRL/XOR pair, which is likely to simplify more.
4488       unsigned ShAmt = UnknownBits.countTrailingZeros();
4489       SDValue Op = N0.getOperand(0);
4490
4491       if (ShAmt) {
4492         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4493                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4494         AddToWorklist(Op.getNode());
4495       }
4496
4497       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4498                          Op, DAG.getConstant(1, VT));
4499     }
4500   }
4501
4502   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4503   if (N1.getOpcode() == ISD::TRUNCATE &&
4504       N1.getOperand(0).getOpcode() == ISD::AND) {
4505     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4506     if (NewOp1.getNode())
4507       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4508   }
4509
4510   // fold operands of srl based on knowledge that the low bits are not
4511   // demanded.
4512   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4513     return SDValue(N, 0);
4514
4515   if (N1C) {
4516     SDValue NewSRL = visitShiftByConstant(N, N1C);
4517     if (NewSRL.getNode())
4518       return NewSRL;
4519   }
4520
4521   // Attempt to convert a srl of a load into a narrower zero-extending load.
4522   SDValue NarrowLoad = ReduceLoadWidth(N);
4523   if (NarrowLoad.getNode())
4524     return NarrowLoad;
4525
4526   // Here is a common situation. We want to optimize:
4527   //
4528   //   %a = ...
4529   //   %b = and i32 %a, 2
4530   //   %c = srl i32 %b, 1
4531   //   brcond i32 %c ...
4532   //
4533   // into
4534   //
4535   //   %a = ...
4536   //   %b = and %a, 2
4537   //   %c = setcc eq %b, 0
4538   //   brcond %c ...
4539   //
4540   // However when after the source operand of SRL is optimized into AND, the SRL
4541   // itself may not be optimized further. Look for it and add the BRCOND into
4542   // the worklist.
4543   if (N->hasOneUse()) {
4544     SDNode *Use = *N->use_begin();
4545     if (Use->getOpcode() == ISD::BRCOND)
4546       AddToWorklist(Use);
4547     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4548       // Also look pass the truncate.
4549       Use = *Use->use_begin();
4550       if (Use->getOpcode() == ISD::BRCOND)
4551         AddToWorklist(Use);
4552     }
4553   }
4554
4555   return SDValue();
4556 }
4557
4558 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4559   SDValue N0 = N->getOperand(0);
4560   EVT VT = N->getValueType(0);
4561
4562   // fold (ctlz c1) -> c2
4563   if (isa<ConstantSDNode>(N0))
4564     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   EVT VT = N->getValueType(0);
4571
4572   // fold (ctlz_zero_undef c1) -> c2
4573   if (isa<ConstantSDNode>(N0))
4574     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4575   return SDValue();
4576 }
4577
4578 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4579   SDValue N0 = N->getOperand(0);
4580   EVT VT = N->getValueType(0);
4581
4582   // fold (cttz c1) -> c2
4583   if (isa<ConstantSDNode>(N0))
4584     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4585   return SDValue();
4586 }
4587
4588 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4589   SDValue N0 = N->getOperand(0);
4590   EVT VT = N->getValueType(0);
4591
4592   // fold (cttz_zero_undef c1) -> c2
4593   if (isa<ConstantSDNode>(N0))
4594     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4595   return SDValue();
4596 }
4597
4598 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4599   SDValue N0 = N->getOperand(0);
4600   EVT VT = N->getValueType(0);
4601
4602   // fold (ctpop c1) -> c2
4603   if (isa<ConstantSDNode>(N0))
4604     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4605   return SDValue();
4606 }
4607
4608 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4609   SDValue N0 = N->getOperand(0);
4610   SDValue N1 = N->getOperand(1);
4611   SDValue N2 = N->getOperand(2);
4612   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4613   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4614   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4615   EVT VT = N->getValueType(0);
4616   EVT VT0 = N0.getValueType();
4617
4618   // fold (select C, X, X) -> X
4619   if (N1 == N2)
4620     return N1;
4621   // fold (select true, X, Y) -> X
4622   if (N0C && !N0C->isNullValue())
4623     return N1;
4624   // fold (select false, X, Y) -> Y
4625   if (N0C && N0C->isNullValue())
4626     return N2;
4627   // fold (select C, 1, X) -> (or C, X)
4628   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4629     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4630   // fold (select C, 0, 1) -> (xor C, 1)
4631   // We can't do this reliably if integer based booleans have different contents
4632   // to floating point based booleans. This is because we can't tell whether we
4633   // have an integer-based boolean or a floating-point-based boolean unless we
4634   // can find the SETCC that produced it and inspect its operands. This is
4635   // fairly easy if C is the SETCC node, but it can potentially be
4636   // undiscoverable (or not reasonably discoverable). For example, it could be
4637   // in another basic block or it could require searching a complicated
4638   // expression.
4639   if (VT.isInteger() &&
4640       (VT0 == MVT::i1 || (VT0.isInteger() &&
4641                           TLI.getBooleanContents(false, false) ==
4642                               TLI.getBooleanContents(false, true) &&
4643                           TLI.getBooleanContents(false, false) ==
4644                               TargetLowering::ZeroOrOneBooleanContent)) &&
4645       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4646     SDValue XORNode;
4647     if (VT == VT0)
4648       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4649                          N0, DAG.getConstant(1, VT0));
4650     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4651                           N0, DAG.getConstant(1, VT0));
4652     AddToWorklist(XORNode.getNode());
4653     if (VT.bitsGT(VT0))
4654       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4655     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4656   }
4657   // fold (select C, 0, X) -> (and (not C), X)
4658   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4659     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4660     AddToWorklist(NOTNode.getNode());
4661     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4662   }
4663   // fold (select C, X, 1) -> (or (not C), X)
4664   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4665     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4666     AddToWorklist(NOTNode.getNode());
4667     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4668   }
4669   // fold (select C, X, 0) -> (and C, X)
4670   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4671     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4672   // fold (select X, X, Y) -> (or X, Y)
4673   // fold (select X, 1, Y) -> (or X, Y)
4674   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4675     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4676   // fold (select X, Y, X) -> (and X, Y)
4677   // fold (select X, Y, 0) -> (and X, Y)
4678   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4679     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4680
4681   // If we can fold this based on the true/false value, do so.
4682   if (SimplifySelectOps(N, N1, N2))
4683     return SDValue(N, 0);  // Don't revisit N.
4684
4685   // fold selects based on a setcc into other things, such as min/max/abs
4686   if (N0.getOpcode() == ISD::SETCC) {
4687     if ((!LegalOperations &&
4688          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4689         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4690       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4691                          N0.getOperand(0), N0.getOperand(1),
4692                          N1, N2, N0.getOperand(2));
4693     return SimplifySelect(SDLoc(N), N0, N1, N2);
4694   }
4695
4696   return SDValue();
4697 }
4698
4699 static
4700 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4701   SDLoc DL(N);
4702   EVT LoVT, HiVT;
4703   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4704
4705   // Split the inputs.
4706   SDValue Lo, Hi, LL, LH, RL, RH;
4707   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4708   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4709
4710   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4711   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4712
4713   return std::make_pair(Lo, Hi);
4714 }
4715
4716 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4717 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4718 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4719   SDLoc dl(N);
4720   SDValue Cond = N->getOperand(0);
4721   SDValue LHS = N->getOperand(1);
4722   SDValue RHS = N->getOperand(2);
4723   EVT VT = N->getValueType(0);
4724   int NumElems = VT.getVectorNumElements();
4725   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4726          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4727          Cond.getOpcode() == ISD::BUILD_VECTOR);
4728
4729   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4730   // binary ones here.
4731   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4732     return SDValue();
4733
4734   // We're sure we have an even number of elements due to the
4735   // concat_vectors we have as arguments to vselect.
4736   // Skip BV elements until we find one that's not an UNDEF
4737   // After we find an UNDEF element, keep looping until we get to half the
4738   // length of the BV and see if all the non-undef nodes are the same.
4739   ConstantSDNode *BottomHalf = nullptr;
4740   for (int i = 0; i < NumElems / 2; ++i) {
4741     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4742       continue;
4743
4744     if (BottomHalf == nullptr)
4745       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4746     else if (Cond->getOperand(i).getNode() != BottomHalf)
4747       return SDValue();
4748   }
4749
4750   // Do the same for the second half of the BuildVector
4751   ConstantSDNode *TopHalf = nullptr;
4752   for (int i = NumElems / 2; i < NumElems; ++i) {
4753     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4754       continue;
4755
4756     if (TopHalf == nullptr)
4757       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4758     else if (Cond->getOperand(i).getNode() != TopHalf)
4759       return SDValue();
4760   }
4761
4762   assert(TopHalf && BottomHalf &&
4763          "One half of the selector was all UNDEFs and the other was all the "
4764          "same value. This should have been addressed before this function.");
4765   return DAG.getNode(
4766       ISD::CONCAT_VECTORS, dl, VT,
4767       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4768       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4769 }
4770
4771 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4772   SDValue N0 = N->getOperand(0);
4773   SDValue N1 = N->getOperand(1);
4774   SDValue N2 = N->getOperand(2);
4775   SDLoc DL(N);
4776
4777   // Canonicalize integer abs.
4778   // vselect (setg[te] X,  0),  X, -X ->
4779   // vselect (setgt    X, -1),  X, -X ->
4780   // vselect (setl[te] X,  0), -X,  X ->
4781   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4782   if (N0.getOpcode() == ISD::SETCC) {
4783     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4784     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4785     bool isAbs = false;
4786     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4787
4788     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4789          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4790         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4791       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4792     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4793              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4794       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4795
4796     if (isAbs) {
4797       EVT VT = LHS.getValueType();
4798       SDValue Shift = DAG.getNode(
4799           ISD::SRA, DL, VT, LHS,
4800           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4801       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4802       AddToWorklist(Shift.getNode());
4803       AddToWorklist(Add.getNode());
4804       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4805     }
4806   }
4807
4808   // If the VSELECT result requires splitting and the mask is provided by a
4809   // SETCC, then split both nodes and its operands before legalization. This
4810   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4811   // and enables future optimizations (e.g. min/max pattern matching on X86).
4812   if (N0.getOpcode() == ISD::SETCC) {
4813     EVT VT = N->getValueType(0);
4814
4815     // Check if any splitting is required.
4816     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4817         TargetLowering::TypeSplitVector)
4818       return SDValue();
4819
4820     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4821     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4822     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4823     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4824
4825     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4826     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4827
4828     // Add the new VSELECT nodes to the work list in case they need to be split
4829     // again.
4830     AddToWorklist(Lo.getNode());
4831     AddToWorklist(Hi.getNode());
4832
4833     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4834   }
4835
4836   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4837   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4838     return N1;
4839   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4840   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4841     return N2;
4842
4843   // The ConvertSelectToConcatVector function is assuming both the above
4844   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4845   // and addressed.
4846   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4847       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4848       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4849     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4850     if (CV.getNode())
4851       return CV;
4852   }
4853
4854   return SDValue();
4855 }
4856
4857 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4858   SDValue N0 = N->getOperand(0);
4859   SDValue N1 = N->getOperand(1);
4860   SDValue N2 = N->getOperand(2);
4861   SDValue N3 = N->getOperand(3);
4862   SDValue N4 = N->getOperand(4);
4863   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4864
4865   // fold select_cc lhs, rhs, x, x, cc -> x
4866   if (N2 == N3)
4867     return N2;
4868
4869   // Determine if the condition we're dealing with is constant
4870   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4871                               N0, N1, CC, SDLoc(N), false);
4872   if (SCC.getNode()) {
4873     AddToWorklist(SCC.getNode());
4874
4875     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4876       if (!SCCC->isNullValue())
4877         return N2;    // cond always true -> true val
4878       else
4879         return N3;    // cond always false -> false val
4880     }
4881
4882     // Fold to a simpler select_cc
4883     if (SCC.getOpcode() == ISD::SETCC)
4884       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4885                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4886                          SCC.getOperand(2));
4887   }
4888
4889   // If we can fold this based on the true/false value, do so.
4890   if (SimplifySelectOps(N, N2, N3))
4891     return SDValue(N, 0);  // Don't revisit N.
4892
4893   // fold select_cc into other things, such as min/max/abs
4894   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4895 }
4896
4897 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4898   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4899                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4900                        SDLoc(N));
4901 }
4902
4903 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4904 // dag node into a ConstantSDNode or a build_vector of constants.
4905 // This function is called by the DAGCombiner when visiting sext/zext/aext
4906 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4907 // Vector extends are not folded if operations are legal; this is to
4908 // avoid introducing illegal build_vector dag nodes.
4909 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4910                                          SelectionDAG &DAG, bool LegalTypes,
4911                                          bool LegalOperations) {
4912   unsigned Opcode = N->getOpcode();
4913   SDValue N0 = N->getOperand(0);
4914   EVT VT = N->getValueType(0);
4915
4916   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4917          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4918
4919   // fold (sext c1) -> c1
4920   // fold (zext c1) -> c1
4921   // fold (aext c1) -> c1
4922   if (isa<ConstantSDNode>(N0))
4923     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4924
4925   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4926   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4927   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4928   EVT SVT = VT.getScalarType();
4929   if (!(VT.isVector() &&
4930       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4931       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4932     return nullptr;
4933
4934   // We can fold this node into a build_vector.
4935   unsigned VTBits = SVT.getSizeInBits();
4936   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4937   unsigned ShAmt = VTBits - EVTBits;
4938   SmallVector<SDValue, 8> Elts;
4939   unsigned NumElts = N0->getNumOperands();
4940   SDLoc DL(N);
4941
4942   for (unsigned i=0; i != NumElts; ++i) {
4943     SDValue Op = N0->getOperand(i);
4944     if (Op->getOpcode() == ISD::UNDEF) {
4945       Elts.push_back(DAG.getUNDEF(SVT));
4946       continue;
4947     }
4948
4949     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4950     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4951     if (Opcode == ISD::SIGN_EXTEND)
4952       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4953                                      SVT));
4954     else
4955       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4956                                      SVT));
4957   }
4958
4959   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4960 }
4961
4962 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4963 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4964 // transformation. Returns true if extension are possible and the above
4965 // mentioned transformation is profitable.
4966 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4967                                     unsigned ExtOpc,
4968                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4969                                     const TargetLowering &TLI) {
4970   bool HasCopyToRegUses = false;
4971   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4972   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4973                             UE = N0.getNode()->use_end();
4974        UI != UE; ++UI) {
4975     SDNode *User = *UI;
4976     if (User == N)
4977       continue;
4978     if (UI.getUse().getResNo() != N0.getResNo())
4979       continue;
4980     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4981     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4982       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4983       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4984         // Sign bits will be lost after a zext.
4985         return false;
4986       bool Add = false;
4987       for (unsigned i = 0; i != 2; ++i) {
4988         SDValue UseOp = User->getOperand(i);
4989         if (UseOp == N0)
4990           continue;
4991         if (!isa<ConstantSDNode>(UseOp))
4992           return false;
4993         Add = true;
4994       }
4995       if (Add)
4996         ExtendNodes.push_back(User);
4997       continue;
4998     }
4999     // If truncates aren't free and there are users we can't
5000     // extend, it isn't worthwhile.
5001     if (!isTruncFree)
5002       return false;
5003     // Remember if this value is live-out.
5004     if (User->getOpcode() == ISD::CopyToReg)
5005       HasCopyToRegUses = true;
5006   }
5007
5008   if (HasCopyToRegUses) {
5009     bool BothLiveOut = false;
5010     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5011          UI != UE; ++UI) {
5012       SDUse &Use = UI.getUse();
5013       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5014         BothLiveOut = true;
5015         break;
5016       }
5017     }
5018     if (BothLiveOut)
5019       // Both unextended and extended values are live out. There had better be
5020       // a good reason for the transformation.
5021       return ExtendNodes.size();
5022   }
5023   return true;
5024 }
5025
5026 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5027                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5028                                   ISD::NodeType ExtType) {
5029   // Extend SetCC uses if necessary.
5030   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5031     SDNode *SetCC = SetCCs[i];
5032     SmallVector<SDValue, 4> Ops;
5033
5034     for (unsigned j = 0; j != 2; ++j) {
5035       SDValue SOp = SetCC->getOperand(j);
5036       if (SOp == Trunc)
5037         Ops.push_back(ExtLoad);
5038       else
5039         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5040     }
5041
5042     Ops.push_back(SetCC->getOperand(2));
5043     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5044   }
5045 }
5046
5047 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5048   SDValue N0 = N->getOperand(0);
5049   EVT VT = N->getValueType(0);
5050
5051   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5052                                               LegalOperations))
5053     return SDValue(Res, 0);
5054
5055   // fold (sext (sext x)) -> (sext x)
5056   // fold (sext (aext x)) -> (sext x)
5057   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5058     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5059                        N0.getOperand(0));
5060
5061   if (N0.getOpcode() == ISD::TRUNCATE) {
5062     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5063     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5064     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5065     if (NarrowLoad.getNode()) {
5066       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5067       if (NarrowLoad.getNode() != N0.getNode()) {
5068         CombineTo(N0.getNode(), NarrowLoad);
5069         // CombineTo deleted the truncate, if needed, but not what's under it.
5070         AddToWorklist(oye);
5071       }
5072       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5073     }
5074
5075     // See if the value being truncated is already sign extended.  If so, just
5076     // eliminate the trunc/sext pair.
5077     SDValue Op = N0.getOperand(0);
5078     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5079     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5080     unsigned DestBits = VT.getScalarType().getSizeInBits();
5081     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5082
5083     if (OpBits == DestBits) {
5084       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5085       // bits, it is already ready.
5086       if (NumSignBits > DestBits-MidBits)
5087         return Op;
5088     } else if (OpBits < DestBits) {
5089       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5090       // bits, just sext from i32.
5091       if (NumSignBits > OpBits-MidBits)
5092         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5093     } else {
5094       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5095       // bits, just truncate to i32.
5096       if (NumSignBits > OpBits-MidBits)
5097         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5098     }
5099
5100     // fold (sext (truncate x)) -> (sextinreg x).
5101     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5102                                                  N0.getValueType())) {
5103       if (OpBits < DestBits)
5104         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5105       else if (OpBits > DestBits)
5106         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5107       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5108                          DAG.getValueType(N0.getValueType()));
5109     }
5110   }
5111
5112   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5113   // None of the supported targets knows how to perform load and sign extend
5114   // on vectors in one instruction.  We only perform this transformation on
5115   // scalars.
5116   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5117       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5118       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5119        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5120     bool DoXform = true;
5121     SmallVector<SDNode*, 4> SetCCs;
5122     if (!N0.hasOneUse())
5123       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5124     if (DoXform) {
5125       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5126       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5127                                        LN0->getChain(),
5128                                        LN0->getBasePtr(), N0.getValueType(),
5129                                        LN0->getMemOperand());
5130       CombineTo(N, ExtLoad);
5131       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5132                                   N0.getValueType(), ExtLoad);
5133       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5134       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5135                       ISD::SIGN_EXTEND);
5136       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5137     }
5138   }
5139
5140   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5141   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5142   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5143       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5144     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5145     EVT MemVT = LN0->getMemoryVT();
5146     if ((!LegalOperations && !LN0->isVolatile()) ||
5147         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5148       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5149                                        LN0->getChain(),
5150                                        LN0->getBasePtr(), MemVT,
5151                                        LN0->getMemOperand());
5152       CombineTo(N, ExtLoad);
5153       CombineTo(N0.getNode(),
5154                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5155                             N0.getValueType(), ExtLoad),
5156                 ExtLoad.getValue(1));
5157       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5158     }
5159   }
5160
5161   // fold (sext (and/or/xor (load x), cst)) ->
5162   //      (and/or/xor (sextload x), (sext cst))
5163   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5164        N0.getOpcode() == ISD::XOR) &&
5165       isa<LoadSDNode>(N0.getOperand(0)) &&
5166       N0.getOperand(1).getOpcode() == ISD::Constant &&
5167       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5168       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5169     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5170     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5171       bool DoXform = true;
5172       SmallVector<SDNode*, 4> SetCCs;
5173       if (!N0.hasOneUse())
5174         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5175                                           SetCCs, TLI);
5176       if (DoXform) {
5177         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5178                                          LN0->getChain(), LN0->getBasePtr(),
5179                                          LN0->getMemoryVT(),
5180                                          LN0->getMemOperand());
5181         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5182         Mask = Mask.sext(VT.getSizeInBits());
5183         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5184                                   ExtLoad, DAG.getConstant(Mask, VT));
5185         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5186                                     SDLoc(N0.getOperand(0)),
5187                                     N0.getOperand(0).getValueType(), ExtLoad);
5188         CombineTo(N, And);
5189         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5190         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5191                         ISD::SIGN_EXTEND);
5192         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5193       }
5194     }
5195   }
5196
5197   if (N0.getOpcode() == ISD::SETCC) {
5198     EVT N0VT = N0.getOperand(0).getValueType();
5199     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5200     // Only do this before legalize for now.
5201     if (VT.isVector() && !LegalOperations &&
5202         TLI.getBooleanContents(N0VT) ==
5203             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5204       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5205       // of the same size as the compared operands. Only optimize sext(setcc())
5206       // if this is the case.
5207       EVT SVT = getSetCCResultType(N0VT);
5208
5209       // We know that the # elements of the results is the same as the
5210       // # elements of the compare (and the # elements of the compare result
5211       // for that matter).  Check to see that they are the same size.  If so,
5212       // we know that the element size of the sext'd result matches the
5213       // element size of the compare operands.
5214       if (VT.getSizeInBits() == SVT.getSizeInBits())
5215         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5216                              N0.getOperand(1),
5217                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5218
5219       // If the desired elements are smaller or larger than the source
5220       // elements we can use a matching integer vector type and then
5221       // truncate/sign extend
5222       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5223       if (SVT == MatchingVectorType) {
5224         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5225                                N0.getOperand(0), N0.getOperand(1),
5226                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5227         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5228       }
5229     }
5230
5231     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5232     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5233     SDValue NegOne =
5234       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5235     SDValue SCC =
5236       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5237                        NegOne, DAG.getConstant(0, VT),
5238                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5239     if (SCC.getNode()) return SCC;
5240
5241     if (!VT.isVector()) {
5242       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5243       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5244         SDLoc DL(N);
5245         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5246         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5247                                      N0.getOperand(0), N0.getOperand(1), CC);
5248         return DAG.getSelect(DL, VT, SetCC,
5249                              NegOne, DAG.getConstant(0, VT));
5250       }
5251     }
5252   }
5253
5254   // fold (sext x) -> (zext x) if the sign bit is known zero.
5255   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5256       DAG.SignBitIsZero(N0))
5257     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5258
5259   return SDValue();
5260 }
5261
5262 // isTruncateOf - If N is a truncate of some other value, return true, record
5263 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5264 // This function computes KnownZero to avoid a duplicated call to
5265 // computeKnownBits in the caller.
5266 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5267                          APInt &KnownZero) {
5268   APInt KnownOne;
5269   if (N->getOpcode() == ISD::TRUNCATE) {
5270     Op = N->getOperand(0);
5271     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5272     return true;
5273   }
5274
5275   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5276       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5277     return false;
5278
5279   SDValue Op0 = N->getOperand(0);
5280   SDValue Op1 = N->getOperand(1);
5281   assert(Op0.getValueType() == Op1.getValueType());
5282
5283   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5284   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5285   if (COp0 && COp0->isNullValue())
5286     Op = Op1;
5287   else if (COp1 && COp1->isNullValue())
5288     Op = Op0;
5289   else
5290     return false;
5291
5292   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5293
5294   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5295     return false;
5296
5297   return true;
5298 }
5299
5300 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5301   SDValue N0 = N->getOperand(0);
5302   EVT VT = N->getValueType(0);
5303
5304   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5305                                               LegalOperations))
5306     return SDValue(Res, 0);
5307
5308   // fold (zext (zext x)) -> (zext x)
5309   // fold (zext (aext x)) -> (zext x)
5310   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5311     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5312                        N0.getOperand(0));
5313
5314   // fold (zext (truncate x)) -> (zext x) or
5315   //      (zext (truncate x)) -> (truncate x)
5316   // This is valid when the truncated bits of x are already zero.
5317   // FIXME: We should extend this to work for vectors too.
5318   SDValue Op;
5319   APInt KnownZero;
5320   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5321     APInt TruncatedBits =
5322       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5323       APInt(Op.getValueSizeInBits(), 0) :
5324       APInt::getBitsSet(Op.getValueSizeInBits(),
5325                         N0.getValueSizeInBits(),
5326                         std::min(Op.getValueSizeInBits(),
5327                                  VT.getSizeInBits()));
5328     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5329       if (VT.bitsGT(Op.getValueType()))
5330         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5331       if (VT.bitsLT(Op.getValueType()))
5332         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5333
5334       return Op;
5335     }
5336   }
5337
5338   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5339   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5340   if (N0.getOpcode() == ISD::TRUNCATE) {
5341     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5342     if (NarrowLoad.getNode()) {
5343       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5344       if (NarrowLoad.getNode() != N0.getNode()) {
5345         CombineTo(N0.getNode(), NarrowLoad);
5346         // CombineTo deleted the truncate, if needed, but not what's under it.
5347         AddToWorklist(oye);
5348       }
5349       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5350     }
5351   }
5352
5353   // fold (zext (truncate x)) -> (and x, mask)
5354   if (N0.getOpcode() == ISD::TRUNCATE &&
5355       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5356
5357     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5358     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5359     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5360     if (NarrowLoad.getNode()) {
5361       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5362       if (NarrowLoad.getNode() != N0.getNode()) {
5363         CombineTo(N0.getNode(), NarrowLoad);
5364         // CombineTo deleted the truncate, if needed, but not what's under it.
5365         AddToWorklist(oye);
5366       }
5367       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5368     }
5369
5370     SDValue Op = N0.getOperand(0);
5371     if (Op.getValueType().bitsLT(VT)) {
5372       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5373       AddToWorklist(Op.getNode());
5374     } else if (Op.getValueType().bitsGT(VT)) {
5375       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5376       AddToWorklist(Op.getNode());
5377     }
5378     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5379                                   N0.getValueType().getScalarType());
5380   }
5381
5382   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5383   // if either of the casts is not free.
5384   if (N0.getOpcode() == ISD::AND &&
5385       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5386       N0.getOperand(1).getOpcode() == ISD::Constant &&
5387       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5388                            N0.getValueType()) ||
5389        !TLI.isZExtFree(N0.getValueType(), VT))) {
5390     SDValue X = N0.getOperand(0).getOperand(0);
5391     if (X.getValueType().bitsLT(VT)) {
5392       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5393     } else if (X.getValueType().bitsGT(VT)) {
5394       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5395     }
5396     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5397     Mask = Mask.zext(VT.getSizeInBits());
5398     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399                        X, DAG.getConstant(Mask, VT));
5400   }
5401
5402   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5403   // None of the supported targets knows how to perform load and vector_zext
5404   // on vectors in one instruction.  We only perform this transformation on
5405   // scalars.
5406   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5407       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5408       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5409        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5410     bool DoXform = true;
5411     SmallVector<SDNode*, 4> SetCCs;
5412     if (!N0.hasOneUse())
5413       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5414     if (DoXform) {
5415       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5416       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5417                                        LN0->getChain(),
5418                                        LN0->getBasePtr(), N0.getValueType(),
5419                                        LN0->getMemOperand());
5420       CombineTo(N, ExtLoad);
5421       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5422                                   N0.getValueType(), ExtLoad);
5423       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5424
5425       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5426                       ISD::ZERO_EXTEND);
5427       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5428     }
5429   }
5430
5431   // fold (zext (and/or/xor (load x), cst)) ->
5432   //      (and/or/xor (zextload x), (zext cst))
5433   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5434        N0.getOpcode() == ISD::XOR) &&
5435       isa<LoadSDNode>(N0.getOperand(0)) &&
5436       N0.getOperand(1).getOpcode() == ISD::Constant &&
5437       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5438       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5439     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5440     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5441       bool DoXform = true;
5442       SmallVector<SDNode*, 4> SetCCs;
5443       if (!N0.hasOneUse())
5444         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5445                                           SetCCs, TLI);
5446       if (DoXform) {
5447         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5448                                          LN0->getChain(), LN0->getBasePtr(),
5449                                          LN0->getMemoryVT(),
5450                                          LN0->getMemOperand());
5451         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5452         Mask = Mask.zext(VT.getSizeInBits());
5453         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5454                                   ExtLoad, DAG.getConstant(Mask, VT));
5455         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5456                                     SDLoc(N0.getOperand(0)),
5457                                     N0.getOperand(0).getValueType(), ExtLoad);
5458         CombineTo(N, And);
5459         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5460         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5461                         ISD::ZERO_EXTEND);
5462         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5463       }
5464     }
5465   }
5466
5467   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5468   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5469   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5470       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5471     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472     EVT MemVT = LN0->getMemoryVT();
5473     if ((!LegalOperations && !LN0->isVolatile()) ||
5474         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5475       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5476                                        LN0->getChain(),
5477                                        LN0->getBasePtr(), MemVT,
5478                                        LN0->getMemOperand());
5479       CombineTo(N, ExtLoad);
5480       CombineTo(N0.getNode(),
5481                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5482                             ExtLoad),
5483                 ExtLoad.getValue(1));
5484       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5485     }
5486   }
5487
5488   if (N0.getOpcode() == ISD::SETCC) {
5489     if (!LegalOperations && VT.isVector() &&
5490         N0.getValueType().getVectorElementType() == MVT::i1) {
5491       EVT N0VT = N0.getOperand(0).getValueType();
5492       if (getSetCCResultType(N0VT) == N0.getValueType())
5493         return SDValue();
5494
5495       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5496       // Only do this before legalize for now.
5497       EVT EltVT = VT.getVectorElementType();
5498       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5499                                     DAG.getConstant(1, EltVT));
5500       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5501         // We know that the # elements of the results is the same as the
5502         // # elements of the compare (and the # elements of the compare result
5503         // for that matter).  Check to see that they are the same size.  If so,
5504         // we know that the element size of the sext'd result matches the
5505         // element size of the compare operands.
5506         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5507                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5508                                          N0.getOperand(1),
5509                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5510                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5511                                        OneOps));
5512
5513       // If the desired elements are smaller or larger than the source
5514       // elements we can use a matching integer vector type and then
5515       // truncate/sign extend
5516       EVT MatchingElementType =
5517         EVT::getIntegerVT(*DAG.getContext(),
5518                           N0VT.getScalarType().getSizeInBits());
5519       EVT MatchingVectorType =
5520         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5521                          N0VT.getVectorNumElements());
5522       SDValue VsetCC =
5523         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5524                       N0.getOperand(1),
5525                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5526       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5527                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5528                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5529     }
5530
5531     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5532     SDValue SCC =
5533       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5534                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5535                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5536     if (SCC.getNode()) return SCC;
5537   }
5538
5539   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5540   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5541       isa<ConstantSDNode>(N0.getOperand(1)) &&
5542       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5543       N0.hasOneUse()) {
5544     SDValue ShAmt = N0.getOperand(1);
5545     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5546     if (N0.getOpcode() == ISD::SHL) {
5547       SDValue InnerZExt = N0.getOperand(0);
5548       // If the original shl may be shifting out bits, do not perform this
5549       // transformation.
5550       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5551         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5552       if (ShAmtVal > KnownZeroBits)
5553         return SDValue();
5554     }
5555
5556     SDLoc DL(N);
5557
5558     // Ensure that the shift amount is wide enough for the shifted value.
5559     if (VT.getSizeInBits() >= 256)
5560       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5561
5562     return DAG.getNode(N0.getOpcode(), DL, VT,
5563                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5564                        ShAmt);
5565   }
5566
5567   return SDValue();
5568 }
5569
5570 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5571   SDValue N0 = N->getOperand(0);
5572   EVT VT = N->getValueType(0);
5573
5574   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5575                                               LegalOperations))
5576     return SDValue(Res, 0);
5577
5578   // fold (aext (aext x)) -> (aext x)
5579   // fold (aext (zext x)) -> (zext x)
5580   // fold (aext (sext x)) -> (sext x)
5581   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5582       N0.getOpcode() == ISD::ZERO_EXTEND ||
5583       N0.getOpcode() == ISD::SIGN_EXTEND)
5584     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5585
5586   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5587   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5588   if (N0.getOpcode() == ISD::TRUNCATE) {
5589     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5590     if (NarrowLoad.getNode()) {
5591       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5592       if (NarrowLoad.getNode() != N0.getNode()) {
5593         CombineTo(N0.getNode(), NarrowLoad);
5594         // CombineTo deleted the truncate, if needed, but not what's under it.
5595         AddToWorklist(oye);
5596       }
5597       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5598     }
5599   }
5600
5601   // fold (aext (truncate x))
5602   if (N0.getOpcode() == ISD::TRUNCATE) {
5603     SDValue TruncOp = N0.getOperand(0);
5604     if (TruncOp.getValueType() == VT)
5605       return TruncOp; // x iff x size == zext size.
5606     if (TruncOp.getValueType().bitsGT(VT))
5607       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5608     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5609   }
5610
5611   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5612   // if the trunc is not free.
5613   if (N0.getOpcode() == ISD::AND &&
5614       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5615       N0.getOperand(1).getOpcode() == ISD::Constant &&
5616       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5617                           N0.getValueType())) {
5618     SDValue X = N0.getOperand(0).getOperand(0);
5619     if (X.getValueType().bitsLT(VT)) {
5620       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5621     } else if (X.getValueType().bitsGT(VT)) {
5622       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5623     }
5624     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5625     Mask = Mask.zext(VT.getSizeInBits());
5626     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5627                        X, DAG.getConstant(Mask, VT));
5628   }
5629
5630   // fold (aext (load x)) -> (aext (truncate (extload x)))
5631   // None of the supported targets knows how to perform load and any_ext
5632   // on vectors in one instruction.  We only perform this transformation on
5633   // scalars.
5634   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5635       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5636       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5637     bool DoXform = true;
5638     SmallVector<SDNode*, 4> SetCCs;
5639     if (!N0.hasOneUse())
5640       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5641     if (DoXform) {
5642       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5643       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5644                                        LN0->getChain(),
5645                                        LN0->getBasePtr(), N0.getValueType(),
5646                                        LN0->getMemOperand());
5647       CombineTo(N, ExtLoad);
5648       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5649                                   N0.getValueType(), ExtLoad);
5650       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5651       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5652                       ISD::ANY_EXTEND);
5653       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5654     }
5655   }
5656
5657   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5658   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5659   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5660   if (N0.getOpcode() == ISD::LOAD &&
5661       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5662       N0.hasOneUse()) {
5663     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5664     ISD::LoadExtType ExtType = LN0->getExtensionType();
5665     EVT MemVT = LN0->getMemoryVT();
5666     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5667       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5668                                        VT, LN0->getChain(), LN0->getBasePtr(),
5669                                        MemVT, LN0->getMemOperand());
5670       CombineTo(N, ExtLoad);
5671       CombineTo(N0.getNode(),
5672                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5673                             N0.getValueType(), ExtLoad),
5674                 ExtLoad.getValue(1));
5675       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5676     }
5677   }
5678
5679   if (N0.getOpcode() == ISD::SETCC) {
5680     // For vectors:
5681     // aext(setcc) -> vsetcc
5682     // aext(setcc) -> truncate(vsetcc)
5683     // aext(setcc) -> aext(vsetcc)
5684     // Only do this before legalize for now.
5685     if (VT.isVector() && !LegalOperations) {
5686       EVT N0VT = N0.getOperand(0).getValueType();
5687         // We know that the # elements of the results is the same as the
5688         // # elements of the compare (and the # elements of the compare result
5689         // for that matter).  Check to see that they are the same size.  If so,
5690         // we know that the element size of the sext'd result matches the
5691         // element size of the compare operands.
5692       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5693         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5694                              N0.getOperand(1),
5695                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5696       // If the desired elements are smaller or larger than the source
5697       // elements we can use a matching integer vector type and then
5698       // truncate/any extend
5699       else {
5700         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5701         SDValue VsetCC =
5702           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5703                         N0.getOperand(1),
5704                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5705         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5706       }
5707     }
5708
5709     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5710     SDValue SCC =
5711       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5712                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5713                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5714     if (SCC.getNode())
5715       return SCC;
5716   }
5717
5718   return SDValue();
5719 }
5720
5721 /// See if the specified operand can be simplified with the knowledge that only
5722 /// the bits specified by Mask are used.  If so, return the simpler operand,
5723 /// otherwise return a null SDValue.
5724 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5725   switch (V.getOpcode()) {
5726   default: break;
5727   case ISD::Constant: {
5728     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5729     assert(CV && "Const value should be ConstSDNode.");
5730     const APInt &CVal = CV->getAPIntValue();
5731     APInt NewVal = CVal & Mask;
5732     if (NewVal != CVal)
5733       return DAG.getConstant(NewVal, V.getValueType());
5734     break;
5735   }
5736   case ISD::OR:
5737   case ISD::XOR:
5738     // If the LHS or RHS don't contribute bits to the or, drop them.
5739     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5740       return V.getOperand(1);
5741     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5742       return V.getOperand(0);
5743     break;
5744   case ISD::SRL:
5745     // Only look at single-use SRLs.
5746     if (!V.getNode()->hasOneUse())
5747       break;
5748     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5749       // See if we can recursively simplify the LHS.
5750       unsigned Amt = RHSC->getZExtValue();
5751
5752       // Watch out for shift count overflow though.
5753       if (Amt >= Mask.getBitWidth()) break;
5754       APInt NewMask = Mask << Amt;
5755       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5756       if (SimplifyLHS.getNode())
5757         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5758                            SimplifyLHS, V.getOperand(1));
5759     }
5760   }
5761   return SDValue();
5762 }
5763
5764 /// If the result of a wider load is shifted to right of N  bits and then
5765 /// truncated to a narrower type and where N is a multiple of number of bits of
5766 /// the narrower type, transform it to a narrower load from address + N / num of
5767 /// bits of new type. If the result is to be extended, also fold the extension
5768 /// to form a extending load.
5769 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5770   unsigned Opc = N->getOpcode();
5771
5772   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5773   SDValue N0 = N->getOperand(0);
5774   EVT VT = N->getValueType(0);
5775   EVT ExtVT = VT;
5776
5777   // This transformation isn't valid for vector loads.
5778   if (VT.isVector())
5779     return SDValue();
5780
5781   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5782   // extended to VT.
5783   if (Opc == ISD::SIGN_EXTEND_INREG) {
5784     ExtType = ISD::SEXTLOAD;
5785     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5786   } else if (Opc == ISD::SRL) {
5787     // Another special-case: SRL is basically zero-extending a narrower value.
5788     ExtType = ISD::ZEXTLOAD;
5789     N0 = SDValue(N, 0);
5790     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5791     if (!N01) return SDValue();
5792     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5793                               VT.getSizeInBits() - N01->getZExtValue());
5794   }
5795   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5796     return SDValue();
5797
5798   unsigned EVTBits = ExtVT.getSizeInBits();
5799
5800   // Do not generate loads of non-round integer types since these can
5801   // be expensive (and would be wrong if the type is not byte sized).
5802   if (!ExtVT.isRound())
5803     return SDValue();
5804
5805   unsigned ShAmt = 0;
5806   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5807     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808       ShAmt = N01->getZExtValue();
5809       // Is the shift amount a multiple of size of VT?
5810       if ((ShAmt & (EVTBits-1)) == 0) {
5811         N0 = N0.getOperand(0);
5812         // Is the load width a multiple of size of VT?
5813         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5814           return SDValue();
5815       }
5816
5817       // At this point, we must have a load or else we can't do the transform.
5818       if (!isa<LoadSDNode>(N0)) return SDValue();
5819
5820       // Because a SRL must be assumed to *need* to zero-extend the high bits
5821       // (as opposed to anyext the high bits), we can't combine the zextload
5822       // lowering of SRL and an sextload.
5823       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5824         return SDValue();
5825
5826       // If the shift amount is larger than the input type then we're not
5827       // accessing any of the loaded bytes.  If the load was a zextload/extload
5828       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5829       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5830         return SDValue();
5831     }
5832   }
5833
5834   // If the load is shifted left (and the result isn't shifted back right),
5835   // we can fold the truncate through the shift.
5836   unsigned ShLeftAmt = 0;
5837   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5838       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5839     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5840       ShLeftAmt = N01->getZExtValue();
5841       N0 = N0.getOperand(0);
5842     }
5843   }
5844
5845   // If we haven't found a load, we can't narrow it.  Don't transform one with
5846   // multiple uses, this would require adding a new load.
5847   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5848     return SDValue();
5849
5850   // Don't change the width of a volatile load.
5851   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5852   if (LN0->isVolatile())
5853     return SDValue();
5854
5855   // Verify that we are actually reducing a load width here.
5856   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5857     return SDValue();
5858
5859   // For the transform to be legal, the load must produce only two values
5860   // (the value loaded and the chain).  Don't transform a pre-increment
5861   // load, for example, which produces an extra value.  Otherwise the
5862   // transformation is not equivalent, and the downstream logic to replace
5863   // uses gets things wrong.
5864   if (LN0->getNumValues() > 2)
5865     return SDValue();
5866
5867   // If the load that we're shrinking is an extload and we're not just
5868   // discarding the extension we can't simply shrink the load. Bail.
5869   // TODO: It would be possible to merge the extensions in some cases.
5870   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5871       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5872     return SDValue();
5873
5874   EVT PtrType = N0.getOperand(1).getValueType();
5875
5876   if (PtrType == MVT::Untyped || PtrType.isExtended())
5877     // It's not possible to generate a constant of extended or untyped type.
5878     return SDValue();
5879
5880   // For big endian targets, we need to adjust the offset to the pointer to
5881   // load the correct bytes.
5882   if (TLI.isBigEndian()) {
5883     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5884     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5885     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5886   }
5887
5888   uint64_t PtrOff = ShAmt / 8;
5889   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5890   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5891                                PtrType, LN0->getBasePtr(),
5892                                DAG.getConstant(PtrOff, PtrType));
5893   AddToWorklist(NewPtr.getNode());
5894
5895   SDValue Load;
5896   if (ExtType == ISD::NON_EXTLOAD)
5897     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5898                         LN0->getPointerInfo().getWithOffset(PtrOff),
5899                         LN0->isVolatile(), LN0->isNonTemporal(),
5900                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5901   else
5902     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5903                           LN0->getPointerInfo().getWithOffset(PtrOff),
5904                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5905                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5906
5907   // Replace the old load's chain with the new load's chain.
5908   WorklistRemover DeadNodes(*this);
5909   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5910
5911   // Shift the result left, if we've swallowed a left shift.
5912   SDValue Result = Load;
5913   if (ShLeftAmt != 0) {
5914     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5915     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5916       ShImmTy = VT;
5917     // If the shift amount is as large as the result size (but, presumably,
5918     // no larger than the source) then the useful bits of the result are
5919     // zero; we can't simply return the shortened shift, because the result
5920     // of that operation is undefined.
5921     if (ShLeftAmt >= VT.getSizeInBits())
5922       Result = DAG.getConstant(0, VT);
5923     else
5924       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5925                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5926   }
5927
5928   // Return the new loaded value.
5929   return Result;
5930 }
5931
5932 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5933   SDValue N0 = N->getOperand(0);
5934   SDValue N1 = N->getOperand(1);
5935   EVT VT = N->getValueType(0);
5936   EVT EVT = cast<VTSDNode>(N1)->getVT();
5937   unsigned VTBits = VT.getScalarType().getSizeInBits();
5938   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5939
5940   // fold (sext_in_reg c1) -> c1
5941   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5942     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5943
5944   // If the input is already sign extended, just drop the extension.
5945   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5946     return N0;
5947
5948   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5949   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5950       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5951     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5952                        N0.getOperand(0), N1);
5953
5954   // fold (sext_in_reg (sext x)) -> (sext x)
5955   // fold (sext_in_reg (aext x)) -> (sext x)
5956   // if x is small enough.
5957   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5958     SDValue N00 = N0.getOperand(0);
5959     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5960         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5961       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5962   }
5963
5964   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5965   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5966     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5967
5968   // fold operands of sext_in_reg based on knowledge that the top bits are not
5969   // demanded.
5970   if (SimplifyDemandedBits(SDValue(N, 0)))
5971     return SDValue(N, 0);
5972
5973   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5974   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5975   SDValue NarrowLoad = ReduceLoadWidth(N);
5976   if (NarrowLoad.getNode())
5977     return NarrowLoad;
5978
5979   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5980   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5981   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5982   if (N0.getOpcode() == ISD::SRL) {
5983     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5984       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5985         // We can turn this into an SRA iff the input to the SRL is already sign
5986         // extended enough.
5987         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5988         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5989           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5990                              N0.getOperand(0), N0.getOperand(1));
5991       }
5992   }
5993
5994   // fold (sext_inreg (extload x)) -> (sextload x)
5995   if (ISD::isEXTLoad(N0.getNode()) &&
5996       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5997       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5998       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5999        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6000     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6001     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6002                                      LN0->getChain(),
6003                                      LN0->getBasePtr(), EVT,
6004                                      LN0->getMemOperand());
6005     CombineTo(N, ExtLoad);
6006     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6007     AddToWorklist(ExtLoad.getNode());
6008     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6009   }
6010   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6011   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6012       N0.hasOneUse() &&
6013       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6014       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6015        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6016     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6018                                      LN0->getChain(),
6019                                      LN0->getBasePtr(), EVT,
6020                                      LN0->getMemOperand());
6021     CombineTo(N, ExtLoad);
6022     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6023     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6024   }
6025
6026   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6027   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6028     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6029                                        N0.getOperand(1), false);
6030     if (BSwap.getNode())
6031       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6032                          BSwap, N1);
6033   }
6034
6035   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6036   // into a build_vector.
6037   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6038     SmallVector<SDValue, 8> Elts;
6039     unsigned NumElts = N0->getNumOperands();
6040     unsigned ShAmt = VTBits - EVTBits;
6041
6042     for (unsigned i = 0; i != NumElts; ++i) {
6043       SDValue Op = N0->getOperand(i);
6044       if (Op->getOpcode() == ISD::UNDEF) {
6045         Elts.push_back(Op);
6046         continue;
6047       }
6048
6049       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6050       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6051       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6052                                      Op.getValueType()));
6053     }
6054
6055     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6056   }
6057
6058   return SDValue();
6059 }
6060
6061 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6062   SDValue N0 = N->getOperand(0);
6063   EVT VT = N->getValueType(0);
6064   bool isLE = TLI.isLittleEndian();
6065
6066   // noop truncate
6067   if (N0.getValueType() == N->getValueType(0))
6068     return N0;
6069   // fold (truncate c1) -> c1
6070   if (isa<ConstantSDNode>(N0))
6071     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6072   // fold (truncate (truncate x)) -> (truncate x)
6073   if (N0.getOpcode() == ISD::TRUNCATE)
6074     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6075   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6076   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6077       N0.getOpcode() == ISD::SIGN_EXTEND ||
6078       N0.getOpcode() == ISD::ANY_EXTEND) {
6079     if (N0.getOperand(0).getValueType().bitsLT(VT))
6080       // if the source is smaller than the dest, we still need an extend
6081       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6082                          N0.getOperand(0));
6083     if (N0.getOperand(0).getValueType().bitsGT(VT))
6084       // if the source is larger than the dest, than we just need the truncate
6085       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6086     // if the source and dest are the same type, we can drop both the extend
6087     // and the truncate.
6088     return N0.getOperand(0);
6089   }
6090
6091   // Fold extract-and-trunc into a narrow extract. For example:
6092   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6093   //   i32 y = TRUNCATE(i64 x)
6094   //        -- becomes --
6095   //   v16i8 b = BITCAST (v2i64 val)
6096   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6097   //
6098   // Note: We only run this optimization after type legalization (which often
6099   // creates this pattern) and before operation legalization after which
6100   // we need to be more careful about the vector instructions that we generate.
6101   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6102       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6103
6104     EVT VecTy = N0.getOperand(0).getValueType();
6105     EVT ExTy = N0.getValueType();
6106     EVT TrTy = N->getValueType(0);
6107
6108     unsigned NumElem = VecTy.getVectorNumElements();
6109     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6110
6111     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6112     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6113
6114     SDValue EltNo = N0->getOperand(1);
6115     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6116       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6117       EVT IndexTy = TLI.getVectorIdxTy();
6118       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6119
6120       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6121                               NVT, N0.getOperand(0));
6122
6123       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6124                          SDLoc(N), TrTy, V,
6125                          DAG.getConstant(Index, IndexTy));
6126     }
6127   }
6128
6129   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6130   if (N0.getOpcode() == ISD::SELECT) {
6131     EVT SrcVT = N0.getValueType();
6132     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6133         TLI.isTruncateFree(SrcVT, VT)) {
6134       SDLoc SL(N0);
6135       SDValue Cond = N0.getOperand(0);
6136       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6137       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6138       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6139     }
6140   }
6141
6142   // Fold a series of buildvector, bitcast, and truncate if possible.
6143   // For example fold
6144   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6145   //   (2xi32 (buildvector x, y)).
6146   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6147       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6148       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6149       N0.getOperand(0).hasOneUse()) {
6150
6151     SDValue BuildVect = N0.getOperand(0);
6152     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6153     EVT TruncVecEltTy = VT.getVectorElementType();
6154
6155     // Check that the element types match.
6156     if (BuildVectEltTy == TruncVecEltTy) {
6157       // Now we only need to compute the offset of the truncated elements.
6158       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6159       unsigned TruncVecNumElts = VT.getVectorNumElements();
6160       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6161
6162       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6163              "Invalid number of elements");
6164
6165       SmallVector<SDValue, 8> Opnds;
6166       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6167         Opnds.push_back(BuildVect.getOperand(i));
6168
6169       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6170     }
6171   }
6172
6173   // See if we can simplify the input to this truncate through knowledge that
6174   // only the low bits are being used.
6175   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6176   // Currently we only perform this optimization on scalars because vectors
6177   // may have different active low bits.
6178   if (!VT.isVector()) {
6179     SDValue Shorter =
6180       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6181                                                VT.getSizeInBits()));
6182     if (Shorter.getNode())
6183       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6184   }
6185   // fold (truncate (load x)) -> (smaller load x)
6186   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6187   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6188     SDValue Reduced = ReduceLoadWidth(N);
6189     if (Reduced.getNode())
6190       return Reduced;
6191     // Handle the case where the load remains an extending load even
6192     // after truncation.
6193     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6194       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6195       if (!LN0->isVolatile() &&
6196           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6197         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6198                                          VT, LN0->getChain(), LN0->getBasePtr(),
6199                                          LN0->getMemoryVT(),
6200                                          LN0->getMemOperand());
6201         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6202         return NewLoad;
6203       }
6204     }
6205   }
6206   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6207   // where ... are all 'undef'.
6208   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6209     SmallVector<EVT, 8> VTs;
6210     SDValue V;
6211     unsigned Idx = 0;
6212     unsigned NumDefs = 0;
6213
6214     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6215       SDValue X = N0.getOperand(i);
6216       if (X.getOpcode() != ISD::UNDEF) {
6217         V = X;
6218         Idx = i;
6219         NumDefs++;
6220       }
6221       // Stop if more than one members are non-undef.
6222       if (NumDefs > 1)
6223         break;
6224       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6225                                      VT.getVectorElementType(),
6226                                      X.getValueType().getVectorNumElements()));
6227     }
6228
6229     if (NumDefs == 0)
6230       return DAG.getUNDEF(VT);
6231
6232     if (NumDefs == 1) {
6233       assert(V.getNode() && "The single defined operand is empty!");
6234       SmallVector<SDValue, 8> Opnds;
6235       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6236         if (i != Idx) {
6237           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6238           continue;
6239         }
6240         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6241         AddToWorklist(NV.getNode());
6242         Opnds.push_back(NV);
6243       }
6244       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6245     }
6246   }
6247
6248   // Simplify the operands using demanded-bits information.
6249   if (!VT.isVector() &&
6250       SimplifyDemandedBits(SDValue(N, 0)))
6251     return SDValue(N, 0);
6252
6253   return SDValue();
6254 }
6255
6256 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6257   SDValue Elt = N->getOperand(i);
6258   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6259     return Elt.getNode();
6260   return Elt.getOperand(Elt.getResNo()).getNode();
6261 }
6262
6263 /// build_pair (load, load) -> load
6264 /// if load locations are consecutive.
6265 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6266   assert(N->getOpcode() == ISD::BUILD_PAIR);
6267
6268   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6269   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6270   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6271       LD1->getAddressSpace() != LD2->getAddressSpace())
6272     return SDValue();
6273   EVT LD1VT = LD1->getValueType(0);
6274
6275   if (ISD::isNON_EXTLoad(LD2) &&
6276       LD2->hasOneUse() &&
6277       // If both are volatile this would reduce the number of volatile loads.
6278       // If one is volatile it might be ok, but play conservative and bail out.
6279       !LD1->isVolatile() &&
6280       !LD2->isVolatile() &&
6281       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6282     unsigned Align = LD1->getAlignment();
6283     unsigned NewAlign = TLI.getDataLayout()->
6284       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6285
6286     if (NewAlign <= Align &&
6287         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6288       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6289                          LD1->getBasePtr(), LD1->getPointerInfo(),
6290                          false, false, false, Align);
6291   }
6292
6293   return SDValue();
6294 }
6295
6296 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6297   SDValue N0 = N->getOperand(0);
6298   EVT VT = N->getValueType(0);
6299
6300   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6301   // Only do this before legalize, since afterward the target may be depending
6302   // on the bitconvert.
6303   // First check to see if this is all constant.
6304   if (!LegalTypes &&
6305       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6306       VT.isVector()) {
6307     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6308
6309     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6310     assert(!DestEltVT.isVector() &&
6311            "Element type of vector ValueType must not be vector!");
6312     if (isSimple)
6313       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6314   }
6315
6316   // If the input is a constant, let getNode fold it.
6317   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6318     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6319     if (Res.getNode() != N) {
6320       if (!LegalOperations ||
6321           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6322         return Res;
6323
6324       // Folding it resulted in an illegal node, and it's too late to
6325       // do that. Clean up the old node and forego the transformation.
6326       // Ideally this won't happen very often, because instcombine
6327       // and the earlier dagcombine runs (where illegal nodes are
6328       // permitted) should have folded most of them already.
6329       deleteAndRecombine(Res.getNode());
6330     }
6331   }
6332
6333   // (conv (conv x, t1), t2) -> (conv x, t2)
6334   if (N0.getOpcode() == ISD::BITCAST)
6335     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6336                        N0.getOperand(0));
6337
6338   // fold (conv (load x)) -> (load (conv*)x)
6339   // If the resultant load doesn't need a higher alignment than the original!
6340   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6341       // Do not change the width of a volatile load.
6342       !cast<LoadSDNode>(N0)->isVolatile() &&
6343       // Do not remove the cast if the types differ in endian layout.
6344       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6345       TLI.hasBigEndianPartOrdering(VT) &&
6346       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6347       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6348     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6349     unsigned Align = TLI.getDataLayout()->
6350       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6351     unsigned OrigAlign = LN0->getAlignment();
6352
6353     if (Align <= OrigAlign) {
6354       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6355                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6356                                  LN0->isVolatile(), LN0->isNonTemporal(),
6357                                  LN0->isInvariant(), OrigAlign,
6358                                  LN0->getAAInfo());
6359       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6360       return Load;
6361     }
6362   }
6363
6364   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6365   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6366   // This often reduces constant pool loads.
6367   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6368        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6369       N0.getNode()->hasOneUse() && VT.isInteger() &&
6370       !VT.isVector() && !N0.getValueType().isVector()) {
6371     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6372                                   N0.getOperand(0));
6373     AddToWorklist(NewConv.getNode());
6374
6375     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6376     if (N0.getOpcode() == ISD::FNEG)
6377       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6378                          NewConv, DAG.getConstant(SignBit, VT));
6379     assert(N0.getOpcode() == ISD::FABS);
6380     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6381                        NewConv, DAG.getConstant(~SignBit, VT));
6382   }
6383
6384   // fold (bitconvert (fcopysign cst, x)) ->
6385   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6386   // Note that we don't handle (copysign x, cst) because this can always be
6387   // folded to an fneg or fabs.
6388   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6389       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6390       VT.isInteger() && !VT.isVector()) {
6391     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6392     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6393     if (isTypeLegal(IntXVT)) {
6394       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6395                               IntXVT, N0.getOperand(1));
6396       AddToWorklist(X.getNode());
6397
6398       // If X has a different width than the result/lhs, sext it or truncate it.
6399       unsigned VTWidth = VT.getSizeInBits();
6400       if (OrigXWidth < VTWidth) {
6401         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6402         AddToWorklist(X.getNode());
6403       } else if (OrigXWidth > VTWidth) {
6404         // To get the sign bit in the right place, we have to shift it right
6405         // before truncating.
6406         X = DAG.getNode(ISD::SRL, SDLoc(X),
6407                         X.getValueType(), X,
6408                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6409         AddToWorklist(X.getNode());
6410         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6411         AddToWorklist(X.getNode());
6412       }
6413
6414       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6415       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6416                       X, DAG.getConstant(SignBit, VT));
6417       AddToWorklist(X.getNode());
6418
6419       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6420                                 VT, N0.getOperand(0));
6421       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6422                         Cst, DAG.getConstant(~SignBit, VT));
6423       AddToWorklist(Cst.getNode());
6424
6425       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6426     }
6427   }
6428
6429   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6430   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6431     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6432     if (CombineLD.getNode())
6433       return CombineLD;
6434   }
6435
6436   return SDValue();
6437 }
6438
6439 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6440   EVT VT = N->getValueType(0);
6441   return CombineConsecutiveLoads(N, VT);
6442 }
6443
6444 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6445 /// operands. DstEltVT indicates the destination element value type.
6446 SDValue DAGCombiner::
6447 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6448   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6449
6450   // If this is already the right type, we're done.
6451   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6452
6453   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6454   unsigned DstBitSize = DstEltVT.getSizeInBits();
6455
6456   // If this is a conversion of N elements of one type to N elements of another
6457   // type, convert each element.  This handles FP<->INT cases.
6458   if (SrcBitSize == DstBitSize) {
6459     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6460                               BV->getValueType(0).getVectorNumElements());
6461
6462     // Due to the FP element handling below calling this routine recursively,
6463     // we can end up with a scalar-to-vector node here.
6464     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6465       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6466                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6467                                      DstEltVT, BV->getOperand(0)));
6468
6469     SmallVector<SDValue, 8> Ops;
6470     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6471       SDValue Op = BV->getOperand(i);
6472       // If the vector element type is not legal, the BUILD_VECTOR operands
6473       // are promoted and implicitly truncated.  Make that explicit here.
6474       if (Op.getValueType() != SrcEltVT)
6475         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6476       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6477                                 DstEltVT, Op));
6478       AddToWorklist(Ops.back().getNode());
6479     }
6480     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6481   }
6482
6483   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6484   // handle annoying details of growing/shrinking FP values, we convert them to
6485   // int first.
6486   if (SrcEltVT.isFloatingPoint()) {
6487     // Convert the input float vector to a int vector where the elements are the
6488     // same sizes.
6489     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6490     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6491     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6492     SrcEltVT = IntVT;
6493   }
6494
6495   // Now we know the input is an integer vector.  If the output is a FP type,
6496   // convert to integer first, then to FP of the right size.
6497   if (DstEltVT.isFloatingPoint()) {
6498     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6499     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6500     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6501
6502     // Next, convert to FP elements of the same size.
6503     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6504   }
6505
6506   // Okay, we know the src/dst types are both integers of differing types.
6507   // Handling growing first.
6508   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6509   if (SrcBitSize < DstBitSize) {
6510     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6511
6512     SmallVector<SDValue, 8> Ops;
6513     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6514          i += NumInputsPerOutput) {
6515       bool isLE = TLI.isLittleEndian();
6516       APInt NewBits = APInt(DstBitSize, 0);
6517       bool EltIsUndef = true;
6518       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6519         // Shift the previously computed bits over.
6520         NewBits <<= SrcBitSize;
6521         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6522         if (Op.getOpcode() == ISD::UNDEF) continue;
6523         EltIsUndef = false;
6524
6525         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6526                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6527       }
6528
6529       if (EltIsUndef)
6530         Ops.push_back(DAG.getUNDEF(DstEltVT));
6531       else
6532         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6533     }
6534
6535     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6536     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6537   }
6538
6539   // Finally, this must be the case where we are shrinking elements: each input
6540   // turns into multiple outputs.
6541   bool isS2V = ISD::isScalarToVector(BV);
6542   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6543   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6544                             NumOutputsPerInput*BV->getNumOperands());
6545   SmallVector<SDValue, 8> Ops;
6546
6547   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6548     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6549       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6550         Ops.push_back(DAG.getUNDEF(DstEltVT));
6551       continue;
6552     }
6553
6554     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6555                   getAPIntValue().zextOrTrunc(SrcBitSize);
6556
6557     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6558       APInt ThisVal = OpVal.trunc(DstBitSize);
6559       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6560       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6561         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6562         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6563                            Ops[0]);
6564       OpVal = OpVal.lshr(DstBitSize);
6565     }
6566
6567     // For big endian targets, swap the order of the pieces of each element.
6568     if (TLI.isBigEndian())
6569       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6570   }
6571
6572   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6573 }
6574
6575 SDValue DAGCombiner::visitFADD(SDNode *N) {
6576   SDValue N0 = N->getOperand(0);
6577   SDValue N1 = N->getOperand(1);
6578   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6579   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6580   EVT VT = N->getValueType(0);
6581   const TargetOptions &Options = DAG.getTarget().Options;
6582
6583   // fold vector ops
6584   if (VT.isVector()) {
6585     SDValue FoldedVOp = SimplifyVBinOp(N);
6586     if (FoldedVOp.getNode()) return FoldedVOp;
6587   }
6588
6589   // fold (fadd c1, c2) -> c1 + c2
6590   if (N0CFP && N1CFP)
6591     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6592
6593   // canonicalize constant to RHS
6594   if (N0CFP && !N1CFP)
6595     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6596
6597   // fold (fadd A, (fneg B)) -> (fsub A, B)
6598   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6599       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6600     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6601                        GetNegatedExpression(N1, DAG, LegalOperations));
6602
6603   // fold (fadd (fneg A), B) -> (fsub B, A)
6604   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6605       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6606     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6607                        GetNegatedExpression(N0, DAG, LegalOperations));
6608
6609   // If 'unsafe math' is enabled, fold lots of things.
6610   if (Options.UnsafeFPMath) {
6611     // No FP constant should be created after legalization as Instruction
6612     // Selection pass has a hard time dealing with FP constants.
6613     bool AllowNewConst = (Level < AfterLegalizeDAG);
6614
6615     // fold (fadd A, 0) -> A
6616     if (N1CFP && N1CFP->getValueAPF().isZero())
6617       return N0;
6618
6619     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6620     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6621         isa<ConstantFPSDNode>(N0.getOperand(1)))
6622       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6623                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6624                                      N0.getOperand(1), N1));
6625
6626     // If allowed, fold (fadd (fneg x), x) -> 0.0
6627     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6628       return DAG.getConstantFP(0.0, VT);
6629
6630     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6631     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6632       return DAG.getConstantFP(0.0, VT);
6633
6634     // We can fold chains of FADD's of the same value into multiplications.
6635     // This transform is not safe in general because we are reducing the number
6636     // of rounding steps.
6637     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6638       if (N0.getOpcode() == ISD::FMUL) {
6639         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6640         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6641
6642         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6643         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6644           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645                                        SDValue(CFP01, 0),
6646                                        DAG.getConstantFP(1.0, VT));
6647           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6648         }
6649
6650         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6651         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6652             N1.getOperand(0) == N1.getOperand(1) &&
6653             N0.getOperand(0) == N1.getOperand(0)) {
6654           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6655                                        SDValue(CFP01, 0),
6656                                        DAG.getConstantFP(2.0, VT));
6657           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658                              N0.getOperand(0), NewCFP);
6659         }
6660       }
6661
6662       if (N1.getOpcode() == ISD::FMUL) {
6663         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6664         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6665
6666         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6667         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6668           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6669                                        SDValue(CFP11, 0),
6670                                        DAG.getConstantFP(1.0, VT));
6671           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6672         }
6673
6674         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6675         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6676             N0.getOperand(0) == N0.getOperand(1) &&
6677             N1.getOperand(0) == N0.getOperand(0)) {
6678           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6679                                        SDValue(CFP11, 0),
6680                                        DAG.getConstantFP(2.0, VT));
6681           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6682         }
6683       }
6684
6685       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6686         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6687         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6688         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6689             (N0.getOperand(0) == N1))
6690           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6691                              N1, DAG.getConstantFP(3.0, VT));
6692       }
6693
6694       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6695         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6696         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6697         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6698             N1.getOperand(0) == N0)
6699           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6700                              N0, DAG.getConstantFP(3.0, VT));
6701       }
6702
6703       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6704       if (AllowNewConst &&
6705           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6706           N0.getOperand(0) == N0.getOperand(1) &&
6707           N1.getOperand(0) == N1.getOperand(1) &&
6708           N0.getOperand(0) == N1.getOperand(0))
6709         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6710                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6711     }
6712   } // enable-unsafe-fp-math
6713
6714   // FADD -> FMA combines:
6715   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6716       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6717       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6718
6719     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6720     if (N0.getOpcode() == ISD::FMUL &&
6721         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6722       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6723                          N0.getOperand(0), N0.getOperand(1), N1);
6724
6725     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6726     // Note: Commutes FADD operands.
6727     if (N1.getOpcode() == ISD::FMUL &&
6728         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6729       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6730                          N1.getOperand(0), N1.getOperand(1), N0);
6731   }
6732
6733   return SDValue();
6734 }
6735
6736 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6737   SDValue N0 = N->getOperand(0);
6738   SDValue N1 = N->getOperand(1);
6739   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6740   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6741   EVT VT = N->getValueType(0);
6742   SDLoc dl(N);
6743   const TargetOptions &Options = DAG.getTarget().Options;
6744
6745   // fold vector ops
6746   if (VT.isVector()) {
6747     SDValue FoldedVOp = SimplifyVBinOp(N);
6748     if (FoldedVOp.getNode()) return FoldedVOp;
6749   }
6750
6751   // fold (fsub c1, c2) -> c1-c2
6752   if (N0CFP && N1CFP)
6753     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6754
6755   // fold (fsub A, (fneg B)) -> (fadd A, B)
6756   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6757     return DAG.getNode(ISD::FADD, dl, VT, N0,
6758                        GetNegatedExpression(N1, DAG, LegalOperations));
6759
6760   // If 'unsafe math' is enabled, fold lots of things.
6761   if (Options.UnsafeFPMath) {
6762     // (fsub A, 0) -> A
6763     if (N1CFP && N1CFP->getValueAPF().isZero())
6764       return N0;
6765
6766     // (fsub 0, B) -> -B
6767     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6768       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6769         return GetNegatedExpression(N1, DAG, LegalOperations);
6770       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6771         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6772     }
6773
6774     // (fsub x, x) -> 0.0
6775     if (N0 == N1)
6776       return DAG.getConstantFP(0.0f, VT);
6777
6778     // (fsub x, (fadd x, y)) -> (fneg y)
6779     // (fsub x, (fadd y, x)) -> (fneg y)
6780     if (N1.getOpcode() == ISD::FADD) {
6781       SDValue N10 = N1->getOperand(0);
6782       SDValue N11 = N1->getOperand(1);
6783
6784       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6785         return GetNegatedExpression(N11, DAG, LegalOperations);
6786
6787       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6788         return GetNegatedExpression(N10, DAG, LegalOperations);
6789     }
6790   }
6791
6792   // FSUB -> FMA combines:
6793   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6794       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6795       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6796
6797     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6798     if (N0.getOpcode() == ISD::FMUL &&
6799         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6800       return DAG.getNode(ISD::FMA, dl, VT,
6801                          N0.getOperand(0), N0.getOperand(1),
6802                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6803
6804     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6805     // Note: Commutes FSUB operands.
6806     if (N1.getOpcode() == ISD::FMUL &&
6807         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6808       return DAG.getNode(ISD::FMA, dl, VT,
6809                          DAG.getNode(ISD::FNEG, dl, VT,
6810                          N1.getOperand(0)),
6811                          N1.getOperand(1), N0);
6812
6813     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6814     if (N0.getOpcode() == ISD::FNEG &&
6815         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6816         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6817             TLI.enableAggressiveFMAFusion(VT))) {
6818       SDValue N00 = N0.getOperand(0).getOperand(0);
6819       SDValue N01 = N0.getOperand(0).getOperand(1);
6820       return DAG.getNode(ISD::FMA, dl, VT,
6821                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6822                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6823     }
6824   }
6825
6826   return SDValue();
6827 }
6828
6829 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6830   SDValue N0 = N->getOperand(0);
6831   SDValue N1 = N->getOperand(1);
6832   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6833   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6834   EVT VT = N->getValueType(0);
6835   const TargetOptions &Options = DAG.getTarget().Options;
6836
6837   // fold vector ops
6838   if (VT.isVector()) {
6839     // This just handles C1 * C2 for vectors. Other vector folds are below.
6840     SDValue FoldedVOp = SimplifyVBinOp(N);
6841     if (FoldedVOp.getNode())
6842       return FoldedVOp;
6843     // Canonicalize vector constant to RHS.
6844     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6845         N1.getOpcode() != ISD::BUILD_VECTOR)
6846       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6847         if (BV0->isConstant())
6848           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6849   }
6850
6851   // fold (fmul c1, c2) -> c1*c2
6852   if (N0CFP && N1CFP)
6853     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6854
6855   // canonicalize constant to RHS
6856   if (N0CFP && !N1CFP)
6857     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6858
6859   // fold (fmul A, 1.0) -> A
6860   if (N1CFP && N1CFP->isExactlyValue(1.0))
6861     return N0;
6862
6863   if (Options.UnsafeFPMath) {
6864     // fold (fmul A, 0) -> 0
6865     if (N1CFP && N1CFP->getValueAPF().isZero())
6866       return N1;
6867
6868     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6869     if (N0.getOpcode() == ISD::FMUL) {
6870       // Fold scalars or any vector constants (not just splats).
6871       // This fold is done in general by InstCombine, but extra fmul insts
6872       // may have been generated during lowering.
6873       SDValue N01 = N0.getOperand(1);
6874       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6875       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6876       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6877           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6878         SDLoc SL(N);
6879         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6880         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6881       }
6882     }
6883
6884     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6885     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6886     // during an early run of DAGCombiner can prevent folding with fmuls
6887     // inserted during lowering.
6888     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6889       SDLoc SL(N);
6890       const SDValue Two = DAG.getConstantFP(2.0, VT);
6891       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6892       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6893     }
6894   }
6895
6896   // fold (fmul X, 2.0) -> (fadd X, X)
6897   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6898     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6899
6900   // fold (fmul X, -1.0) -> (fneg X)
6901   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6902     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6903       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6904
6905   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6906   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6907     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6908       // Both can be negated for free, check to see if at least one is cheaper
6909       // negated.
6910       if (LHSNeg == 2 || RHSNeg == 2)
6911         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6912                            GetNegatedExpression(N0, DAG, LegalOperations),
6913                            GetNegatedExpression(N1, DAG, LegalOperations));
6914     }
6915   }
6916
6917   return SDValue();
6918 }
6919
6920 SDValue DAGCombiner::visitFMA(SDNode *N) {
6921   SDValue N0 = N->getOperand(0);
6922   SDValue N1 = N->getOperand(1);
6923   SDValue N2 = N->getOperand(2);
6924   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6925   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6926   EVT VT = N->getValueType(0);
6927   SDLoc dl(N);
6928   const TargetOptions &Options = DAG.getTarget().Options;
6929
6930   // Constant fold FMA.
6931   if (isa<ConstantFPSDNode>(N0) &&
6932       isa<ConstantFPSDNode>(N1) &&
6933       isa<ConstantFPSDNode>(N2)) {
6934     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6935   }
6936
6937   if (Options.UnsafeFPMath) {
6938     if (N0CFP && N0CFP->isZero())
6939       return N2;
6940     if (N1CFP && N1CFP->isZero())
6941       return N2;
6942   }
6943   if (N0CFP && N0CFP->isExactlyValue(1.0))
6944     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6945   if (N1CFP && N1CFP->isExactlyValue(1.0))
6946     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6947
6948   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6949   if (N0CFP && !N1CFP)
6950     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6951
6952   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6953   if (Options.UnsafeFPMath && N1CFP &&
6954       N2.getOpcode() == ISD::FMUL &&
6955       N0 == N2.getOperand(0) &&
6956       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6957     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6958                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6959   }
6960
6961
6962   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6963   if (Options.UnsafeFPMath &&
6964       N0.getOpcode() == ISD::FMUL && N1CFP &&
6965       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6966     return DAG.getNode(ISD::FMA, dl, VT,
6967                        N0.getOperand(0),
6968                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6969                        N2);
6970   }
6971
6972   // (fma x, 1, y) -> (fadd x, y)
6973   // (fma x, -1, y) -> (fadd (fneg x), y)
6974   if (N1CFP) {
6975     if (N1CFP->isExactlyValue(1.0))
6976       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6977
6978     if (N1CFP->isExactlyValue(-1.0) &&
6979         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6980       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6981       AddToWorklist(RHSNeg.getNode());
6982       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6983     }
6984   }
6985
6986   // (fma x, c, x) -> (fmul x, (c+1))
6987   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6988     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6989                        DAG.getNode(ISD::FADD, dl, VT,
6990                                    N1, DAG.getConstantFP(1.0, VT)));
6991
6992   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6993   if (Options.UnsafeFPMath && N1CFP &&
6994       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6995     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6996                        DAG.getNode(ISD::FADD, dl, VT,
6997                                    N1, DAG.getConstantFP(-1.0, VT)));
6998
6999
7000   return SDValue();
7001 }
7002
7003 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7004   SDValue N0 = N->getOperand(0);
7005   SDValue N1 = N->getOperand(1);
7006   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7007   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7008   EVT VT = N->getValueType(0);
7009   SDLoc DL(N);
7010   const TargetOptions &Options = DAG.getTarget().Options;
7011
7012   // fold vector ops
7013   if (VT.isVector()) {
7014     SDValue FoldedVOp = SimplifyVBinOp(N);
7015     if (FoldedVOp.getNode()) return FoldedVOp;
7016   }
7017
7018   // fold (fdiv c1, c2) -> c1/c2
7019   if (N0CFP && N1CFP)
7020     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7021
7022   if (Options.UnsafeFPMath) {
7023     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7024     if (N1CFP) {
7025       // Compute the reciprocal 1.0 / c2.
7026       APFloat N1APF = N1CFP->getValueAPF();
7027       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7028       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7029       // Only do the transform if the reciprocal is a legal fp immediate that
7030       // isn't too nasty (eg NaN, denormal, ...).
7031       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7032           (!LegalOperations ||
7033            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7034            // backend)... we should handle this gracefully after Legalize.
7035            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7036            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7037            TLI.isFPImmLegal(Recip, VT)))
7038         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7039                            DAG.getConstantFP(Recip, VT));
7040     }
7041
7042     // If this FDIV is part of a reciprocal square root, it may be folded
7043     // into a target-specific square root estimate instruction.
7044     if (N1.getOpcode() == ISD::FSQRT) {
7045       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7046         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7047       }
7048     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7049                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7050       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7051         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7052         AddToWorklist(RV.getNode());
7053         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7054       }
7055     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7056                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7057       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7058         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7059         AddToWorklist(RV.getNode());
7060         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7061       }
7062     } else if (N1.getOpcode() == ISD::FMUL) {
7063       // Look through an FMUL. Even though this won't remove the FDIV directly,
7064       // it's still worthwhile to get rid of the FSQRT if possible.
7065       SDValue SqrtOp;
7066       SDValue OtherOp;
7067       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7068         SqrtOp = N1.getOperand(0);
7069         OtherOp = N1.getOperand(1);
7070       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7071         SqrtOp = N1.getOperand(1);
7072         OtherOp = N1.getOperand(0);
7073       }
7074       if (SqrtOp.getNode()) {
7075         // We found a FSQRT, so try to make this fold:
7076         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7077         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7078           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7079           AddToWorklist(RV.getNode());
7080           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7081         }
7082       }
7083     }
7084
7085     // Fold into a reciprocal estimate and multiply instead of a real divide.
7086     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7087       AddToWorklist(RV.getNode());
7088       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7089     }
7090   }
7091
7092   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7093   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7094     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7095       // Both can be negated for free, check to see if at least one is cheaper
7096       // negated.
7097       if (LHSNeg == 2 || RHSNeg == 2)
7098         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7099                            GetNegatedExpression(N0, DAG, LegalOperations),
7100                            GetNegatedExpression(N1, DAG, LegalOperations));
7101     }
7102   }
7103
7104   return SDValue();
7105 }
7106
7107 SDValue DAGCombiner::visitFREM(SDNode *N) {
7108   SDValue N0 = N->getOperand(0);
7109   SDValue N1 = N->getOperand(1);
7110   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7111   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7112   EVT VT = N->getValueType(0);
7113
7114   // fold (frem c1, c2) -> fmod(c1,c2)
7115   if (N0CFP && N1CFP)
7116     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7117
7118   return SDValue();
7119 }
7120
7121 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7122   if (DAG.getTarget().Options.UnsafeFPMath) {
7123     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7124     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7125       EVT VT = RV.getValueType();
7126       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7127       AddToWorklist(RV.getNode());
7128
7129       // Unfortunately, RV is now NaN if the input was exactly 0.
7130       // Select out this case and force the answer to 0.
7131       SDValue Zero = DAG.getConstantFP(0.0, VT);
7132       SDValue ZeroCmp =
7133         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7134                      N->getOperand(0), Zero, ISD::SETEQ);
7135       AddToWorklist(ZeroCmp.getNode());
7136       AddToWorklist(RV.getNode());
7137
7138       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7139                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7140       return RV;
7141     }
7142   }
7143   return SDValue();
7144 }
7145
7146 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7147   SDValue N0 = N->getOperand(0);
7148   SDValue N1 = N->getOperand(1);
7149   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7150   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7151   EVT VT = N->getValueType(0);
7152
7153   if (N0CFP && N1CFP)  // Constant fold
7154     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7155
7156   if (N1CFP) {
7157     const APFloat& V = N1CFP->getValueAPF();
7158     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7159     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7160     if (!V.isNegative()) {
7161       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7162         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7163     } else {
7164       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7165         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7166                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7167     }
7168   }
7169
7170   // copysign(fabs(x), y) -> copysign(x, y)
7171   // copysign(fneg(x), y) -> copysign(x, y)
7172   // copysign(copysign(x,z), y) -> copysign(x, y)
7173   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7174       N0.getOpcode() == ISD::FCOPYSIGN)
7175     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7176                        N0.getOperand(0), N1);
7177
7178   // copysign(x, abs(y)) -> abs(x)
7179   if (N1.getOpcode() == ISD::FABS)
7180     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7181
7182   // copysign(x, copysign(y,z)) -> copysign(x, z)
7183   if (N1.getOpcode() == ISD::FCOPYSIGN)
7184     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7185                        N0, N1.getOperand(1));
7186
7187   // copysign(x, fp_extend(y)) -> copysign(x, y)
7188   // copysign(x, fp_round(y)) -> copysign(x, y)
7189   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7190     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7191                        N0, N1.getOperand(0));
7192
7193   return SDValue();
7194 }
7195
7196 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7197   SDValue N0 = N->getOperand(0);
7198   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7199   EVT VT = N->getValueType(0);
7200   EVT OpVT = N0.getValueType();
7201
7202   // fold (sint_to_fp c1) -> c1fp
7203   if (N0C &&
7204       // ...but only if the target supports immediate floating-point values
7205       (!LegalOperations ||
7206        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7207     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7208
7209   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7210   // but UINT_TO_FP is legal on this target, try to convert.
7211   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7212       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7213     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7214     if (DAG.SignBitIsZero(N0))
7215       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7216   }
7217
7218   // The next optimizations are desirable only if SELECT_CC can be lowered.
7219   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7220     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7221     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7222         !VT.isVector() &&
7223         (!LegalOperations ||
7224          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7225       SDValue Ops[] =
7226         { N0.getOperand(0), N0.getOperand(1),
7227           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7228           N0.getOperand(2) };
7229       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7230     }
7231
7232     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7233     //      (select_cc x, y, 1.0, 0.0,, cc)
7234     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7235         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7236         (!LegalOperations ||
7237          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7238       SDValue Ops[] =
7239         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7240           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7241           N0.getOperand(0).getOperand(2) };
7242       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7243     }
7244   }
7245
7246   return SDValue();
7247 }
7248
7249 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7250   SDValue N0 = N->getOperand(0);
7251   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7252   EVT VT = N->getValueType(0);
7253   EVT OpVT = N0.getValueType();
7254
7255   // fold (uint_to_fp c1) -> c1fp
7256   if (N0C &&
7257       // ...but only if the target supports immediate floating-point values
7258       (!LegalOperations ||
7259        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7260     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7261
7262   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7263   // but SINT_TO_FP is legal on this target, try to convert.
7264   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7265       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7266     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7267     if (DAG.SignBitIsZero(N0))
7268       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7269   }
7270
7271   // The next optimizations are desirable only if SELECT_CC can be lowered.
7272   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7273     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7274
7275     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7276         (!LegalOperations ||
7277          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7278       SDValue Ops[] =
7279         { N0.getOperand(0), N0.getOperand(1),
7280           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7281           N0.getOperand(2) };
7282       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7283     }
7284   }
7285
7286   return SDValue();
7287 }
7288
7289 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7290   SDValue N0 = N->getOperand(0);
7291   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7292   EVT VT = N->getValueType(0);
7293
7294   // fold (fp_to_sint c1fp) -> c1
7295   if (N0CFP)
7296     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7297
7298   return SDValue();
7299 }
7300
7301 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7302   SDValue N0 = N->getOperand(0);
7303   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7304   EVT VT = N->getValueType(0);
7305
7306   // fold (fp_to_uint c1fp) -> c1
7307   if (N0CFP)
7308     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7309
7310   return SDValue();
7311 }
7312
7313 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7314   SDValue N0 = N->getOperand(0);
7315   SDValue N1 = N->getOperand(1);
7316   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7317   EVT VT = N->getValueType(0);
7318
7319   // fold (fp_round c1fp) -> c1fp
7320   if (N0CFP)
7321     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7322
7323   // fold (fp_round (fp_extend x)) -> x
7324   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7325     return N0.getOperand(0);
7326
7327   // fold (fp_round (fp_round x)) -> (fp_round x)
7328   if (N0.getOpcode() == ISD::FP_ROUND) {
7329     // This is a value preserving truncation if both round's are.
7330     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7331                    N0.getNode()->getConstantOperandVal(1) == 1;
7332     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7333                        DAG.getIntPtrConstant(IsTrunc));
7334   }
7335
7336   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7337   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7338     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7339                               N0.getOperand(0), N1);
7340     AddToWorklist(Tmp.getNode());
7341     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7342                        Tmp, N0.getOperand(1));
7343   }
7344
7345   return SDValue();
7346 }
7347
7348 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7349   SDValue N0 = N->getOperand(0);
7350   EVT VT = N->getValueType(0);
7351   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7352   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7353
7354   // fold (fp_round_inreg c1fp) -> c1fp
7355   if (N0CFP && isTypeLegal(EVT)) {
7356     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7357     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7358   }
7359
7360   return SDValue();
7361 }
7362
7363 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7364   SDValue N0 = N->getOperand(0);
7365   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7366   EVT VT = N->getValueType(0);
7367
7368   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7369   if (N->hasOneUse() &&
7370       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7371     return SDValue();
7372
7373   // fold (fp_extend c1fp) -> c1fp
7374   if (N0CFP)
7375     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7376
7377   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7378   // value of X.
7379   if (N0.getOpcode() == ISD::FP_ROUND
7380       && N0.getNode()->getConstantOperandVal(1) == 1) {
7381     SDValue In = N0.getOperand(0);
7382     if (In.getValueType() == VT) return In;
7383     if (VT.bitsLT(In.getValueType()))
7384       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7385                          In, N0.getOperand(1));
7386     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7387   }
7388
7389   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7390   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7391        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7392     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7393     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7394                                      LN0->getChain(),
7395                                      LN0->getBasePtr(), N0.getValueType(),
7396                                      LN0->getMemOperand());
7397     CombineTo(N, ExtLoad);
7398     CombineTo(N0.getNode(),
7399               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7400                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7401               ExtLoad.getValue(1));
7402     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7403   }
7404
7405   return SDValue();
7406 }
7407
7408 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7409   SDValue N0 = N->getOperand(0);
7410   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7411   EVT VT = N->getValueType(0);
7412
7413   // fold (fceil c1) -> fceil(c1)
7414   if (N0CFP)
7415     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7416
7417   return SDValue();
7418 }
7419
7420 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7421   SDValue N0 = N->getOperand(0);
7422   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7423   EVT VT = N->getValueType(0);
7424
7425   // fold (ftrunc c1) -> ftrunc(c1)
7426   if (N0CFP)
7427     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7428
7429   return SDValue();
7430 }
7431
7432 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7433   SDValue N0 = N->getOperand(0);
7434   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7435   EVT VT = N->getValueType(0);
7436
7437   // fold (ffloor c1) -> ffloor(c1)
7438   if (N0CFP)
7439     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7440
7441   return SDValue();
7442 }
7443
7444 // FIXME: FNEG and FABS have a lot in common; refactor.
7445 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7446   SDValue N0 = N->getOperand(0);
7447   EVT VT = N->getValueType(0);
7448
7449   if (VT.isVector()) {
7450     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7451     if (FoldedVOp.getNode()) return FoldedVOp;
7452   }
7453
7454   // Constant fold FNEG.
7455   if (isa<ConstantFPSDNode>(N0))
7456     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7457
7458   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7459                          &DAG.getTarget().Options))
7460     return GetNegatedExpression(N0, DAG, LegalOperations);
7461
7462   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7463   // constant pool values.
7464   if (!TLI.isFNegFree(VT) &&
7465       N0.getOpcode() == ISD::BITCAST &&
7466       N0.getNode()->hasOneUse()) {
7467     SDValue Int = N0.getOperand(0);
7468     EVT IntVT = Int.getValueType();
7469     if (IntVT.isInteger() && !IntVT.isVector()) {
7470       APInt SignMask;
7471       if (N0.getValueType().isVector()) {
7472         // For a vector, get a mask such as 0x80... per scalar element
7473         // and splat it.
7474         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7475         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7476       } else {
7477         // For a scalar, just generate 0x80...
7478         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7479       }
7480       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7481                         DAG.getConstant(SignMask, IntVT));
7482       AddToWorklist(Int.getNode());
7483       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7484     }
7485   }
7486
7487   // (fneg (fmul c, x)) -> (fmul -c, x)
7488   if (N0.getOpcode() == ISD::FMUL) {
7489     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7490     if (CFP1) {
7491       APFloat CVal = CFP1->getValueAPF();
7492       CVal.changeSign();
7493       if (Level >= AfterLegalizeDAG &&
7494           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7495            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7496         return DAG.getNode(
7497             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7498             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7499     }
7500   }
7501
7502   return SDValue();
7503 }
7504
7505 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7506   SDValue N0 = N->getOperand(0);
7507   SDValue N1 = N->getOperand(1);
7508   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7509   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7510
7511   if (N0CFP && N1CFP) {
7512     const APFloat &C0 = N0CFP->getValueAPF();
7513     const APFloat &C1 = N1CFP->getValueAPF();
7514     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7515   }
7516
7517   if (N0CFP) {
7518     EVT VT = N->getValueType(0);
7519     // Canonicalize to constant on RHS.
7520     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7521   }
7522
7523   return SDValue();
7524 }
7525
7526 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7527   SDValue N0 = N->getOperand(0);
7528   SDValue N1 = N->getOperand(1);
7529   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7530   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7531
7532   if (N0CFP && N1CFP) {
7533     const APFloat &C0 = N0CFP->getValueAPF();
7534     const APFloat &C1 = N1CFP->getValueAPF();
7535     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7536   }
7537
7538   if (N0CFP) {
7539     EVT VT = N->getValueType(0);
7540     // Canonicalize to constant on RHS.
7541     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7542   }
7543
7544   return SDValue();
7545 }
7546
7547 SDValue DAGCombiner::visitFABS(SDNode *N) {
7548   SDValue N0 = N->getOperand(0);
7549   EVT VT = N->getValueType(0);
7550
7551   if (VT.isVector()) {
7552     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7553     if (FoldedVOp.getNode()) return FoldedVOp;
7554   }
7555
7556   // fold (fabs c1) -> fabs(c1)
7557   if (isa<ConstantFPSDNode>(N0))
7558     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7559
7560   // fold (fabs (fabs x)) -> (fabs x)
7561   if (N0.getOpcode() == ISD::FABS)
7562     return N->getOperand(0);
7563
7564   // fold (fabs (fneg x)) -> (fabs x)
7565   // fold (fabs (fcopysign x, y)) -> (fabs x)
7566   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7567     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7568
7569   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7570   // constant pool values.
7571   if (!TLI.isFAbsFree(VT) &&
7572       N0.getOpcode() == ISD::BITCAST &&
7573       N0.getNode()->hasOneUse()) {
7574     SDValue Int = N0.getOperand(0);
7575     EVT IntVT = Int.getValueType();
7576     if (IntVT.isInteger() && !IntVT.isVector()) {
7577       APInt SignMask;
7578       if (N0.getValueType().isVector()) {
7579         // For a vector, get a mask such as 0x7f... per scalar element
7580         // and splat it.
7581         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7582         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7583       } else {
7584         // For a scalar, just generate 0x7f...
7585         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7586       }
7587       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7588                         DAG.getConstant(SignMask, IntVT));
7589       AddToWorklist(Int.getNode());
7590       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7591     }
7592   }
7593
7594   return SDValue();
7595 }
7596
7597 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7598   SDValue Chain = N->getOperand(0);
7599   SDValue N1 = N->getOperand(1);
7600   SDValue N2 = N->getOperand(2);
7601
7602   // If N is a constant we could fold this into a fallthrough or unconditional
7603   // branch. However that doesn't happen very often in normal code, because
7604   // Instcombine/SimplifyCFG should have handled the available opportunities.
7605   // If we did this folding here, it would be necessary to update the
7606   // MachineBasicBlock CFG, which is awkward.
7607
7608   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7609   // on the target.
7610   if (N1.getOpcode() == ISD::SETCC &&
7611       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7612                                    N1.getOperand(0).getValueType())) {
7613     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7614                        Chain, N1.getOperand(2),
7615                        N1.getOperand(0), N1.getOperand(1), N2);
7616   }
7617
7618   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7619       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7620        (N1.getOperand(0).hasOneUse() &&
7621         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7622     SDNode *Trunc = nullptr;
7623     if (N1.getOpcode() == ISD::TRUNCATE) {
7624       // Look pass the truncate.
7625       Trunc = N1.getNode();
7626       N1 = N1.getOperand(0);
7627     }
7628
7629     // Match this pattern so that we can generate simpler code:
7630     //
7631     //   %a = ...
7632     //   %b = and i32 %a, 2
7633     //   %c = srl i32 %b, 1
7634     //   brcond i32 %c ...
7635     //
7636     // into
7637     //
7638     //   %a = ...
7639     //   %b = and i32 %a, 2
7640     //   %c = setcc eq %b, 0
7641     //   brcond %c ...
7642     //
7643     // This applies only when the AND constant value has one bit set and the
7644     // SRL constant is equal to the log2 of the AND constant. The back-end is
7645     // smart enough to convert the result into a TEST/JMP sequence.
7646     SDValue Op0 = N1.getOperand(0);
7647     SDValue Op1 = N1.getOperand(1);
7648
7649     if (Op0.getOpcode() == ISD::AND &&
7650         Op1.getOpcode() == ISD::Constant) {
7651       SDValue AndOp1 = Op0.getOperand(1);
7652
7653       if (AndOp1.getOpcode() == ISD::Constant) {
7654         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7655
7656         if (AndConst.isPowerOf2() &&
7657             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7658           SDValue SetCC =
7659             DAG.getSetCC(SDLoc(N),
7660                          getSetCCResultType(Op0.getValueType()),
7661                          Op0, DAG.getConstant(0, Op0.getValueType()),
7662                          ISD::SETNE);
7663
7664           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7665                                           MVT::Other, Chain, SetCC, N2);
7666           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7667           // will convert it back to (X & C1) >> C2.
7668           CombineTo(N, NewBRCond, false);
7669           // Truncate is dead.
7670           if (Trunc)
7671             deleteAndRecombine(Trunc);
7672           // Replace the uses of SRL with SETCC
7673           WorklistRemover DeadNodes(*this);
7674           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7675           deleteAndRecombine(N1.getNode());
7676           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7677         }
7678       }
7679     }
7680
7681     if (Trunc)
7682       // Restore N1 if the above transformation doesn't match.
7683       N1 = N->getOperand(1);
7684   }
7685
7686   // Transform br(xor(x, y)) -> br(x != y)
7687   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7688   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7689     SDNode *TheXor = N1.getNode();
7690     SDValue Op0 = TheXor->getOperand(0);
7691     SDValue Op1 = TheXor->getOperand(1);
7692     if (Op0.getOpcode() == Op1.getOpcode()) {
7693       // Avoid missing important xor optimizations.
7694       SDValue Tmp = visitXOR(TheXor);
7695       if (Tmp.getNode()) {
7696         if (Tmp.getNode() != TheXor) {
7697           DEBUG(dbgs() << "\nReplacing.8 ";
7698                 TheXor->dump(&DAG);
7699                 dbgs() << "\nWith: ";
7700                 Tmp.getNode()->dump(&DAG);
7701                 dbgs() << '\n');
7702           WorklistRemover DeadNodes(*this);
7703           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7704           deleteAndRecombine(TheXor);
7705           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7706                              MVT::Other, Chain, Tmp, N2);
7707         }
7708
7709         // visitXOR has changed XOR's operands or replaced the XOR completely,
7710         // bail out.
7711         return SDValue(N, 0);
7712       }
7713     }
7714
7715     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7716       bool Equal = false;
7717       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7718         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7719             Op0.getOpcode() == ISD::XOR) {
7720           TheXor = Op0.getNode();
7721           Equal = true;
7722         }
7723
7724       EVT SetCCVT = N1.getValueType();
7725       if (LegalTypes)
7726         SetCCVT = getSetCCResultType(SetCCVT);
7727       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7728                                    SetCCVT,
7729                                    Op0, Op1,
7730                                    Equal ? ISD::SETEQ : ISD::SETNE);
7731       // Replace the uses of XOR with SETCC
7732       WorklistRemover DeadNodes(*this);
7733       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7734       deleteAndRecombine(N1.getNode());
7735       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7736                          MVT::Other, Chain, SetCC, N2);
7737     }
7738   }
7739
7740   return SDValue();
7741 }
7742
7743 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7744 //
7745 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7746   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7747   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7748
7749   // If N is a constant we could fold this into a fallthrough or unconditional
7750   // branch. However that doesn't happen very often in normal code, because
7751   // Instcombine/SimplifyCFG should have handled the available opportunities.
7752   // If we did this folding here, it would be necessary to update the
7753   // MachineBasicBlock CFG, which is awkward.
7754
7755   // Use SimplifySetCC to simplify SETCC's.
7756   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7757                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7758                                false);
7759   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7760
7761   // fold to a simpler setcc
7762   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7763     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7764                        N->getOperand(0), Simp.getOperand(2),
7765                        Simp.getOperand(0), Simp.getOperand(1),
7766                        N->getOperand(4));
7767
7768   return SDValue();
7769 }
7770
7771 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7772 /// and that N may be folded in the load / store addressing mode.
7773 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7774                                     SelectionDAG &DAG,
7775                                     const TargetLowering &TLI) {
7776   EVT VT;
7777   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7778     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7779       return false;
7780     VT = Use->getValueType(0);
7781   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7782     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7783       return false;
7784     VT = ST->getValue().getValueType();
7785   } else
7786     return false;
7787
7788   TargetLowering::AddrMode AM;
7789   if (N->getOpcode() == ISD::ADD) {
7790     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7791     if (Offset)
7792       // [reg +/- imm]
7793       AM.BaseOffs = Offset->getSExtValue();
7794     else
7795       // [reg +/- reg]
7796       AM.Scale = 1;
7797   } else if (N->getOpcode() == ISD::SUB) {
7798     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7799     if (Offset)
7800       // [reg +/- imm]
7801       AM.BaseOffs = -Offset->getSExtValue();
7802     else
7803       // [reg +/- reg]
7804       AM.Scale = 1;
7805   } else
7806     return false;
7807
7808   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7809 }
7810
7811 /// Try turning a load/store into a pre-indexed load/store when the base
7812 /// pointer is an add or subtract and it has other uses besides the load/store.
7813 /// After the transformation, the new indexed load/store has effectively folded
7814 /// the add/subtract in and all of its other uses are redirected to the
7815 /// new load/store.
7816 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7817   if (Level < AfterLegalizeDAG)
7818     return false;
7819
7820   bool isLoad = true;
7821   SDValue Ptr;
7822   EVT VT;
7823   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7824     if (LD->isIndexed())
7825       return false;
7826     VT = LD->getMemoryVT();
7827     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7828         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7829       return false;
7830     Ptr = LD->getBasePtr();
7831   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7832     if (ST->isIndexed())
7833       return false;
7834     VT = ST->getMemoryVT();
7835     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7836         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7837       return false;
7838     Ptr = ST->getBasePtr();
7839     isLoad = false;
7840   } else {
7841     return false;
7842   }
7843
7844   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7845   // out.  There is no reason to make this a preinc/predec.
7846   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7847       Ptr.getNode()->hasOneUse())
7848     return false;
7849
7850   // Ask the target to do addressing mode selection.
7851   SDValue BasePtr;
7852   SDValue Offset;
7853   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7854   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7855     return false;
7856
7857   // Backends without true r+i pre-indexed forms may need to pass a
7858   // constant base with a variable offset so that constant coercion
7859   // will work with the patterns in canonical form.
7860   bool Swapped = false;
7861   if (isa<ConstantSDNode>(BasePtr)) {
7862     std::swap(BasePtr, Offset);
7863     Swapped = true;
7864   }
7865
7866   // Don't create a indexed load / store with zero offset.
7867   if (isa<ConstantSDNode>(Offset) &&
7868       cast<ConstantSDNode>(Offset)->isNullValue())
7869     return false;
7870
7871   // Try turning it into a pre-indexed load / store except when:
7872   // 1) The new base ptr is a frame index.
7873   // 2) If N is a store and the new base ptr is either the same as or is a
7874   //    predecessor of the value being stored.
7875   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7876   //    that would create a cycle.
7877   // 4) All uses are load / store ops that use it as old base ptr.
7878
7879   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7880   // (plus the implicit offset) to a register to preinc anyway.
7881   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7882     return false;
7883
7884   // Check #2.
7885   if (!isLoad) {
7886     SDValue Val = cast<StoreSDNode>(N)->getValue();
7887     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7888       return false;
7889   }
7890
7891   // If the offset is a constant, there may be other adds of constants that
7892   // can be folded with this one. We should do this to avoid having to keep
7893   // a copy of the original base pointer.
7894   SmallVector<SDNode *, 16> OtherUses;
7895   if (isa<ConstantSDNode>(Offset))
7896     for (SDNode *Use : BasePtr.getNode()->uses()) {
7897       if (Use == Ptr.getNode())
7898         continue;
7899
7900       if (Use->isPredecessorOf(N))
7901         continue;
7902
7903       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7904         OtherUses.clear();
7905         break;
7906       }
7907
7908       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7909       if (Op1.getNode() == BasePtr.getNode())
7910         std::swap(Op0, Op1);
7911       assert(Op0.getNode() == BasePtr.getNode() &&
7912              "Use of ADD/SUB but not an operand");
7913
7914       if (!isa<ConstantSDNode>(Op1)) {
7915         OtherUses.clear();
7916         break;
7917       }
7918
7919       // FIXME: In some cases, we can be smarter about this.
7920       if (Op1.getValueType() != Offset.getValueType()) {
7921         OtherUses.clear();
7922         break;
7923       }
7924
7925       OtherUses.push_back(Use);
7926     }
7927
7928   if (Swapped)
7929     std::swap(BasePtr, Offset);
7930
7931   // Now check for #3 and #4.
7932   bool RealUse = false;
7933
7934   // Caches for hasPredecessorHelper
7935   SmallPtrSet<const SDNode *, 32> Visited;
7936   SmallVector<const SDNode *, 16> Worklist;
7937
7938   for (SDNode *Use : Ptr.getNode()->uses()) {
7939     if (Use == N)
7940       continue;
7941     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7942       return false;
7943
7944     // If Ptr may be folded in addressing mode of other use, then it's
7945     // not profitable to do this transformation.
7946     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7947       RealUse = true;
7948   }
7949
7950   if (!RealUse)
7951     return false;
7952
7953   SDValue Result;
7954   if (isLoad)
7955     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7956                                 BasePtr, Offset, AM);
7957   else
7958     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7959                                  BasePtr, Offset, AM);
7960   ++PreIndexedNodes;
7961   ++NodesCombined;
7962   DEBUG(dbgs() << "\nReplacing.4 ";
7963         N->dump(&DAG);
7964         dbgs() << "\nWith: ";
7965         Result.getNode()->dump(&DAG);
7966         dbgs() << '\n');
7967   WorklistRemover DeadNodes(*this);
7968   if (isLoad) {
7969     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7970     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7971   } else {
7972     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7973   }
7974
7975   // Finally, since the node is now dead, remove it from the graph.
7976   deleteAndRecombine(N);
7977
7978   if (Swapped)
7979     std::swap(BasePtr, Offset);
7980
7981   // Replace other uses of BasePtr that can be updated to use Ptr
7982   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7983     unsigned OffsetIdx = 1;
7984     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7985       OffsetIdx = 0;
7986     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7987            BasePtr.getNode() && "Expected BasePtr operand");
7988
7989     // We need to replace ptr0 in the following expression:
7990     //   x0 * offset0 + y0 * ptr0 = t0
7991     // knowing that
7992     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7993     //
7994     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7995     // indexed load/store and the expresion that needs to be re-written.
7996     //
7997     // Therefore, we have:
7998     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7999
8000     ConstantSDNode *CN =
8001       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8002     int X0, X1, Y0, Y1;
8003     APInt Offset0 = CN->getAPIntValue();
8004     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8005
8006     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8007     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8008     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8009     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8010
8011     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8012
8013     APInt CNV = Offset0;
8014     if (X0 < 0) CNV = -CNV;
8015     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8016     else CNV = CNV - Offset1;
8017
8018     // We can now generate the new expression.
8019     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8020     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8021
8022     SDValue NewUse = DAG.getNode(Opcode,
8023                                  SDLoc(OtherUses[i]),
8024                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8025     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8026     deleteAndRecombine(OtherUses[i]);
8027   }
8028
8029   // Replace the uses of Ptr with uses of the updated base value.
8030   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8031   deleteAndRecombine(Ptr.getNode());
8032
8033   return true;
8034 }
8035
8036 /// Try to combine a load/store with a add/sub of the base pointer node into a
8037 /// post-indexed load/store. The transformation folded the add/subtract into the
8038 /// new indexed load/store effectively and all of its uses are redirected to the
8039 /// new load/store.
8040 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8041   if (Level < AfterLegalizeDAG)
8042     return false;
8043
8044   bool isLoad = true;
8045   SDValue Ptr;
8046   EVT VT;
8047   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8048     if (LD->isIndexed())
8049       return false;
8050     VT = LD->getMemoryVT();
8051     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8052         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8053       return false;
8054     Ptr = LD->getBasePtr();
8055   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8056     if (ST->isIndexed())
8057       return false;
8058     VT = ST->getMemoryVT();
8059     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8060         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8061       return false;
8062     Ptr = ST->getBasePtr();
8063     isLoad = false;
8064   } else {
8065     return false;
8066   }
8067
8068   if (Ptr.getNode()->hasOneUse())
8069     return false;
8070
8071   for (SDNode *Op : Ptr.getNode()->uses()) {
8072     if (Op == N ||
8073         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8074       continue;
8075
8076     SDValue BasePtr;
8077     SDValue Offset;
8078     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8079     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8080       // Don't create a indexed load / store with zero offset.
8081       if (isa<ConstantSDNode>(Offset) &&
8082           cast<ConstantSDNode>(Offset)->isNullValue())
8083         continue;
8084
8085       // Try turning it into a post-indexed load / store except when
8086       // 1) All uses are load / store ops that use it as base ptr (and
8087       //    it may be folded as addressing mmode).
8088       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8089       //    nor a successor of N. Otherwise, if Op is folded that would
8090       //    create a cycle.
8091
8092       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8093         continue;
8094
8095       // Check for #1.
8096       bool TryNext = false;
8097       for (SDNode *Use : BasePtr.getNode()->uses()) {
8098         if (Use == Ptr.getNode())
8099           continue;
8100
8101         // If all the uses are load / store addresses, then don't do the
8102         // transformation.
8103         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8104           bool RealUse = false;
8105           for (SDNode *UseUse : Use->uses()) {
8106             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8107               RealUse = true;
8108           }
8109
8110           if (!RealUse) {
8111             TryNext = true;
8112             break;
8113           }
8114         }
8115       }
8116
8117       if (TryNext)
8118         continue;
8119
8120       // Check for #2
8121       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8122         SDValue Result = isLoad
8123           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8124                                BasePtr, Offset, AM)
8125           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8126                                 BasePtr, Offset, AM);
8127         ++PostIndexedNodes;
8128         ++NodesCombined;
8129         DEBUG(dbgs() << "\nReplacing.5 ";
8130               N->dump(&DAG);
8131               dbgs() << "\nWith: ";
8132               Result.getNode()->dump(&DAG);
8133               dbgs() << '\n');
8134         WorklistRemover DeadNodes(*this);
8135         if (isLoad) {
8136           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8137           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8138         } else {
8139           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8140         }
8141
8142         // Finally, since the node is now dead, remove it from the graph.
8143         deleteAndRecombine(N);
8144
8145         // Replace the uses of Use with uses of the updated base value.
8146         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8147                                       Result.getValue(isLoad ? 1 : 0));
8148         deleteAndRecombine(Op);
8149         return true;
8150       }
8151     }
8152   }
8153
8154   return false;
8155 }
8156
8157 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8158 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8159   ISD::MemIndexedMode AM = LD->getAddressingMode();
8160   assert(AM != ISD::UNINDEXED);
8161   SDValue BP = LD->getOperand(1);
8162   SDValue Inc = LD->getOperand(2);
8163
8164   // Some backends use TargetConstants for load offsets, but don't expect
8165   // TargetConstants in general ADD nodes. We can convert these constants into
8166   // regular Constants (if the constant is not opaque).
8167   assert((Inc.getOpcode() != ISD::TargetConstant ||
8168           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8169          "Cannot split out indexing using opaque target constants");
8170   if (Inc.getOpcode() == ISD::TargetConstant) {
8171     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8172     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8173                           ConstInc->getValueType(0));
8174   }
8175
8176   unsigned Opc =
8177       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8178   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8179 }
8180
8181 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8182   LoadSDNode *LD  = cast<LoadSDNode>(N);
8183   SDValue Chain = LD->getChain();
8184   SDValue Ptr   = LD->getBasePtr();
8185
8186   // If load is not volatile and there are no uses of the loaded value (and
8187   // the updated indexed value in case of indexed loads), change uses of the
8188   // chain value into uses of the chain input (i.e. delete the dead load).
8189   if (!LD->isVolatile()) {
8190     if (N->getValueType(1) == MVT::Other) {
8191       // Unindexed loads.
8192       if (!N->hasAnyUseOfValue(0)) {
8193         // It's not safe to use the two value CombineTo variant here. e.g.
8194         // v1, chain2 = load chain1, loc
8195         // v2, chain3 = load chain2, loc
8196         // v3         = add v2, c
8197         // Now we replace use of chain2 with chain1.  This makes the second load
8198         // isomorphic to the one we are deleting, and thus makes this load live.
8199         DEBUG(dbgs() << "\nReplacing.6 ";
8200               N->dump(&DAG);
8201               dbgs() << "\nWith chain: ";
8202               Chain.getNode()->dump(&DAG);
8203               dbgs() << "\n");
8204         WorklistRemover DeadNodes(*this);
8205         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8206
8207         if (N->use_empty())
8208           deleteAndRecombine(N);
8209
8210         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8211       }
8212     } else {
8213       // Indexed loads.
8214       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8215
8216       // If this load has an opaque TargetConstant offset, then we cannot split
8217       // the indexing into an add/sub directly (that TargetConstant may not be
8218       // valid for a different type of node, and we cannot convert an opaque
8219       // target constant into a regular constant).
8220       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8221                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8222
8223       if (!N->hasAnyUseOfValue(0) &&
8224           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8225         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8226         SDValue Index;
8227         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8228           Index = SplitIndexingFromLoad(LD);
8229           // Try to fold the base pointer arithmetic into subsequent loads and
8230           // stores.
8231           AddUsersToWorklist(N);
8232         } else
8233           Index = DAG.getUNDEF(N->getValueType(1));
8234         DEBUG(dbgs() << "\nReplacing.7 ";
8235               N->dump(&DAG);
8236               dbgs() << "\nWith: ";
8237               Undef.getNode()->dump(&DAG);
8238               dbgs() << " and 2 other values\n");
8239         WorklistRemover DeadNodes(*this);
8240         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8241         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8242         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8243         deleteAndRecombine(N);
8244         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8245       }
8246     }
8247   }
8248
8249   // If this load is directly stored, replace the load value with the stored
8250   // value.
8251   // TODO: Handle store large -> read small portion.
8252   // TODO: Handle TRUNCSTORE/LOADEXT
8253   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8254     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8255       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8256       if (PrevST->getBasePtr() == Ptr &&
8257           PrevST->getValue().getValueType() == N->getValueType(0))
8258       return CombineTo(N, Chain.getOperand(1), Chain);
8259     }
8260   }
8261
8262   // Try to infer better alignment information than the load already has.
8263   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8264     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8265       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8266         SDValue NewLoad =
8267                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8268                               LD->getValueType(0),
8269                               Chain, Ptr, LD->getPointerInfo(),
8270                               LD->getMemoryVT(),
8271                               LD->isVolatile(), LD->isNonTemporal(),
8272                               LD->isInvariant(), Align, LD->getAAInfo());
8273         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8274       }
8275     }
8276   }
8277
8278   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8279                                                   : DAG.getSubtarget().useAA();
8280 #ifndef NDEBUG
8281   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8282       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8283     UseAA = false;
8284 #endif
8285   if (UseAA && LD->isUnindexed()) {
8286     // Walk up chain skipping non-aliasing memory nodes.
8287     SDValue BetterChain = FindBetterChain(N, Chain);
8288
8289     // If there is a better chain.
8290     if (Chain != BetterChain) {
8291       SDValue ReplLoad;
8292
8293       // Replace the chain to void dependency.
8294       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8295         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8296                                BetterChain, Ptr, LD->getMemOperand());
8297       } else {
8298         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8299                                   LD->getValueType(0),
8300                                   BetterChain, Ptr, LD->getMemoryVT(),
8301                                   LD->getMemOperand());
8302       }
8303
8304       // Create token factor to keep old chain connected.
8305       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8306                                   MVT::Other, Chain, ReplLoad.getValue(1));
8307
8308       // Make sure the new and old chains are cleaned up.
8309       AddToWorklist(Token.getNode());
8310
8311       // Replace uses with load result and token factor. Don't add users
8312       // to work list.
8313       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8314     }
8315   }
8316
8317   // Try transforming N to an indexed load.
8318   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8319     return SDValue(N, 0);
8320
8321   // Try to slice up N to more direct loads if the slices are mapped to
8322   // different register banks or pairing can take place.
8323   if (SliceUpLoad(N))
8324     return SDValue(N, 0);
8325
8326   return SDValue();
8327 }
8328
8329 namespace {
8330 /// \brief Helper structure used to slice a load in smaller loads.
8331 /// Basically a slice is obtained from the following sequence:
8332 /// Origin = load Ty1, Base
8333 /// Shift = srl Ty1 Origin, CstTy Amount
8334 /// Inst = trunc Shift to Ty2
8335 ///
8336 /// Then, it will be rewriten into:
8337 /// Slice = load SliceTy, Base + SliceOffset
8338 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8339 ///
8340 /// SliceTy is deduced from the number of bits that are actually used to
8341 /// build Inst.
8342 struct LoadedSlice {
8343   /// \brief Helper structure used to compute the cost of a slice.
8344   struct Cost {
8345     /// Are we optimizing for code size.
8346     bool ForCodeSize;
8347     /// Various cost.
8348     unsigned Loads;
8349     unsigned Truncates;
8350     unsigned CrossRegisterBanksCopies;
8351     unsigned ZExts;
8352     unsigned Shift;
8353
8354     Cost(bool ForCodeSize = false)
8355         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8356           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8357
8358     /// \brief Get the cost of one isolated slice.
8359     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8360         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8361           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8362       EVT TruncType = LS.Inst->getValueType(0);
8363       EVT LoadedType = LS.getLoadedType();
8364       if (TruncType != LoadedType &&
8365           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8366         ZExts = 1;
8367     }
8368
8369     /// \brief Account for slicing gain in the current cost.
8370     /// Slicing provide a few gains like removing a shift or a
8371     /// truncate. This method allows to grow the cost of the original
8372     /// load with the gain from this slice.
8373     void addSliceGain(const LoadedSlice &LS) {
8374       // Each slice saves a truncate.
8375       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8376       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8377                               LS.Inst->getOperand(0).getValueType()))
8378         ++Truncates;
8379       // If there is a shift amount, this slice gets rid of it.
8380       if (LS.Shift)
8381         ++Shift;
8382       // If this slice can merge a cross register bank copy, account for it.
8383       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8384         ++CrossRegisterBanksCopies;
8385     }
8386
8387     Cost &operator+=(const Cost &RHS) {
8388       Loads += RHS.Loads;
8389       Truncates += RHS.Truncates;
8390       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8391       ZExts += RHS.ZExts;
8392       Shift += RHS.Shift;
8393       return *this;
8394     }
8395
8396     bool operator==(const Cost &RHS) const {
8397       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8398              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8399              ZExts == RHS.ZExts && Shift == RHS.Shift;
8400     }
8401
8402     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8403
8404     bool operator<(const Cost &RHS) const {
8405       // Assume cross register banks copies are as expensive as loads.
8406       // FIXME: Do we want some more target hooks?
8407       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8408       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8409       // Unless we are optimizing for code size, consider the
8410       // expensive operation first.
8411       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8412         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8413       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8414              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8415     }
8416
8417     bool operator>(const Cost &RHS) const { return RHS < *this; }
8418
8419     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8420
8421     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8422   };
8423   // The last instruction that represent the slice. This should be a
8424   // truncate instruction.
8425   SDNode *Inst;
8426   // The original load instruction.
8427   LoadSDNode *Origin;
8428   // The right shift amount in bits from the original load.
8429   unsigned Shift;
8430   // The DAG from which Origin came from.
8431   // This is used to get some contextual information about legal types, etc.
8432   SelectionDAG *DAG;
8433
8434   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8435               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8436       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8437
8438   LoadedSlice(const LoadedSlice &LS)
8439       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8440
8441   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8442   /// \return Result is \p BitWidth and has used bits set to 1 and
8443   ///         not used bits set to 0.
8444   APInt getUsedBits() const {
8445     // Reproduce the trunc(lshr) sequence:
8446     // - Start from the truncated value.
8447     // - Zero extend to the desired bit width.
8448     // - Shift left.
8449     assert(Origin && "No original load to compare against.");
8450     unsigned BitWidth = Origin->getValueSizeInBits(0);
8451     assert(Inst && "This slice is not bound to an instruction");
8452     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8453            "Extracted slice is bigger than the whole type!");
8454     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8455     UsedBits.setAllBits();
8456     UsedBits = UsedBits.zext(BitWidth);
8457     UsedBits <<= Shift;
8458     return UsedBits;
8459   }
8460
8461   /// \brief Get the size of the slice to be loaded in bytes.
8462   unsigned getLoadedSize() const {
8463     unsigned SliceSize = getUsedBits().countPopulation();
8464     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8465     return SliceSize / 8;
8466   }
8467
8468   /// \brief Get the type that will be loaded for this slice.
8469   /// Note: This may not be the final type for the slice.
8470   EVT getLoadedType() const {
8471     assert(DAG && "Missing context");
8472     LLVMContext &Ctxt = *DAG->getContext();
8473     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8474   }
8475
8476   /// \brief Get the alignment of the load used for this slice.
8477   unsigned getAlignment() const {
8478     unsigned Alignment = Origin->getAlignment();
8479     unsigned Offset = getOffsetFromBase();
8480     if (Offset != 0)
8481       Alignment = MinAlign(Alignment, Alignment + Offset);
8482     return Alignment;
8483   }
8484
8485   /// \brief Check if this slice can be rewritten with legal operations.
8486   bool isLegal() const {
8487     // An invalid slice is not legal.
8488     if (!Origin || !Inst || !DAG)
8489       return false;
8490
8491     // Offsets are for indexed load only, we do not handle that.
8492     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8493       return false;
8494
8495     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8496
8497     // Check that the type is legal.
8498     EVT SliceType = getLoadedType();
8499     if (!TLI.isTypeLegal(SliceType))
8500       return false;
8501
8502     // Check that the load is legal for this type.
8503     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8504       return false;
8505
8506     // Check that the offset can be computed.
8507     // 1. Check its type.
8508     EVT PtrType = Origin->getBasePtr().getValueType();
8509     if (PtrType == MVT::Untyped || PtrType.isExtended())
8510       return false;
8511
8512     // 2. Check that it fits in the immediate.
8513     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8514       return false;
8515
8516     // 3. Check that the computation is legal.
8517     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8518       return false;
8519
8520     // Check that the zext is legal if it needs one.
8521     EVT TruncateType = Inst->getValueType(0);
8522     if (TruncateType != SliceType &&
8523         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8524       return false;
8525
8526     return true;
8527   }
8528
8529   /// \brief Get the offset in bytes of this slice in the original chunk of
8530   /// bits.
8531   /// \pre DAG != nullptr.
8532   uint64_t getOffsetFromBase() const {
8533     assert(DAG && "Missing context.");
8534     bool IsBigEndian =
8535         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8536     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8537     uint64_t Offset = Shift / 8;
8538     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8539     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8540            "The size of the original loaded type is not a multiple of a"
8541            " byte.");
8542     // If Offset is bigger than TySizeInBytes, it means we are loading all
8543     // zeros. This should have been optimized before in the process.
8544     assert(TySizeInBytes > Offset &&
8545            "Invalid shift amount for given loaded size");
8546     if (IsBigEndian)
8547       Offset = TySizeInBytes - Offset - getLoadedSize();
8548     return Offset;
8549   }
8550
8551   /// \brief Generate the sequence of instructions to load the slice
8552   /// represented by this object and redirect the uses of this slice to
8553   /// this new sequence of instructions.
8554   /// \pre this->Inst && this->Origin are valid Instructions and this
8555   /// object passed the legal check: LoadedSlice::isLegal returned true.
8556   /// \return The last instruction of the sequence used to load the slice.
8557   SDValue loadSlice() const {
8558     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8559     const SDValue &OldBaseAddr = Origin->getBasePtr();
8560     SDValue BaseAddr = OldBaseAddr;
8561     // Get the offset in that chunk of bytes w.r.t. the endianess.
8562     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8563     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8564     if (Offset) {
8565       // BaseAddr = BaseAddr + Offset.
8566       EVT ArithType = BaseAddr.getValueType();
8567       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8568                               DAG->getConstant(Offset, ArithType));
8569     }
8570
8571     // Create the type of the loaded slice according to its size.
8572     EVT SliceType = getLoadedType();
8573
8574     // Create the load for the slice.
8575     SDValue LastInst = DAG->getLoad(
8576         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8577         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8578         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8579     // If the final type is not the same as the loaded type, this means that
8580     // we have to pad with zero. Create a zero extend for that.
8581     EVT FinalType = Inst->getValueType(0);
8582     if (SliceType != FinalType)
8583       LastInst =
8584           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8585     return LastInst;
8586   }
8587
8588   /// \brief Check if this slice can be merged with an expensive cross register
8589   /// bank copy. E.g.,
8590   /// i = load i32
8591   /// f = bitcast i32 i to float
8592   bool canMergeExpensiveCrossRegisterBankCopy() const {
8593     if (!Inst || !Inst->hasOneUse())
8594       return false;
8595     SDNode *Use = *Inst->use_begin();
8596     if (Use->getOpcode() != ISD::BITCAST)
8597       return false;
8598     assert(DAG && "Missing context");
8599     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8600     EVT ResVT = Use->getValueType(0);
8601     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8602     const TargetRegisterClass *ArgRC =
8603         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8604     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8605       return false;
8606
8607     // At this point, we know that we perform a cross-register-bank copy.
8608     // Check if it is expensive.
8609     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8610     // Assume bitcasts are cheap, unless both register classes do not
8611     // explicitly share a common sub class.
8612     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8613       return false;
8614
8615     // Check if it will be merged with the load.
8616     // 1. Check the alignment constraint.
8617     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8618         ResVT.getTypeForEVT(*DAG->getContext()));
8619
8620     if (RequiredAlignment > getAlignment())
8621       return false;
8622
8623     // 2. Check that the load is a legal operation for that type.
8624     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8625       return false;
8626
8627     // 3. Check that we do not have a zext in the way.
8628     if (Inst->getValueType(0) != getLoadedType())
8629       return false;
8630
8631     return true;
8632   }
8633 };
8634 }
8635
8636 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8637 /// \p UsedBits looks like 0..0 1..1 0..0.
8638 static bool areUsedBitsDense(const APInt &UsedBits) {
8639   // If all the bits are one, this is dense!
8640   if (UsedBits.isAllOnesValue())
8641     return true;
8642
8643   // Get rid of the unused bits on the right.
8644   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8645   // Get rid of the unused bits on the left.
8646   if (NarrowedUsedBits.countLeadingZeros())
8647     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8648   // Check that the chunk of bits is completely used.
8649   return NarrowedUsedBits.isAllOnesValue();
8650 }
8651
8652 /// \brief Check whether or not \p First and \p Second are next to each other
8653 /// in memory. This means that there is no hole between the bits loaded
8654 /// by \p First and the bits loaded by \p Second.
8655 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8656                                      const LoadedSlice &Second) {
8657   assert(First.Origin == Second.Origin && First.Origin &&
8658          "Unable to match different memory origins.");
8659   APInt UsedBits = First.getUsedBits();
8660   assert((UsedBits & Second.getUsedBits()) == 0 &&
8661          "Slices are not supposed to overlap.");
8662   UsedBits |= Second.getUsedBits();
8663   return areUsedBitsDense(UsedBits);
8664 }
8665
8666 /// \brief Adjust the \p GlobalLSCost according to the target
8667 /// paring capabilities and the layout of the slices.
8668 /// \pre \p GlobalLSCost should account for at least as many loads as
8669 /// there is in the slices in \p LoadedSlices.
8670 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8671                                  LoadedSlice::Cost &GlobalLSCost) {
8672   unsigned NumberOfSlices = LoadedSlices.size();
8673   // If there is less than 2 elements, no pairing is possible.
8674   if (NumberOfSlices < 2)
8675     return;
8676
8677   // Sort the slices so that elements that are likely to be next to each
8678   // other in memory are next to each other in the list.
8679   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8680             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8681     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8682     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8683   });
8684   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8685   // First (resp. Second) is the first (resp. Second) potentially candidate
8686   // to be placed in a paired load.
8687   const LoadedSlice *First = nullptr;
8688   const LoadedSlice *Second = nullptr;
8689   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8690                 // Set the beginning of the pair.
8691                                                            First = Second) {
8692
8693     Second = &LoadedSlices[CurrSlice];
8694
8695     // If First is NULL, it means we start a new pair.
8696     // Get to the next slice.
8697     if (!First)
8698       continue;
8699
8700     EVT LoadedType = First->getLoadedType();
8701
8702     // If the types of the slices are different, we cannot pair them.
8703     if (LoadedType != Second->getLoadedType())
8704       continue;
8705
8706     // Check if the target supplies paired loads for this type.
8707     unsigned RequiredAlignment = 0;
8708     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8709       // move to the next pair, this type is hopeless.
8710       Second = nullptr;
8711       continue;
8712     }
8713     // Check if we meet the alignment requirement.
8714     if (RequiredAlignment > First->getAlignment())
8715       continue;
8716
8717     // Check that both loads are next to each other in memory.
8718     if (!areSlicesNextToEachOther(*First, *Second))
8719       continue;
8720
8721     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8722     --GlobalLSCost.Loads;
8723     // Move to the next pair.
8724     Second = nullptr;
8725   }
8726 }
8727
8728 /// \brief Check the profitability of all involved LoadedSlice.
8729 /// Currently, it is considered profitable if there is exactly two
8730 /// involved slices (1) which are (2) next to each other in memory, and
8731 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8732 ///
8733 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8734 /// the elements themselves.
8735 ///
8736 /// FIXME: When the cost model will be mature enough, we can relax
8737 /// constraints (1) and (2).
8738 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8739                                 const APInt &UsedBits, bool ForCodeSize) {
8740   unsigned NumberOfSlices = LoadedSlices.size();
8741   if (StressLoadSlicing)
8742     return NumberOfSlices > 1;
8743
8744   // Check (1).
8745   if (NumberOfSlices != 2)
8746     return false;
8747
8748   // Check (2).
8749   if (!areUsedBitsDense(UsedBits))
8750     return false;
8751
8752   // Check (3).
8753   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8754   // The original code has one big load.
8755   OrigCost.Loads = 1;
8756   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8757     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8758     // Accumulate the cost of all the slices.
8759     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8760     GlobalSlicingCost += SliceCost;
8761
8762     // Account as cost in the original configuration the gain obtained
8763     // with the current slices.
8764     OrigCost.addSliceGain(LS);
8765   }
8766
8767   // If the target supports paired load, adjust the cost accordingly.
8768   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8769   return OrigCost > GlobalSlicingCost;
8770 }
8771
8772 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8773 /// operations, split it in the various pieces being extracted.
8774 ///
8775 /// This sort of thing is introduced by SROA.
8776 /// This slicing takes care not to insert overlapping loads.
8777 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8778 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8779   if (Level < AfterLegalizeDAG)
8780     return false;
8781
8782   LoadSDNode *LD = cast<LoadSDNode>(N);
8783   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8784       !LD->getValueType(0).isInteger())
8785     return false;
8786
8787   // Keep track of already used bits to detect overlapping values.
8788   // In that case, we will just abort the transformation.
8789   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8790
8791   SmallVector<LoadedSlice, 4> LoadedSlices;
8792
8793   // Check if this load is used as several smaller chunks of bits.
8794   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8795   // of computation for each trunc.
8796   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8797        UI != UIEnd; ++UI) {
8798     // Skip the uses of the chain.
8799     if (UI.getUse().getResNo() != 0)
8800       continue;
8801
8802     SDNode *User = *UI;
8803     unsigned Shift = 0;
8804
8805     // Check if this is a trunc(lshr).
8806     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8807         isa<ConstantSDNode>(User->getOperand(1))) {
8808       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8809       User = *User->use_begin();
8810     }
8811
8812     // At this point, User is a Truncate, iff we encountered, trunc or
8813     // trunc(lshr).
8814     if (User->getOpcode() != ISD::TRUNCATE)
8815       return false;
8816
8817     // The width of the type must be a power of 2 and greater than 8-bits.
8818     // Otherwise the load cannot be represented in LLVM IR.
8819     // Moreover, if we shifted with a non-8-bits multiple, the slice
8820     // will be across several bytes. We do not support that.
8821     unsigned Width = User->getValueSizeInBits(0);
8822     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8823       return 0;
8824
8825     // Build the slice for this chain of computations.
8826     LoadedSlice LS(User, LD, Shift, &DAG);
8827     APInt CurrentUsedBits = LS.getUsedBits();
8828
8829     // Check if this slice overlaps with another.
8830     if ((CurrentUsedBits & UsedBits) != 0)
8831       return false;
8832     // Update the bits used globally.
8833     UsedBits |= CurrentUsedBits;
8834
8835     // Check if the new slice would be legal.
8836     if (!LS.isLegal())
8837       return false;
8838
8839     // Record the slice.
8840     LoadedSlices.push_back(LS);
8841   }
8842
8843   // Abort slicing if it does not seem to be profitable.
8844   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8845     return false;
8846
8847   ++SlicedLoads;
8848
8849   // Rewrite each chain to use an independent load.
8850   // By construction, each chain can be represented by a unique load.
8851
8852   // Prepare the argument for the new token factor for all the slices.
8853   SmallVector<SDValue, 8> ArgChains;
8854   for (SmallVectorImpl<LoadedSlice>::const_iterator
8855            LSIt = LoadedSlices.begin(),
8856            LSItEnd = LoadedSlices.end();
8857        LSIt != LSItEnd; ++LSIt) {
8858     SDValue SliceInst = LSIt->loadSlice();
8859     CombineTo(LSIt->Inst, SliceInst, true);
8860     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8861       SliceInst = SliceInst.getOperand(0);
8862     assert(SliceInst->getOpcode() == ISD::LOAD &&
8863            "It takes more than a zext to get to the loaded slice!!");
8864     ArgChains.push_back(SliceInst.getValue(1));
8865   }
8866
8867   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8868                               ArgChains);
8869   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8870   return true;
8871 }
8872
8873 /// Check to see if V is (and load (ptr), imm), where the load is having
8874 /// specific bytes cleared out.  If so, return the byte size being masked out
8875 /// and the shift amount.
8876 static std::pair<unsigned, unsigned>
8877 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8878   std::pair<unsigned, unsigned> Result(0, 0);
8879
8880   // Check for the structure we're looking for.
8881   if (V->getOpcode() != ISD::AND ||
8882       !isa<ConstantSDNode>(V->getOperand(1)) ||
8883       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8884     return Result;
8885
8886   // Check the chain and pointer.
8887   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8888   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8889
8890   // The store should be chained directly to the load or be an operand of a
8891   // tokenfactor.
8892   if (LD == Chain.getNode())
8893     ; // ok.
8894   else if (Chain->getOpcode() != ISD::TokenFactor)
8895     return Result; // Fail.
8896   else {
8897     bool isOk = false;
8898     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8899       if (Chain->getOperand(i).getNode() == LD) {
8900         isOk = true;
8901         break;
8902       }
8903     if (!isOk) return Result;
8904   }
8905
8906   // This only handles simple types.
8907   if (V.getValueType() != MVT::i16 &&
8908       V.getValueType() != MVT::i32 &&
8909       V.getValueType() != MVT::i64)
8910     return Result;
8911
8912   // Check the constant mask.  Invert it so that the bits being masked out are
8913   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8914   // follow the sign bit for uniformity.
8915   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8916   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8917   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8918   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8919   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8920   if (NotMaskLZ == 64) return Result;  // All zero mask.
8921
8922   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8923   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8924     return Result;
8925
8926   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8927   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8928     NotMaskLZ -= 64-V.getValueSizeInBits();
8929
8930   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8931   switch (MaskedBytes) {
8932   case 1:
8933   case 2:
8934   case 4: break;
8935   default: return Result; // All one mask, or 5-byte mask.
8936   }
8937
8938   // Verify that the first bit starts at a multiple of mask so that the access
8939   // is aligned the same as the access width.
8940   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8941
8942   Result.first = MaskedBytes;
8943   Result.second = NotMaskTZ/8;
8944   return Result;
8945 }
8946
8947
8948 /// Check to see if IVal is something that provides a value as specified by
8949 /// MaskInfo. If so, replace the specified store with a narrower store of
8950 /// truncated IVal.
8951 static SDNode *
8952 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8953                                 SDValue IVal, StoreSDNode *St,
8954                                 DAGCombiner *DC) {
8955   unsigned NumBytes = MaskInfo.first;
8956   unsigned ByteShift = MaskInfo.second;
8957   SelectionDAG &DAG = DC->getDAG();
8958
8959   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8960   // that uses this.  If not, this is not a replacement.
8961   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8962                                   ByteShift*8, (ByteShift+NumBytes)*8);
8963   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8964
8965   // Check that it is legal on the target to do this.  It is legal if the new
8966   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8967   // legalization.
8968   MVT VT = MVT::getIntegerVT(NumBytes*8);
8969   if (!DC->isTypeLegal(VT))
8970     return nullptr;
8971
8972   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8973   // shifted by ByteShift and truncated down to NumBytes.
8974   if (ByteShift)
8975     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8976                        DAG.getConstant(ByteShift*8,
8977                                     DC->getShiftAmountTy(IVal.getValueType())));
8978
8979   // Figure out the offset for the store and the alignment of the access.
8980   unsigned StOffset;
8981   unsigned NewAlign = St->getAlignment();
8982
8983   if (DAG.getTargetLoweringInfo().isLittleEndian())
8984     StOffset = ByteShift;
8985   else
8986     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8987
8988   SDValue Ptr = St->getBasePtr();
8989   if (StOffset) {
8990     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8991                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8992     NewAlign = MinAlign(NewAlign, StOffset);
8993   }
8994
8995   // Truncate down to the new size.
8996   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8997
8998   ++OpsNarrowed;
8999   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9000                       St->getPointerInfo().getWithOffset(StOffset),
9001                       false, false, NewAlign).getNode();
9002 }
9003
9004
9005 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9006 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9007 /// narrowing the load and store if it would end up being a win for performance
9008 /// or code size.
9009 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9010   StoreSDNode *ST  = cast<StoreSDNode>(N);
9011   if (ST->isVolatile())
9012     return SDValue();
9013
9014   SDValue Chain = ST->getChain();
9015   SDValue Value = ST->getValue();
9016   SDValue Ptr   = ST->getBasePtr();
9017   EVT VT = Value.getValueType();
9018
9019   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9020     return SDValue();
9021
9022   unsigned Opc = Value.getOpcode();
9023
9024   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9025   // is a byte mask indicating a consecutive number of bytes, check to see if
9026   // Y is known to provide just those bytes.  If so, we try to replace the
9027   // load + replace + store sequence with a single (narrower) store, which makes
9028   // the load dead.
9029   if (Opc == ISD::OR) {
9030     std::pair<unsigned, unsigned> MaskedLoad;
9031     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9032     if (MaskedLoad.first)
9033       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9034                                                   Value.getOperand(1), ST,this))
9035         return SDValue(NewST, 0);
9036
9037     // Or is commutative, so try swapping X and Y.
9038     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9039     if (MaskedLoad.first)
9040       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9041                                                   Value.getOperand(0), ST,this))
9042         return SDValue(NewST, 0);
9043   }
9044
9045   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9046       Value.getOperand(1).getOpcode() != ISD::Constant)
9047     return SDValue();
9048
9049   SDValue N0 = Value.getOperand(0);
9050   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9051       Chain == SDValue(N0.getNode(), 1)) {
9052     LoadSDNode *LD = cast<LoadSDNode>(N0);
9053     if (LD->getBasePtr() != Ptr ||
9054         LD->getPointerInfo().getAddrSpace() !=
9055         ST->getPointerInfo().getAddrSpace())
9056       return SDValue();
9057
9058     // Find the type to narrow it the load / op / store to.
9059     SDValue N1 = Value.getOperand(1);
9060     unsigned BitWidth = N1.getValueSizeInBits();
9061     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9062     if (Opc == ISD::AND)
9063       Imm ^= APInt::getAllOnesValue(BitWidth);
9064     if (Imm == 0 || Imm.isAllOnesValue())
9065       return SDValue();
9066     unsigned ShAmt = Imm.countTrailingZeros();
9067     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9068     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9069     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9070     while (NewBW < BitWidth &&
9071            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9072              TLI.isNarrowingProfitable(VT, NewVT))) {
9073       NewBW = NextPowerOf2(NewBW);
9074       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9075     }
9076     if (NewBW >= BitWidth)
9077       return SDValue();
9078
9079     // If the lsb changed does not start at the type bitwidth boundary,
9080     // start at the previous one.
9081     if (ShAmt % NewBW)
9082       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9083     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9084                                    std::min(BitWidth, ShAmt + NewBW));
9085     if ((Imm & Mask) == Imm) {
9086       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9087       if (Opc == ISD::AND)
9088         NewImm ^= APInt::getAllOnesValue(NewBW);
9089       uint64_t PtrOff = ShAmt / 8;
9090       // For big endian targets, we need to adjust the offset to the pointer to
9091       // load the correct bytes.
9092       if (TLI.isBigEndian())
9093         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9094
9095       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9096       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9097       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9098         return SDValue();
9099
9100       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9101                                    Ptr.getValueType(), Ptr,
9102                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9103       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9104                                   LD->getChain(), NewPtr,
9105                                   LD->getPointerInfo().getWithOffset(PtrOff),
9106                                   LD->isVolatile(), LD->isNonTemporal(),
9107                                   LD->isInvariant(), NewAlign,
9108                                   LD->getAAInfo());
9109       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9110                                    DAG.getConstant(NewImm, NewVT));
9111       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9112                                    NewVal, NewPtr,
9113                                    ST->getPointerInfo().getWithOffset(PtrOff),
9114                                    false, false, NewAlign);
9115
9116       AddToWorklist(NewPtr.getNode());
9117       AddToWorklist(NewLD.getNode());
9118       AddToWorklist(NewVal.getNode());
9119       WorklistRemover DeadNodes(*this);
9120       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9121       ++OpsNarrowed;
9122       return NewST;
9123     }
9124   }
9125
9126   return SDValue();
9127 }
9128
9129 /// For a given floating point load / store pair, if the load value isn't used
9130 /// by any other operations, then consider transforming the pair to integer
9131 /// load / store operations if the target deems the transformation profitable.
9132 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9133   StoreSDNode *ST  = cast<StoreSDNode>(N);
9134   SDValue Chain = ST->getChain();
9135   SDValue Value = ST->getValue();
9136   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9137       Value.hasOneUse() &&
9138       Chain == SDValue(Value.getNode(), 1)) {
9139     LoadSDNode *LD = cast<LoadSDNode>(Value);
9140     EVT VT = LD->getMemoryVT();
9141     if (!VT.isFloatingPoint() ||
9142         VT != ST->getMemoryVT() ||
9143         LD->isNonTemporal() ||
9144         ST->isNonTemporal() ||
9145         LD->getPointerInfo().getAddrSpace() != 0 ||
9146         ST->getPointerInfo().getAddrSpace() != 0)
9147       return SDValue();
9148
9149     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9150     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9151         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9152         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9153         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9154       return SDValue();
9155
9156     unsigned LDAlign = LD->getAlignment();
9157     unsigned STAlign = ST->getAlignment();
9158     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9159     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9160     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9161       return SDValue();
9162
9163     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9164                                 LD->getChain(), LD->getBasePtr(),
9165                                 LD->getPointerInfo(),
9166                                 false, false, false, LDAlign);
9167
9168     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9169                                  NewLD, ST->getBasePtr(),
9170                                  ST->getPointerInfo(),
9171                                  false, false, STAlign);
9172
9173     AddToWorklist(NewLD.getNode());
9174     AddToWorklist(NewST.getNode());
9175     WorklistRemover DeadNodes(*this);
9176     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9177     ++LdStFP2Int;
9178     return NewST;
9179   }
9180
9181   return SDValue();
9182 }
9183
9184 /// Helper struct to parse and store a memory address as base + index + offset.
9185 /// We ignore sign extensions when it is safe to do so.
9186 /// The following two expressions are not equivalent. To differentiate we need
9187 /// to store whether there was a sign extension involved in the index
9188 /// computation.
9189 ///  (load (i64 add (i64 copyfromreg %c)
9190 ///                 (i64 signextend (add (i8 load %index)
9191 ///                                      (i8 1))))
9192 /// vs
9193 ///
9194 /// (load (i64 add (i64 copyfromreg %c)
9195 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9196 ///                                         (i32 1)))))
9197 struct BaseIndexOffset {
9198   SDValue Base;
9199   SDValue Index;
9200   int64_t Offset;
9201   bool IsIndexSignExt;
9202
9203   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9204
9205   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9206                   bool IsIndexSignExt) :
9207     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9208
9209   bool equalBaseIndex(const BaseIndexOffset &Other) {
9210     return Other.Base == Base && Other.Index == Index &&
9211       Other.IsIndexSignExt == IsIndexSignExt;
9212   }
9213
9214   /// Parses tree in Ptr for base, index, offset addresses.
9215   static BaseIndexOffset match(SDValue Ptr) {
9216     bool IsIndexSignExt = false;
9217
9218     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9219     // instruction, then it could be just the BASE or everything else we don't
9220     // know how to handle. Just use Ptr as BASE and give up.
9221     if (Ptr->getOpcode() != ISD::ADD)
9222       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9223
9224     // We know that we have at least an ADD instruction. Try to pattern match
9225     // the simple case of BASE + OFFSET.
9226     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9227       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9228       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9229                               IsIndexSignExt);
9230     }
9231
9232     // Inside a loop the current BASE pointer is calculated using an ADD and a
9233     // MUL instruction. In this case Ptr is the actual BASE pointer.
9234     // (i64 add (i64 %array_ptr)
9235     //          (i64 mul (i64 %induction_var)
9236     //                   (i64 %element_size)))
9237     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9238       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9239
9240     // Look at Base + Index + Offset cases.
9241     SDValue Base = Ptr->getOperand(0);
9242     SDValue IndexOffset = Ptr->getOperand(1);
9243
9244     // Skip signextends.
9245     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9246       IndexOffset = IndexOffset->getOperand(0);
9247       IsIndexSignExt = true;
9248     }
9249
9250     // Either the case of Base + Index (no offset) or something else.
9251     if (IndexOffset->getOpcode() != ISD::ADD)
9252       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9253
9254     // Now we have the case of Base + Index + offset.
9255     SDValue Index = IndexOffset->getOperand(0);
9256     SDValue Offset = IndexOffset->getOperand(1);
9257
9258     if (!isa<ConstantSDNode>(Offset))
9259       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9260
9261     // Ignore signextends.
9262     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9263       Index = Index->getOperand(0);
9264       IsIndexSignExt = true;
9265     } else IsIndexSignExt = false;
9266
9267     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9268     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9269   }
9270 };
9271
9272 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9273 /// is located in a sequence of memory operations connected by a chain.
9274 struct MemOpLink {
9275   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9276     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9277   // Ptr to the mem node.
9278   LSBaseSDNode *MemNode;
9279   // Offset from the base ptr.
9280   int64_t OffsetFromBase;
9281   // What is the sequence number of this mem node.
9282   // Lowest mem operand in the DAG starts at zero.
9283   unsigned SequenceNum;
9284 };
9285
9286 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9287   EVT MemVT = St->getMemoryVT();
9288   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9289   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9290     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9291
9292   // Don't merge vectors into wider inputs.
9293   if (MemVT.isVector() || !MemVT.isSimple())
9294     return false;
9295
9296   // Perform an early exit check. Do not bother looking at stored values that
9297   // are not constants or loads.
9298   SDValue StoredVal = St->getValue();
9299   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9300   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9301       !IsLoadSrc)
9302     return false;
9303
9304   // Only look at ends of store sequences.
9305   SDValue Chain = SDValue(St, 0);
9306   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9307     return false;
9308
9309   // This holds the base pointer, index, and the offset in bytes from the base
9310   // pointer.
9311   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9312
9313   // We must have a base and an offset.
9314   if (!BasePtr.Base.getNode())
9315     return false;
9316
9317   // Do not handle stores to undef base pointers.
9318   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9319     return false;
9320
9321   // Save the LoadSDNodes that we find in the chain.
9322   // We need to make sure that these nodes do not interfere with
9323   // any of the store nodes.
9324   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9325
9326   // Save the StoreSDNodes that we find in the chain.
9327   SmallVector<MemOpLink, 8> StoreNodes;
9328
9329   // Walk up the chain and look for nodes with offsets from the same
9330   // base pointer. Stop when reaching an instruction with a different kind
9331   // or instruction which has a different base pointer.
9332   unsigned Seq = 0;
9333   StoreSDNode *Index = St;
9334   while (Index) {
9335     // If the chain has more than one use, then we can't reorder the mem ops.
9336     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9337       break;
9338
9339     // Find the base pointer and offset for this memory node.
9340     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9341
9342     // Check that the base pointer is the same as the original one.
9343     if (!Ptr.equalBaseIndex(BasePtr))
9344       break;
9345
9346     // Check that the alignment is the same.
9347     if (Index->getAlignment() != St->getAlignment())
9348       break;
9349
9350     // The memory operands must not be volatile.
9351     if (Index->isVolatile() || Index->isIndexed())
9352       break;
9353
9354     // No truncation.
9355     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9356       if (St->isTruncatingStore())
9357         break;
9358
9359     // The stored memory type must be the same.
9360     if (Index->getMemoryVT() != MemVT)
9361       break;
9362
9363     // We do not allow unaligned stores because we want to prevent overriding
9364     // stores.
9365     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9366       break;
9367
9368     // We found a potential memory operand to merge.
9369     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9370
9371     // Find the next memory operand in the chain. If the next operand in the
9372     // chain is a store then move up and continue the scan with the next
9373     // memory operand. If the next operand is a load save it and use alias
9374     // information to check if it interferes with anything.
9375     SDNode *NextInChain = Index->getChain().getNode();
9376     while (1) {
9377       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9378         // We found a store node. Use it for the next iteration.
9379         Index = STn;
9380         break;
9381       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9382         if (Ldn->isVolatile()) {
9383           Index = nullptr;
9384           break;
9385         }
9386
9387         // Save the load node for later. Continue the scan.
9388         AliasLoadNodes.push_back(Ldn);
9389         NextInChain = Ldn->getChain().getNode();
9390         continue;
9391       } else {
9392         Index = nullptr;
9393         break;
9394       }
9395     }
9396   }
9397
9398   // Check if there is anything to merge.
9399   if (StoreNodes.size() < 2)
9400     return false;
9401
9402   // Sort the memory operands according to their distance from the base pointer.
9403   std::sort(StoreNodes.begin(), StoreNodes.end(),
9404             [](MemOpLink LHS, MemOpLink RHS) {
9405     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9406            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9407             LHS.SequenceNum > RHS.SequenceNum);
9408   });
9409
9410   // Scan the memory operations on the chain and find the first non-consecutive
9411   // store memory address.
9412   unsigned LastConsecutiveStore = 0;
9413   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9414   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9415
9416     // Check that the addresses are consecutive starting from the second
9417     // element in the list of stores.
9418     if (i > 0) {
9419       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9420       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9421         break;
9422     }
9423
9424     bool Alias = false;
9425     // Check if this store interferes with any of the loads that we found.
9426     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9427       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9428         Alias = true;
9429         break;
9430       }
9431     // We found a load that alias with this store. Stop the sequence.
9432     if (Alias)
9433       break;
9434
9435     // Mark this node as useful.
9436     LastConsecutiveStore = i;
9437   }
9438
9439   // The node with the lowest store address.
9440   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9441
9442   // Store the constants into memory as one consecutive store.
9443   if (!IsLoadSrc) {
9444     unsigned LastLegalType = 0;
9445     unsigned LastLegalVectorType = 0;
9446     bool NonZero = false;
9447     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9448       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9449       SDValue StoredVal = St->getValue();
9450
9451       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9452         NonZero |= !C->isNullValue();
9453       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9454         NonZero |= !C->getConstantFPValue()->isNullValue();
9455       } else {
9456         // Non-constant.
9457         break;
9458       }
9459
9460       // Find a legal type for the constant store.
9461       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9462       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9463       if (TLI.isTypeLegal(StoreTy))
9464         LastLegalType = i+1;
9465       // Or check whether a truncstore is legal.
9466       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9467                TargetLowering::TypePromoteInteger) {
9468         EVT LegalizedStoredValueTy =
9469           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9470         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9471           LastLegalType = i+1;
9472       }
9473
9474       // Find a legal type for the vector store.
9475       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9476       if (TLI.isTypeLegal(Ty))
9477         LastLegalVectorType = i + 1;
9478     }
9479
9480     // We only use vectors if the constant is known to be zero and the
9481     // function is not marked with the noimplicitfloat attribute.
9482     if (NonZero || NoVectors)
9483       LastLegalVectorType = 0;
9484
9485     // Check if we found a legal integer type to store.
9486     if (LastLegalType == 0 && LastLegalVectorType == 0)
9487       return false;
9488
9489     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9490     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9491
9492     // Make sure we have something to merge.
9493     if (NumElem < 2)
9494       return false;
9495
9496     unsigned EarliestNodeUsed = 0;
9497     for (unsigned i=0; i < NumElem; ++i) {
9498       // Find a chain for the new wide-store operand. Notice that some
9499       // of the store nodes that we found may not be selected for inclusion
9500       // in the wide store. The chain we use needs to be the chain of the
9501       // earliest store node which is *used* and replaced by the wide store.
9502       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9503         EarliestNodeUsed = i;
9504     }
9505
9506     // The earliest Node in the DAG.
9507     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9508     SDLoc DL(StoreNodes[0].MemNode);
9509
9510     SDValue StoredVal;
9511     if (UseVector) {
9512       // Find a legal type for the vector store.
9513       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9514       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9515       StoredVal = DAG.getConstant(0, Ty);
9516     } else {
9517       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9518       APInt StoreInt(StoreBW, 0);
9519
9520       // Construct a single integer constant which is made of the smaller
9521       // constant inputs.
9522       bool IsLE = TLI.isLittleEndian();
9523       for (unsigned i = 0; i < NumElem ; ++i) {
9524         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9525         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9526         SDValue Val = St->getValue();
9527         StoreInt<<=ElementSizeBytes*8;
9528         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9529           StoreInt|=C->getAPIntValue().zext(StoreBW);
9530         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9531           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9532         } else {
9533           assert(false && "Invalid constant element type");
9534         }
9535       }
9536
9537       // Create the new Load and Store operations.
9538       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9539       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9540     }
9541
9542     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9543                                     FirstInChain->getBasePtr(),
9544                                     FirstInChain->getPointerInfo(),
9545                                     false, false,
9546                                     FirstInChain->getAlignment());
9547
9548     // Replace the first store with the new store
9549     CombineTo(EarliestOp, NewStore);
9550     // Erase all other stores.
9551     for (unsigned i = 0; i < NumElem ; ++i) {
9552       if (StoreNodes[i].MemNode == EarliestOp)
9553         continue;
9554       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9555       // ReplaceAllUsesWith will replace all uses that existed when it was
9556       // called, but graph optimizations may cause new ones to appear. For
9557       // example, the case in pr14333 looks like
9558       //
9559       //  St's chain -> St -> another store -> X
9560       //
9561       // And the only difference from St to the other store is the chain.
9562       // When we change it's chain to be St's chain they become identical,
9563       // get CSEed and the net result is that X is now a use of St.
9564       // Since we know that St is redundant, just iterate.
9565       while (!St->use_empty())
9566         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9567       deleteAndRecombine(St);
9568     }
9569
9570     return true;
9571   }
9572
9573   // Below we handle the case of multiple consecutive stores that
9574   // come from multiple consecutive loads. We merge them into a single
9575   // wide load and a single wide store.
9576
9577   // Look for load nodes which are used by the stored values.
9578   SmallVector<MemOpLink, 8> LoadNodes;
9579
9580   // Find acceptable loads. Loads need to have the same chain (token factor),
9581   // must not be zext, volatile, indexed, and they must be consecutive.
9582   BaseIndexOffset LdBasePtr;
9583   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9584     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9585     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9586     if (!Ld) break;
9587
9588     // Loads must only have one use.
9589     if (!Ld->hasNUsesOfValue(1, 0))
9590       break;
9591
9592     // Check that the alignment is the same as the stores.
9593     if (Ld->getAlignment() != St->getAlignment())
9594       break;
9595
9596     // The memory operands must not be volatile.
9597     if (Ld->isVolatile() || Ld->isIndexed())
9598       break;
9599
9600     // We do not accept ext loads.
9601     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9602       break;
9603
9604     // The stored memory type must be the same.
9605     if (Ld->getMemoryVT() != MemVT)
9606       break;
9607
9608     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9609     // If this is not the first ptr that we check.
9610     if (LdBasePtr.Base.getNode()) {
9611       // The base ptr must be the same.
9612       if (!LdPtr.equalBaseIndex(LdBasePtr))
9613         break;
9614     } else {
9615       // Check that all other base pointers are the same as this one.
9616       LdBasePtr = LdPtr;
9617     }
9618
9619     // We found a potential memory operand to merge.
9620     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9621   }
9622
9623   if (LoadNodes.size() < 2)
9624     return false;
9625
9626   // If we have load/store pair instructions and we only have two values,
9627   // don't bother.
9628   unsigned RequiredAlignment;
9629   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9630       St->getAlignment() >= RequiredAlignment)
9631     return false;
9632
9633   // Scan the memory operations on the chain and find the first non-consecutive
9634   // load memory address. These variables hold the index in the store node
9635   // array.
9636   unsigned LastConsecutiveLoad = 0;
9637   // This variable refers to the size and not index in the array.
9638   unsigned LastLegalVectorType = 0;
9639   unsigned LastLegalIntegerType = 0;
9640   StartAddress = LoadNodes[0].OffsetFromBase;
9641   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9642   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9643     // All loads much share the same chain.
9644     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9645       break;
9646
9647     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9648     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9649       break;
9650     LastConsecutiveLoad = i;
9651
9652     // Find a legal type for the vector store.
9653     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9654     if (TLI.isTypeLegal(StoreTy))
9655       LastLegalVectorType = i + 1;
9656
9657     // Find a legal type for the integer store.
9658     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9659     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9660     if (TLI.isTypeLegal(StoreTy))
9661       LastLegalIntegerType = i + 1;
9662     // Or check whether a truncstore and extload is legal.
9663     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9664              TargetLowering::TypePromoteInteger) {
9665       EVT LegalizedStoredValueTy =
9666         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9667       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9668           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9669           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9670           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9671         LastLegalIntegerType = i+1;
9672     }
9673   }
9674
9675   // Only use vector types if the vector type is larger than the integer type.
9676   // If they are the same, use integers.
9677   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9678   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9679
9680   // We add +1 here because the LastXXX variables refer to location while
9681   // the NumElem refers to array/index size.
9682   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9683   NumElem = std::min(LastLegalType, NumElem);
9684
9685   if (NumElem < 2)
9686     return false;
9687
9688   // The earliest Node in the DAG.
9689   unsigned EarliestNodeUsed = 0;
9690   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9691   for (unsigned i=1; i<NumElem; ++i) {
9692     // Find a chain for the new wide-store operand. Notice that some
9693     // of the store nodes that we found may not be selected for inclusion
9694     // in the wide store. The chain we use needs to be the chain of the
9695     // earliest store node which is *used* and replaced by the wide store.
9696     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9697       EarliestNodeUsed = i;
9698   }
9699
9700   // Find if it is better to use vectors or integers to load and store
9701   // to memory.
9702   EVT JointMemOpVT;
9703   if (UseVectorTy) {
9704     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9705   } else {
9706     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9707     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9708   }
9709
9710   SDLoc LoadDL(LoadNodes[0].MemNode);
9711   SDLoc StoreDL(StoreNodes[0].MemNode);
9712
9713   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9714   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9715                                 FirstLoad->getChain(),
9716                                 FirstLoad->getBasePtr(),
9717                                 FirstLoad->getPointerInfo(),
9718                                 false, false, false,
9719                                 FirstLoad->getAlignment());
9720
9721   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9722                                   FirstInChain->getBasePtr(),
9723                                   FirstInChain->getPointerInfo(), false, false,
9724                                   FirstInChain->getAlignment());
9725
9726   // Replace one of the loads with the new load.
9727   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9728   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9729                                 SDValue(NewLoad.getNode(), 1));
9730
9731   // Remove the rest of the load chains.
9732   for (unsigned i = 1; i < NumElem ; ++i) {
9733     // Replace all chain users of the old load nodes with the chain of the new
9734     // load node.
9735     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9736     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9737   }
9738
9739   // Replace the first store with the new store.
9740   CombineTo(EarliestOp, NewStore);
9741   // Erase all other stores.
9742   for (unsigned i = 0; i < NumElem ; ++i) {
9743     // Remove all Store nodes.
9744     if (StoreNodes[i].MemNode == EarliestOp)
9745       continue;
9746     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9747     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9748     deleteAndRecombine(St);
9749   }
9750
9751   return true;
9752 }
9753
9754 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9755   StoreSDNode *ST  = cast<StoreSDNode>(N);
9756   SDValue Chain = ST->getChain();
9757   SDValue Value = ST->getValue();
9758   SDValue Ptr   = ST->getBasePtr();
9759
9760   // If this is a store of a bit convert, store the input value if the
9761   // resultant store does not need a higher alignment than the original.
9762   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9763       ST->isUnindexed()) {
9764     unsigned OrigAlign = ST->getAlignment();
9765     EVT SVT = Value.getOperand(0).getValueType();
9766     unsigned Align = TLI.getDataLayout()->
9767       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9768     if (Align <= OrigAlign &&
9769         ((!LegalOperations && !ST->isVolatile()) ||
9770          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9771       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9772                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9773                           ST->isNonTemporal(), OrigAlign,
9774                           ST->getAAInfo());
9775   }
9776
9777   // Turn 'store undef, Ptr' -> nothing.
9778   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9779     return Chain;
9780
9781   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9782   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9783     // NOTE: If the original store is volatile, this transform must not increase
9784     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9785     // processor operation but an i64 (which is not legal) requires two.  So the
9786     // transform should not be done in this case.
9787     if (Value.getOpcode() != ISD::TargetConstantFP) {
9788       SDValue Tmp;
9789       switch (CFP->getSimpleValueType(0).SimpleTy) {
9790       default: llvm_unreachable("Unknown FP type");
9791       case MVT::f16:    // We don't do this for these yet.
9792       case MVT::f80:
9793       case MVT::f128:
9794       case MVT::ppcf128:
9795         break;
9796       case MVT::f32:
9797         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9798             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9799           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9800                               bitcastToAPInt().getZExtValue(), MVT::i32);
9801           return DAG.getStore(Chain, SDLoc(N), Tmp,
9802                               Ptr, ST->getMemOperand());
9803         }
9804         break;
9805       case MVT::f64:
9806         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9807              !ST->isVolatile()) ||
9808             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9809           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9810                                 getZExtValue(), MVT::i64);
9811           return DAG.getStore(Chain, SDLoc(N), Tmp,
9812                               Ptr, ST->getMemOperand());
9813         }
9814
9815         if (!ST->isVolatile() &&
9816             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9817           // Many FP stores are not made apparent until after legalize, e.g. for
9818           // argument passing.  Since this is so common, custom legalize the
9819           // 64-bit integer store into two 32-bit stores.
9820           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9821           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9822           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9823           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9824
9825           unsigned Alignment = ST->getAlignment();
9826           bool isVolatile = ST->isVolatile();
9827           bool isNonTemporal = ST->isNonTemporal();
9828           AAMDNodes AAInfo = ST->getAAInfo();
9829
9830           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9831                                      Ptr, ST->getPointerInfo(),
9832                                      isVolatile, isNonTemporal,
9833                                      ST->getAlignment(), AAInfo);
9834           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9835                             DAG.getConstant(4, Ptr.getValueType()));
9836           Alignment = MinAlign(Alignment, 4U);
9837           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9838                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9839                                      isVolatile, isNonTemporal,
9840                                      Alignment, AAInfo);
9841           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9842                              St0, St1);
9843         }
9844
9845         break;
9846       }
9847     }
9848   }
9849
9850   // Try to infer better alignment information than the store already has.
9851   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9852     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9853       if (Align > ST->getAlignment())
9854         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9855                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9856                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9857                                  ST->getAAInfo());
9858     }
9859   }
9860
9861   // Try transforming a pair floating point load / store ops to integer
9862   // load / store ops.
9863   SDValue NewST = TransformFPLoadStorePair(N);
9864   if (NewST.getNode())
9865     return NewST;
9866
9867   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9868                                                   : DAG.getSubtarget().useAA();
9869 #ifndef NDEBUG
9870   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9871       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9872     UseAA = false;
9873 #endif
9874   if (UseAA && ST->isUnindexed()) {
9875     // Walk up chain skipping non-aliasing memory nodes.
9876     SDValue BetterChain = FindBetterChain(N, Chain);
9877
9878     // If there is a better chain.
9879     if (Chain != BetterChain) {
9880       SDValue ReplStore;
9881
9882       // Replace the chain to avoid dependency.
9883       if (ST->isTruncatingStore()) {
9884         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9885                                       ST->getMemoryVT(), ST->getMemOperand());
9886       } else {
9887         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9888                                  ST->getMemOperand());
9889       }
9890
9891       // Create token to keep both nodes around.
9892       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9893                                   MVT::Other, Chain, ReplStore);
9894
9895       // Make sure the new and old chains are cleaned up.
9896       AddToWorklist(Token.getNode());
9897
9898       // Don't add users to work list.
9899       return CombineTo(N, Token, false);
9900     }
9901   }
9902
9903   // Try transforming N to an indexed store.
9904   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9905     return SDValue(N, 0);
9906
9907   // FIXME: is there such a thing as a truncating indexed store?
9908   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9909       Value.getValueType().isInteger()) {
9910     // See if we can simplify the input to this truncstore with knowledge that
9911     // only the low bits are being used.  For example:
9912     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9913     SDValue Shorter =
9914       GetDemandedBits(Value,
9915                       APInt::getLowBitsSet(
9916                         Value.getValueType().getScalarType().getSizeInBits(),
9917                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9918     AddToWorklist(Value.getNode());
9919     if (Shorter.getNode())
9920       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9921                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9922
9923     // Otherwise, see if we can simplify the operation with
9924     // SimplifyDemandedBits, which only works if the value has a single use.
9925     if (SimplifyDemandedBits(Value,
9926                         APInt::getLowBitsSet(
9927                           Value.getValueType().getScalarType().getSizeInBits(),
9928                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9929       return SDValue(N, 0);
9930   }
9931
9932   // If this is a load followed by a store to the same location, then the store
9933   // is dead/noop.
9934   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9935     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9936         ST->isUnindexed() && !ST->isVolatile() &&
9937         // There can't be any side effects between the load and store, such as
9938         // a call or store.
9939         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9940       // The store is dead, remove it.
9941       return Chain;
9942     }
9943   }
9944
9945   // If this is a store followed by a store with the same value to the same
9946   // location, then the store is dead/noop.
9947   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9948     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9949         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9950         ST1->isUnindexed() && !ST1->isVolatile()) {
9951       // The store is dead, remove it.
9952       return Chain;
9953     }
9954   }
9955
9956   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9957   // truncating store.  We can do this even if this is already a truncstore.
9958   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9959       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9960       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9961                             ST->getMemoryVT())) {
9962     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9963                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9964   }
9965
9966   // Only perform this optimization before the types are legal, because we
9967   // don't want to perform this optimization on every DAGCombine invocation.
9968   if (!LegalTypes) {
9969     bool EverChanged = false;
9970
9971     do {
9972       // There can be multiple store sequences on the same chain.
9973       // Keep trying to merge store sequences until we are unable to do so
9974       // or until we merge the last store on the chain.
9975       bool Changed = MergeConsecutiveStores(ST);
9976       EverChanged |= Changed;
9977       if (!Changed) break;
9978     } while (ST->getOpcode() != ISD::DELETED_NODE);
9979
9980     if (EverChanged)
9981       return SDValue(N, 0);
9982   }
9983
9984   return ReduceLoadOpStoreWidth(N);
9985 }
9986
9987 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9988   SDValue InVec = N->getOperand(0);
9989   SDValue InVal = N->getOperand(1);
9990   SDValue EltNo = N->getOperand(2);
9991   SDLoc dl(N);
9992
9993   // If the inserted element is an UNDEF, just use the input vector.
9994   if (InVal.getOpcode() == ISD::UNDEF)
9995     return InVec;
9996
9997   EVT VT = InVec.getValueType();
9998
9999   // If we can't generate a legal BUILD_VECTOR, exit
10000   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10001     return SDValue();
10002
10003   // Check that we know which element is being inserted
10004   if (!isa<ConstantSDNode>(EltNo))
10005     return SDValue();
10006   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10007
10008   // Canonicalize insert_vector_elt dag nodes.
10009   // Example:
10010   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10011   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10012   //
10013   // Do this only if the child insert_vector node has one use; also
10014   // do this only if indices are both constants and Idx1 < Idx0.
10015   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10016       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10017     unsigned OtherElt =
10018       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10019     if (Elt < OtherElt) {
10020       // Swap nodes.
10021       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10022                                   InVec.getOperand(0), InVal, EltNo);
10023       AddToWorklist(NewOp.getNode());
10024       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10025                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10026     }
10027   }
10028
10029   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10030   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10031   // vector elements.
10032   SmallVector<SDValue, 8> Ops;
10033   // Do not combine these two vectors if the output vector will not replace
10034   // the input vector.
10035   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10036     Ops.append(InVec.getNode()->op_begin(),
10037                InVec.getNode()->op_end());
10038   } else if (InVec.getOpcode() == ISD::UNDEF) {
10039     unsigned NElts = VT.getVectorNumElements();
10040     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10041   } else {
10042     return SDValue();
10043   }
10044
10045   // Insert the element
10046   if (Elt < Ops.size()) {
10047     // All the operands of BUILD_VECTOR must have the same type;
10048     // we enforce that here.
10049     EVT OpVT = Ops[0].getValueType();
10050     if (InVal.getValueType() != OpVT)
10051       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10052                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10053                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10054     Ops[Elt] = InVal;
10055   }
10056
10057   // Return the new vector
10058   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10059 }
10060
10061 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10062     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10063   EVT ResultVT = EVE->getValueType(0);
10064   EVT VecEltVT = InVecVT.getVectorElementType();
10065   unsigned Align = OriginalLoad->getAlignment();
10066   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10067       VecEltVT.getTypeForEVT(*DAG.getContext()));
10068
10069   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10070     return SDValue();
10071
10072   Align = NewAlign;
10073
10074   SDValue NewPtr = OriginalLoad->getBasePtr();
10075   SDValue Offset;
10076   EVT PtrType = NewPtr.getValueType();
10077   MachinePointerInfo MPI;
10078   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10079     int Elt = ConstEltNo->getZExtValue();
10080     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10081     if (TLI.isBigEndian())
10082       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10083     Offset = DAG.getConstant(PtrOff, PtrType);
10084     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10085   } else {
10086     Offset = DAG.getNode(
10087         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10088         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10089     if (TLI.isBigEndian())
10090       Offset = DAG.getNode(
10091           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10092           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10093     MPI = OriginalLoad->getPointerInfo();
10094   }
10095   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10096
10097   // The replacement we need to do here is a little tricky: we need to
10098   // replace an extractelement of a load with a load.
10099   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10100   // Note that this replacement assumes that the extractvalue is the only
10101   // use of the load; that's okay because we don't want to perform this
10102   // transformation in other cases anyway.
10103   SDValue Load;
10104   SDValue Chain;
10105   if (ResultVT.bitsGT(VecEltVT)) {
10106     // If the result type of vextract is wider than the load, then issue an
10107     // extending load instead.
10108     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10109                                    ? ISD::ZEXTLOAD
10110                                    : ISD::EXTLOAD;
10111     Load = DAG.getExtLoad(
10112         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10113         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10114         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10115     Chain = Load.getValue(1);
10116   } else {
10117     Load = DAG.getLoad(
10118         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10119         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10120         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10121     Chain = Load.getValue(1);
10122     if (ResultVT.bitsLT(VecEltVT))
10123       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10124     else
10125       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10126   }
10127   WorklistRemover DeadNodes(*this);
10128   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10129   SDValue To[] = { Load, Chain };
10130   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10131   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10132   // worklist explicitly as well.
10133   AddToWorklist(Load.getNode());
10134   AddUsersToWorklist(Load.getNode()); // Add users too
10135   // Make sure to revisit this node to clean it up; it will usually be dead.
10136   AddToWorklist(EVE);
10137   ++OpsNarrowed;
10138   return SDValue(EVE, 0);
10139 }
10140
10141 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10142   // (vextract (scalar_to_vector val, 0) -> val
10143   SDValue InVec = N->getOperand(0);
10144   EVT VT = InVec.getValueType();
10145   EVT NVT = N->getValueType(0);
10146
10147   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10148     // Check if the result type doesn't match the inserted element type. A
10149     // SCALAR_TO_VECTOR may truncate the inserted element and the
10150     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10151     SDValue InOp = InVec.getOperand(0);
10152     if (InOp.getValueType() != NVT) {
10153       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10154       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10155     }
10156     return InOp;
10157   }
10158
10159   SDValue EltNo = N->getOperand(1);
10160   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10161
10162   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10163   // We only perform this optimization before the op legalization phase because
10164   // we may introduce new vector instructions which are not backed by TD
10165   // patterns. For example on AVX, extracting elements from a wide vector
10166   // without using extract_subvector. However, if we can find an underlying
10167   // scalar value, then we can always use that.
10168   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10169       && ConstEltNo) {
10170     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10171     int NumElem = VT.getVectorNumElements();
10172     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10173     // Find the new index to extract from.
10174     int OrigElt = SVOp->getMaskElt(Elt);
10175
10176     // Extracting an undef index is undef.
10177     if (OrigElt == -1)
10178       return DAG.getUNDEF(NVT);
10179
10180     // Select the right vector half to extract from.
10181     SDValue SVInVec;
10182     if (OrigElt < NumElem) {
10183       SVInVec = InVec->getOperand(0);
10184     } else {
10185       SVInVec = InVec->getOperand(1);
10186       OrigElt -= NumElem;
10187     }
10188
10189     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10190       SDValue InOp = SVInVec.getOperand(OrigElt);
10191       if (InOp.getValueType() != NVT) {
10192         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10193         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10194       }
10195
10196       return InOp;
10197     }
10198
10199     // FIXME: We should handle recursing on other vector shuffles and
10200     // scalar_to_vector here as well.
10201
10202     if (!LegalOperations) {
10203       EVT IndexTy = TLI.getVectorIdxTy();
10204       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10205                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10206     }
10207   }
10208
10209   bool BCNumEltsChanged = false;
10210   EVT ExtVT = VT.getVectorElementType();
10211   EVT LVT = ExtVT;
10212
10213   // If the result of load has to be truncated, then it's not necessarily
10214   // profitable.
10215   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10216     return SDValue();
10217
10218   if (InVec.getOpcode() == ISD::BITCAST) {
10219     // Don't duplicate a load with other uses.
10220     if (!InVec.hasOneUse())
10221       return SDValue();
10222
10223     EVT BCVT = InVec.getOperand(0).getValueType();
10224     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10225       return SDValue();
10226     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10227       BCNumEltsChanged = true;
10228     InVec = InVec.getOperand(0);
10229     ExtVT = BCVT.getVectorElementType();
10230   }
10231
10232   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10233   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10234       ISD::isNormalLoad(InVec.getNode()) &&
10235       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10236     SDValue Index = N->getOperand(1);
10237     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10238       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10239                                                            OrigLoad);
10240   }
10241
10242   // Perform only after legalization to ensure build_vector / vector_shuffle
10243   // optimizations have already been done.
10244   if (!LegalOperations) return SDValue();
10245
10246   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10247   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10248   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10249
10250   if (ConstEltNo) {
10251     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10252
10253     LoadSDNode *LN0 = nullptr;
10254     const ShuffleVectorSDNode *SVN = nullptr;
10255     if (ISD::isNormalLoad(InVec.getNode())) {
10256       LN0 = cast<LoadSDNode>(InVec);
10257     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10258                InVec.getOperand(0).getValueType() == ExtVT &&
10259                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10260       // Don't duplicate a load with other uses.
10261       if (!InVec.hasOneUse())
10262         return SDValue();
10263
10264       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10265     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10266       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10267       // =>
10268       // (load $addr+1*size)
10269
10270       // Don't duplicate a load with other uses.
10271       if (!InVec.hasOneUse())
10272         return SDValue();
10273
10274       // If the bit convert changed the number of elements, it is unsafe
10275       // to examine the mask.
10276       if (BCNumEltsChanged)
10277         return SDValue();
10278
10279       // Select the input vector, guarding against out of range extract vector.
10280       unsigned NumElems = VT.getVectorNumElements();
10281       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10282       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10283
10284       if (InVec.getOpcode() == ISD::BITCAST) {
10285         // Don't duplicate a load with other uses.
10286         if (!InVec.hasOneUse())
10287           return SDValue();
10288
10289         InVec = InVec.getOperand(0);
10290       }
10291       if (ISD::isNormalLoad(InVec.getNode())) {
10292         LN0 = cast<LoadSDNode>(InVec);
10293         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10294         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10295       }
10296     }
10297
10298     // Make sure we found a non-volatile load and the extractelement is
10299     // the only use.
10300     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10301       return SDValue();
10302
10303     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10304     if (Elt == -1)
10305       return DAG.getUNDEF(LVT);
10306
10307     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10308   }
10309
10310   return SDValue();
10311 }
10312
10313 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10314 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10315   // We perform this optimization post type-legalization because
10316   // the type-legalizer often scalarizes integer-promoted vectors.
10317   // Performing this optimization before may create bit-casts which
10318   // will be type-legalized to complex code sequences.
10319   // We perform this optimization only before the operation legalizer because we
10320   // may introduce illegal operations.
10321   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10322     return SDValue();
10323
10324   unsigned NumInScalars = N->getNumOperands();
10325   SDLoc dl(N);
10326   EVT VT = N->getValueType(0);
10327
10328   // Check to see if this is a BUILD_VECTOR of a bunch of values
10329   // which come from any_extend or zero_extend nodes. If so, we can create
10330   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10331   // optimizations. We do not handle sign-extend because we can't fill the sign
10332   // using shuffles.
10333   EVT SourceType = MVT::Other;
10334   bool AllAnyExt = true;
10335
10336   for (unsigned i = 0; i != NumInScalars; ++i) {
10337     SDValue In = N->getOperand(i);
10338     // Ignore undef inputs.
10339     if (In.getOpcode() == ISD::UNDEF) continue;
10340
10341     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10342     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10343
10344     // Abort if the element is not an extension.
10345     if (!ZeroExt && !AnyExt) {
10346       SourceType = MVT::Other;
10347       break;
10348     }
10349
10350     // The input is a ZeroExt or AnyExt. Check the original type.
10351     EVT InTy = In.getOperand(0).getValueType();
10352
10353     // Check that all of the widened source types are the same.
10354     if (SourceType == MVT::Other)
10355       // First time.
10356       SourceType = InTy;
10357     else if (InTy != SourceType) {
10358       // Multiple income types. Abort.
10359       SourceType = MVT::Other;
10360       break;
10361     }
10362
10363     // Check if all of the extends are ANY_EXTENDs.
10364     AllAnyExt &= AnyExt;
10365   }
10366
10367   // In order to have valid types, all of the inputs must be extended from the
10368   // same source type and all of the inputs must be any or zero extend.
10369   // Scalar sizes must be a power of two.
10370   EVT OutScalarTy = VT.getScalarType();
10371   bool ValidTypes = SourceType != MVT::Other &&
10372                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10373                  isPowerOf2_32(SourceType.getSizeInBits());
10374
10375   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10376   // turn into a single shuffle instruction.
10377   if (!ValidTypes)
10378     return SDValue();
10379
10380   bool isLE = TLI.isLittleEndian();
10381   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10382   assert(ElemRatio > 1 && "Invalid element size ratio");
10383   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10384                                DAG.getConstant(0, SourceType);
10385
10386   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10387   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10388
10389   // Populate the new build_vector
10390   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10391     SDValue Cast = N->getOperand(i);
10392     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10393             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10394             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10395     SDValue In;
10396     if (Cast.getOpcode() == ISD::UNDEF)
10397       In = DAG.getUNDEF(SourceType);
10398     else
10399       In = Cast->getOperand(0);
10400     unsigned Index = isLE ? (i * ElemRatio) :
10401                             (i * ElemRatio + (ElemRatio - 1));
10402
10403     assert(Index < Ops.size() && "Invalid index");
10404     Ops[Index] = In;
10405   }
10406
10407   // The type of the new BUILD_VECTOR node.
10408   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10409   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10410          "Invalid vector size");
10411   // Check if the new vector type is legal.
10412   if (!isTypeLegal(VecVT)) return SDValue();
10413
10414   // Make the new BUILD_VECTOR.
10415   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10416
10417   // The new BUILD_VECTOR node has the potential to be further optimized.
10418   AddToWorklist(BV.getNode());
10419   // Bitcast to the desired type.
10420   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10421 }
10422
10423 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10424   EVT VT = N->getValueType(0);
10425
10426   unsigned NumInScalars = N->getNumOperands();
10427   SDLoc dl(N);
10428
10429   EVT SrcVT = MVT::Other;
10430   unsigned Opcode = ISD::DELETED_NODE;
10431   unsigned NumDefs = 0;
10432
10433   for (unsigned i = 0; i != NumInScalars; ++i) {
10434     SDValue In = N->getOperand(i);
10435     unsigned Opc = In.getOpcode();
10436
10437     if (Opc == ISD::UNDEF)
10438       continue;
10439
10440     // If all scalar values are floats and converted from integers.
10441     if (Opcode == ISD::DELETED_NODE &&
10442         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10443       Opcode = Opc;
10444     }
10445
10446     if (Opc != Opcode)
10447       return SDValue();
10448
10449     EVT InVT = In.getOperand(0).getValueType();
10450
10451     // If all scalar values are typed differently, bail out. It's chosen to
10452     // simplify BUILD_VECTOR of integer types.
10453     if (SrcVT == MVT::Other)
10454       SrcVT = InVT;
10455     if (SrcVT != InVT)
10456       return SDValue();
10457     NumDefs++;
10458   }
10459
10460   // If the vector has just one element defined, it's not worth to fold it into
10461   // a vectorized one.
10462   if (NumDefs < 2)
10463     return SDValue();
10464
10465   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10466          && "Should only handle conversion from integer to float.");
10467   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10468
10469   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10470
10471   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10472     return SDValue();
10473
10474   SmallVector<SDValue, 8> Opnds;
10475   for (unsigned i = 0; i != NumInScalars; ++i) {
10476     SDValue In = N->getOperand(i);
10477
10478     if (In.getOpcode() == ISD::UNDEF)
10479       Opnds.push_back(DAG.getUNDEF(SrcVT));
10480     else
10481       Opnds.push_back(In.getOperand(0));
10482   }
10483   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10484   AddToWorklist(BV.getNode());
10485
10486   return DAG.getNode(Opcode, dl, VT, BV);
10487 }
10488
10489 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10490   unsigned NumInScalars = N->getNumOperands();
10491   SDLoc dl(N);
10492   EVT VT = N->getValueType(0);
10493
10494   // A vector built entirely of undefs is undef.
10495   if (ISD::allOperandsUndef(N))
10496     return DAG.getUNDEF(VT);
10497
10498   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10499   if (V.getNode())
10500     return V;
10501
10502   V = reduceBuildVecConvertToConvertBuildVec(N);
10503   if (V.getNode())
10504     return V;
10505
10506   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10507   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10508   // at most two distinct vectors, turn this into a shuffle node.
10509
10510   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10511   if (!isTypeLegal(VT))
10512     return SDValue();
10513
10514   // May only combine to shuffle after legalize if shuffle is legal.
10515   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10516     return SDValue();
10517
10518   SDValue VecIn1, VecIn2;
10519   for (unsigned i = 0; i != NumInScalars; ++i) {
10520     // Ignore undef inputs.
10521     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10522
10523     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10524     // constant index, bail out.
10525     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10526         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10527       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10528       break;
10529     }
10530
10531     // We allow up to two distinct input vectors.
10532     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10533     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10534       continue;
10535
10536     if (!VecIn1.getNode()) {
10537       VecIn1 = ExtractedFromVec;
10538     } else if (!VecIn2.getNode()) {
10539       VecIn2 = ExtractedFromVec;
10540     } else {
10541       // Too many inputs.
10542       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10543       break;
10544     }
10545   }
10546
10547   // If everything is good, we can make a shuffle operation.
10548   if (VecIn1.getNode()) {
10549     SmallVector<int, 8> Mask;
10550     for (unsigned i = 0; i != NumInScalars; ++i) {
10551       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10552         Mask.push_back(-1);
10553         continue;
10554       }
10555
10556       // If extracting from the first vector, just use the index directly.
10557       SDValue Extract = N->getOperand(i);
10558       SDValue ExtVal = Extract.getOperand(1);
10559       if (Extract.getOperand(0) == VecIn1) {
10560         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10561         if (ExtIndex > VT.getVectorNumElements())
10562           return SDValue();
10563
10564         Mask.push_back(ExtIndex);
10565         continue;
10566       }
10567
10568       // Otherwise, use InIdx + VecSize
10569       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10570       Mask.push_back(Idx+NumInScalars);
10571     }
10572
10573     // We can't generate a shuffle node with mismatched input and output types.
10574     // Attempt to transform a single input vector to the correct type.
10575     if ((VT != VecIn1.getValueType())) {
10576       // We don't support shuffeling between TWO values of different types.
10577       if (VecIn2.getNode())
10578         return SDValue();
10579
10580       // We only support widening of vectors which are half the size of the
10581       // output registers. For example XMM->YMM widening on X86 with AVX.
10582       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10583         return SDValue();
10584
10585       // If the input vector type has a different base type to the output
10586       // vector type, bail out.
10587       if (VecIn1.getValueType().getVectorElementType() !=
10588           VT.getVectorElementType())
10589         return SDValue();
10590
10591       // Widen the input vector by adding undef values.
10592       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10593                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10594     }
10595
10596     // If VecIn2 is unused then change it to undef.
10597     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10598
10599     // Check that we were able to transform all incoming values to the same
10600     // type.
10601     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10602         VecIn1.getValueType() != VT)
10603           return SDValue();
10604
10605     // Return the new VECTOR_SHUFFLE node.
10606     SDValue Ops[2];
10607     Ops[0] = VecIn1;
10608     Ops[1] = VecIn2;
10609     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10610   }
10611
10612   return SDValue();
10613 }
10614
10615 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10616   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10617   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10618   // inputs come from at most two distinct vectors, turn this into a shuffle
10619   // node.
10620
10621   // If we only have one input vector, we don't need to do any concatenation.
10622   if (N->getNumOperands() == 1)
10623     return N->getOperand(0);
10624
10625   // Check if all of the operands are undefs.
10626   EVT VT = N->getValueType(0);
10627   if (ISD::allOperandsUndef(N))
10628     return DAG.getUNDEF(VT);
10629
10630   // Optimize concat_vectors where one of the vectors is undef.
10631   if (N->getNumOperands() == 2 &&
10632       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10633     SDValue In = N->getOperand(0);
10634     assert(In.getValueType().isVector() && "Must concat vectors");
10635
10636     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10637     if (In->getOpcode() == ISD::BITCAST &&
10638         !In->getOperand(0)->getValueType(0).isVector()) {
10639       SDValue Scalar = In->getOperand(0);
10640       EVT SclTy = Scalar->getValueType(0);
10641
10642       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10643         return SDValue();
10644
10645       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10646                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10647       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10648         return SDValue();
10649
10650       SDLoc dl = SDLoc(N);
10651       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10652       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10653     }
10654   }
10655
10656   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10657   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10658   if (N->getNumOperands() == 2 &&
10659       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10660       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10661     EVT VT = N->getValueType(0);
10662     SDValue N0 = N->getOperand(0);
10663     SDValue N1 = N->getOperand(1);
10664     SmallVector<SDValue, 8> Opnds;
10665     unsigned BuildVecNumElts =  N0.getNumOperands();
10666
10667     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10668     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10669     if (SclTy0.isFloatingPoint()) {
10670       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10671         Opnds.push_back(N0.getOperand(i));
10672       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10673         Opnds.push_back(N1.getOperand(i));
10674     } else {
10675       // If BUILD_VECTOR are from built from integer, they may have different
10676       // operand types. Get the smaller type and truncate all operands to it.
10677       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10678       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10679         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10680                         N0.getOperand(i)));
10681       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10682         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10683                         N1.getOperand(i)));
10684     }
10685
10686     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10687   }
10688
10689   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10690   // nodes often generate nop CONCAT_VECTOR nodes.
10691   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10692   // place the incoming vectors at the exact same location.
10693   SDValue SingleSource = SDValue();
10694   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10695
10696   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10697     SDValue Op = N->getOperand(i);
10698
10699     if (Op.getOpcode() == ISD::UNDEF)
10700       continue;
10701
10702     // Check if this is the identity extract:
10703     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10704       return SDValue();
10705
10706     // Find the single incoming vector for the extract_subvector.
10707     if (SingleSource.getNode()) {
10708       if (Op.getOperand(0) != SingleSource)
10709         return SDValue();
10710     } else {
10711       SingleSource = Op.getOperand(0);
10712
10713       // Check the source type is the same as the type of the result.
10714       // If not, this concat may extend the vector, so we can not
10715       // optimize it away.
10716       if (SingleSource.getValueType() != N->getValueType(0))
10717         return SDValue();
10718     }
10719
10720     unsigned IdentityIndex = i * PartNumElem;
10721     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10722     // The extract index must be constant.
10723     if (!CS)
10724       return SDValue();
10725
10726     // Check that we are reading from the identity index.
10727     if (CS->getZExtValue() != IdentityIndex)
10728       return SDValue();
10729   }
10730
10731   if (SingleSource.getNode())
10732     return SingleSource;
10733
10734   return SDValue();
10735 }
10736
10737 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10738   EVT NVT = N->getValueType(0);
10739   SDValue V = N->getOperand(0);
10740
10741   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10742     // Combine:
10743     //    (extract_subvec (concat V1, V2, ...), i)
10744     // Into:
10745     //    Vi if possible
10746     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10747     // type.
10748     if (V->getOperand(0).getValueType() != NVT)
10749       return SDValue();
10750     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10751     unsigned NumElems = NVT.getVectorNumElements();
10752     assert((Idx % NumElems) == 0 &&
10753            "IDX in concat is not a multiple of the result vector length.");
10754     return V->getOperand(Idx / NumElems);
10755   }
10756
10757   // Skip bitcasting
10758   if (V->getOpcode() == ISD::BITCAST)
10759     V = V.getOperand(0);
10760
10761   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10762     SDLoc dl(N);
10763     // Handle only simple case where vector being inserted and vector
10764     // being extracted are of same type, and are half size of larger vectors.
10765     EVT BigVT = V->getOperand(0).getValueType();
10766     EVT SmallVT = V->getOperand(1).getValueType();
10767     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10768       return SDValue();
10769
10770     // Only handle cases where both indexes are constants with the same type.
10771     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10772     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10773
10774     if (InsIdx && ExtIdx &&
10775         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10776         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10777       // Combine:
10778       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10779       // Into:
10780       //    indices are equal or bit offsets are equal => V1
10781       //    otherwise => (extract_subvec V1, ExtIdx)
10782       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10783           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10784         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10785       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10786                          DAG.getNode(ISD::BITCAST, dl,
10787                                      N->getOperand(0).getValueType(),
10788                                      V->getOperand(0)), N->getOperand(1));
10789     }
10790   }
10791
10792   return SDValue();
10793 }
10794
10795 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10796                                                  SDValue V, SelectionDAG &DAG) {
10797   SDLoc DL(V);
10798   EVT VT = V.getValueType();
10799
10800   switch (V.getOpcode()) {
10801   default:
10802     return V;
10803
10804   case ISD::CONCAT_VECTORS: {
10805     EVT OpVT = V->getOperand(0).getValueType();
10806     int OpSize = OpVT.getVectorNumElements();
10807     SmallBitVector OpUsedElements(OpSize, false);
10808     bool FoundSimplification = false;
10809     SmallVector<SDValue, 4> NewOps;
10810     NewOps.reserve(V->getNumOperands());
10811     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10812       SDValue Op = V->getOperand(i);
10813       bool OpUsed = false;
10814       for (int j = 0; j < OpSize; ++j)
10815         if (UsedElements[i * OpSize + j]) {
10816           OpUsedElements[j] = true;
10817           OpUsed = true;
10818         }
10819       NewOps.push_back(
10820           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10821                  : DAG.getUNDEF(OpVT));
10822       FoundSimplification |= Op == NewOps.back();
10823       OpUsedElements.reset();
10824     }
10825     if (FoundSimplification)
10826       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10827     return V;
10828   }
10829
10830   case ISD::INSERT_SUBVECTOR: {
10831     SDValue BaseV = V->getOperand(0);
10832     SDValue SubV = V->getOperand(1);
10833     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10834     if (!IdxN)
10835       return V;
10836
10837     int SubSize = SubV.getValueType().getVectorNumElements();
10838     int Idx = IdxN->getZExtValue();
10839     bool SubVectorUsed = false;
10840     SmallBitVector SubUsedElements(SubSize, false);
10841     for (int i = 0; i < SubSize; ++i)
10842       if (UsedElements[i + Idx]) {
10843         SubVectorUsed = true;
10844         SubUsedElements[i] = true;
10845         UsedElements[i + Idx] = false;
10846       }
10847
10848     // Now recurse on both the base and sub vectors.
10849     SDValue SimplifiedSubV =
10850         SubVectorUsed
10851             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10852             : DAG.getUNDEF(SubV.getValueType());
10853     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10854     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10855       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10856                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10857     return V;
10858   }
10859   }
10860 }
10861
10862 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10863                                        SDValue N1, SelectionDAG &DAG) {
10864   EVT VT = SVN->getValueType(0);
10865   int NumElts = VT.getVectorNumElements();
10866   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10867   for (int M : SVN->getMask())
10868     if (M >= 0 && M < NumElts)
10869       N0UsedElements[M] = true;
10870     else if (M >= NumElts)
10871       N1UsedElements[M - NumElts] = true;
10872
10873   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10874   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10875   if (S0 == N0 && S1 == N1)
10876     return SDValue();
10877
10878   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10879 }
10880
10881 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10882 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10883   EVT VT = N->getValueType(0);
10884   unsigned NumElts = VT.getVectorNumElements();
10885
10886   SDValue N0 = N->getOperand(0);
10887   SDValue N1 = N->getOperand(1);
10888   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10889
10890   SmallVector<SDValue, 4> Ops;
10891   EVT ConcatVT = N0.getOperand(0).getValueType();
10892   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10893   unsigned NumConcats = NumElts / NumElemsPerConcat;
10894
10895   // Look at every vector that's inserted. We're looking for exact
10896   // subvector-sized copies from a concatenated vector
10897   for (unsigned I = 0; I != NumConcats; ++I) {
10898     // Make sure we're dealing with a copy.
10899     unsigned Begin = I * NumElemsPerConcat;
10900     bool AllUndef = true, NoUndef = true;
10901     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10902       if (SVN->getMaskElt(J) >= 0)
10903         AllUndef = false;
10904       else
10905         NoUndef = false;
10906     }
10907
10908     if (NoUndef) {
10909       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10910         return SDValue();
10911
10912       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10913         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10914           return SDValue();
10915
10916       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10917       if (FirstElt < N0.getNumOperands())
10918         Ops.push_back(N0.getOperand(FirstElt));
10919       else
10920         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10921
10922     } else if (AllUndef) {
10923       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10924     } else { // Mixed with general masks and undefs, can't do optimization.
10925       return SDValue();
10926     }
10927   }
10928
10929   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10930 }
10931
10932 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10933   EVT VT = N->getValueType(0);
10934   unsigned NumElts = VT.getVectorNumElements();
10935
10936   SDValue N0 = N->getOperand(0);
10937   SDValue N1 = N->getOperand(1);
10938
10939   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10940
10941   // Canonicalize shuffle undef, undef -> undef
10942   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10943     return DAG.getUNDEF(VT);
10944
10945   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10946
10947   // Canonicalize shuffle v, v -> v, undef
10948   if (N0 == N1) {
10949     SmallVector<int, 8> NewMask;
10950     for (unsigned i = 0; i != NumElts; ++i) {
10951       int Idx = SVN->getMaskElt(i);
10952       if (Idx >= (int)NumElts) Idx -= NumElts;
10953       NewMask.push_back(Idx);
10954     }
10955     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10956                                 &NewMask[0]);
10957   }
10958
10959   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10960   if (N0.getOpcode() == ISD::UNDEF) {
10961     SmallVector<int, 8> NewMask;
10962     for (unsigned i = 0; i != NumElts; ++i) {
10963       int Idx = SVN->getMaskElt(i);
10964       if (Idx >= 0) {
10965         if (Idx >= (int)NumElts)
10966           Idx -= NumElts;
10967         else
10968           Idx = -1; // remove reference to lhs
10969       }
10970       NewMask.push_back(Idx);
10971     }
10972     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10973                                 &NewMask[0]);
10974   }
10975
10976   // Remove references to rhs if it is undef
10977   if (N1.getOpcode() == ISD::UNDEF) {
10978     bool Changed = false;
10979     SmallVector<int, 8> NewMask;
10980     for (unsigned i = 0; i != NumElts; ++i) {
10981       int Idx = SVN->getMaskElt(i);
10982       if (Idx >= (int)NumElts) {
10983         Idx = -1;
10984         Changed = true;
10985       }
10986       NewMask.push_back(Idx);
10987     }
10988     if (Changed)
10989       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10990   }
10991
10992   // If it is a splat, check if the argument vector is another splat or a
10993   // build_vector with all scalar elements the same.
10994   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10995     SDNode *V = N0.getNode();
10996
10997     // If this is a bit convert that changes the element type of the vector but
10998     // not the number of vector elements, look through it.  Be careful not to
10999     // look though conversions that change things like v4f32 to v2f64.
11000     if (V->getOpcode() == ISD::BITCAST) {
11001       SDValue ConvInput = V->getOperand(0);
11002       if (ConvInput.getValueType().isVector() &&
11003           ConvInput.getValueType().getVectorNumElements() == NumElts)
11004         V = ConvInput.getNode();
11005     }
11006
11007     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11008       assert(V->getNumOperands() == NumElts &&
11009              "BUILD_VECTOR has wrong number of operands");
11010       SDValue Base;
11011       bool AllSame = true;
11012       for (unsigned i = 0; i != NumElts; ++i) {
11013         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11014           Base = V->getOperand(i);
11015           break;
11016         }
11017       }
11018       // Splat of <u, u, u, u>, return <u, u, u, u>
11019       if (!Base.getNode())
11020         return N0;
11021       for (unsigned i = 0; i != NumElts; ++i) {
11022         if (V->getOperand(i) != Base) {
11023           AllSame = false;
11024           break;
11025         }
11026       }
11027       // Splat of <x, x, x, x>, return <x, x, x, x>
11028       if (AllSame)
11029         return N0;
11030     }
11031   }
11032
11033   // There are various patterns used to build up a vector from smaller vectors,
11034   // subvectors, or elements. Scan chains of these and replace unused insertions
11035   // or components with undef.
11036   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11037     return S;
11038
11039   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11040       Level < AfterLegalizeVectorOps &&
11041       (N1.getOpcode() == ISD::UNDEF ||
11042       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11043        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11044     SDValue V = partitionShuffleOfConcats(N, DAG);
11045
11046     if (V.getNode())
11047       return V;
11048   }
11049
11050   // If this shuffle node is simply a swizzle of another shuffle node,
11051   // then try to simplify it.
11052   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11053       N1.getOpcode() == ISD::UNDEF) {
11054
11055     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11056
11057     // The incoming shuffle must be of the same type as the result of the
11058     // current shuffle.
11059     assert(OtherSV->getOperand(0).getValueType() == VT &&
11060            "Shuffle types don't match");
11061
11062     SmallVector<int, 4> Mask;
11063     // Compute the combined shuffle mask.
11064     for (unsigned i = 0; i != NumElts; ++i) {
11065       int Idx = SVN->getMaskElt(i);
11066       assert(Idx < (int)NumElts && "Index references undef operand");
11067       // Next, this index comes from the first value, which is the incoming
11068       // shuffle. Adopt the incoming index.
11069       if (Idx >= 0)
11070         Idx = OtherSV->getMaskElt(Idx);
11071       Mask.push_back(Idx);
11072     }
11073
11074     // Check if all indices in Mask are Undef. In case, propagate Undef.
11075     bool isUndefMask = true;
11076     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11077       isUndefMask &= Mask[i] < 0;
11078
11079     if (isUndefMask)
11080       return DAG.getUNDEF(VT);
11081
11082     bool CommuteOperands = false;
11083     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11084       // To be valid, the combine shuffle mask should only reference elements
11085       // from one of the two vectors in input to the inner shufflevector.
11086       bool IsValidMask = true;
11087       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11088         // See if the combined mask only reference undefs or elements coming
11089         // from the first shufflevector operand.
11090         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11091
11092       if (!IsValidMask) {
11093         IsValidMask = true;
11094         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11095           // Check that all the elements come from the second shuffle operand.
11096           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11097         CommuteOperands = IsValidMask;
11098       }
11099
11100       // Early exit if the combined shuffle mask is not valid.
11101       if (!IsValidMask)
11102         return SDValue();
11103     }
11104
11105     // See if this pair of shuffles can be safely folded according to either
11106     // of the following rules:
11107     //   shuffle(shuffle(x, y), undef) -> x
11108     //   shuffle(shuffle(x, undef), undef) -> x
11109     //   shuffle(shuffle(x, y), undef) -> y
11110     bool IsIdentityMask = true;
11111     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11112     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11113       // Skip Undefs.
11114       if (Mask[i] < 0)
11115         continue;
11116
11117       // The combined shuffle must map each index to itself.
11118       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11119     }
11120
11121     if (IsIdentityMask) {
11122       if (CommuteOperands)
11123         // optimize shuffle(shuffle(x, y), undef) -> y.
11124         return OtherSV->getOperand(1);
11125
11126       // optimize shuffle(shuffle(x, undef), undef) -> x
11127       // optimize shuffle(shuffle(x, y), undef) -> x
11128       return OtherSV->getOperand(0);
11129     }
11130
11131     // It may still be beneficial to combine the two shuffles if the
11132     // resulting shuffle is legal.
11133     if (TLI.isTypeLegal(VT)) {
11134       if (!CommuteOperands) {
11135         if (TLI.isShuffleMaskLegal(Mask, VT))
11136           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11137           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11138           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11139                                       &Mask[0]);
11140       } else {
11141         // Compute the commuted shuffle mask.
11142         for (unsigned i = 0; i != NumElts; ++i) {
11143           int idx = Mask[i];
11144           if (idx < 0)
11145             continue;
11146           else if (idx < (int)NumElts)
11147             Mask[i] = idx + NumElts;
11148           else
11149             Mask[i] = idx - NumElts;
11150         }
11151
11152         if (TLI.isShuffleMaskLegal(Mask, VT))
11153           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11154           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11155                                       &Mask[0]);
11156       }
11157     }
11158   }
11159
11160   // Canonicalize shuffles according to rules:
11161   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11162   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11163   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11164   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11165       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11166       TLI.isTypeLegal(VT)) {
11167     // The incoming shuffle must be of the same type as the result of the
11168     // current shuffle.
11169     assert(N1->getOperand(0).getValueType() == VT &&
11170            "Shuffle types don't match");
11171
11172     SDValue SV0 = N1->getOperand(0);
11173     SDValue SV1 = N1->getOperand(1);
11174     bool HasSameOp0 = N0 == SV0;
11175     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11176     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11177       // Commute the operands of this shuffle so that next rule
11178       // will trigger.
11179       return DAG.getCommutedVectorShuffle(*SVN);
11180   }
11181
11182   // Try to fold according to rules:
11183   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11184   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11185   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11186   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11187   // Don't try to fold shuffles with illegal type.
11188   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11189       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11190     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11191
11192     // The incoming shuffle must be of the same type as the result of the
11193     // current shuffle.
11194     assert(OtherSV->getOperand(0).getValueType() == VT &&
11195            "Shuffle types don't match");
11196
11197     SDValue SV0 = OtherSV->getOperand(0);
11198     SDValue SV1 = OtherSV->getOperand(1);
11199     bool HasSameOp0 = N1 == SV0;
11200     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11201     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11202       // Early exit.
11203       return SDValue();
11204
11205     SmallVector<int, 4> Mask;
11206     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11207     // operand, and SV1 as the second operand.
11208     for (unsigned i = 0; i != NumElts; ++i) {
11209       int Idx = SVN->getMaskElt(i);
11210       if (Idx < 0) {
11211         // Propagate Undef.
11212         Mask.push_back(Idx);
11213         continue;
11214       }
11215
11216       if (Idx < (int)NumElts) {
11217         Idx = OtherSV->getMaskElt(Idx);
11218         if (IsSV1Undef && Idx >= (int) NumElts)
11219           Idx = -1;  // Propagate Undef.
11220       } else
11221         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11222
11223       Mask.push_back(Idx);
11224     }
11225
11226     // Check if all indices in Mask are Undef. In case, propagate Undef.
11227     bool isUndefMask = true;
11228     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11229       isUndefMask &= Mask[i] < 0;
11230
11231     if (isUndefMask)
11232       return DAG.getUNDEF(VT);
11233
11234     // Avoid introducing shuffles with illegal mask.
11235     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11236       if (IsSV1Undef)
11237         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11238         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11239         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11240       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11241     }
11242
11243     // Compute the commuted shuffle mask.
11244     for (unsigned i = 0; i != NumElts; ++i) {
11245       int idx = Mask[i];
11246       if (idx < 0)
11247         continue;
11248       else if (idx < (int)NumElts)
11249         Mask[i] = idx + NumElts;
11250       else
11251         Mask[i] = idx - NumElts;
11252     }
11253
11254     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11255       if (IsSV1Undef)
11256         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(B, A, M2)
11257         return DAG.getVectorShuffle(VT, SDLoc(N), N1, SV0, &Mask[0]);
11258       //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(B, A, M2)
11259       //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(B, A, M2)
11260       return DAG.getVectorShuffle(VT, SDLoc(N), SV1, SV0, &Mask[0]);
11261     }
11262   }
11263
11264   return SDValue();
11265 }
11266
11267 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11268   SDValue N0 = N->getOperand(0);
11269   SDValue N2 = N->getOperand(2);
11270
11271   // If the input vector is a concatenation, and the insert replaces
11272   // one of the halves, we can optimize into a single concat_vectors.
11273   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11274       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11275     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11276     EVT VT = N->getValueType(0);
11277
11278     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11279     // (concat_vectors Z, Y)
11280     if (InsIdx == 0)
11281       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11282                          N->getOperand(1), N0.getOperand(1));
11283
11284     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11285     // (concat_vectors X, Z)
11286     if (InsIdx == VT.getVectorNumElements()/2)
11287       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11288                          N0.getOperand(0), N->getOperand(1));
11289   }
11290
11291   return SDValue();
11292 }
11293
11294 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11295 /// with the destination vector and a zero vector.
11296 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11297 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11298 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11299   EVT VT = N->getValueType(0);
11300   SDLoc dl(N);
11301   SDValue LHS = N->getOperand(0);
11302   SDValue RHS = N->getOperand(1);
11303   if (N->getOpcode() == ISD::AND) {
11304     if (RHS.getOpcode() == ISD::BITCAST)
11305       RHS = RHS.getOperand(0);
11306     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11307       SmallVector<int, 8> Indices;
11308       unsigned NumElts = RHS.getNumOperands();
11309       for (unsigned i = 0; i != NumElts; ++i) {
11310         SDValue Elt = RHS.getOperand(i);
11311         if (!isa<ConstantSDNode>(Elt))
11312           return SDValue();
11313
11314         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11315           Indices.push_back(i);
11316         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11317           Indices.push_back(NumElts+i);
11318         else
11319           return SDValue();
11320       }
11321
11322       // Let's see if the target supports this vector_shuffle.
11323       EVT RVT = RHS.getValueType();
11324       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11325         return SDValue();
11326
11327       // Return the new VECTOR_SHUFFLE node.
11328       EVT EltVT = RVT.getVectorElementType();
11329       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11330                                      DAG.getConstant(0, EltVT));
11331       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11332       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11333       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11334       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11335     }
11336   }
11337
11338   return SDValue();
11339 }
11340
11341 /// Visit a binary vector operation, like ADD.
11342 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11343   assert(N->getValueType(0).isVector() &&
11344          "SimplifyVBinOp only works on vectors!");
11345
11346   SDValue LHS = N->getOperand(0);
11347   SDValue RHS = N->getOperand(1);
11348   SDValue Shuffle = XformToShuffleWithZero(N);
11349   if (Shuffle.getNode()) return Shuffle;
11350
11351   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11352   // this operation.
11353   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11354       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11355     // Check if both vectors are constants. If not bail out.
11356     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11357           cast<BuildVectorSDNode>(RHS)->isConstant()))
11358       return SDValue();
11359
11360     SmallVector<SDValue, 8> Ops;
11361     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11362       SDValue LHSOp = LHS.getOperand(i);
11363       SDValue RHSOp = RHS.getOperand(i);
11364
11365       // Can't fold divide by zero.
11366       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11367           N->getOpcode() == ISD::FDIV) {
11368         if ((RHSOp.getOpcode() == ISD::Constant &&
11369              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11370             (RHSOp.getOpcode() == ISD::ConstantFP &&
11371              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11372           break;
11373       }
11374
11375       EVT VT = LHSOp.getValueType();
11376       EVT RVT = RHSOp.getValueType();
11377       if (RVT != VT) {
11378         // Integer BUILD_VECTOR operands may have types larger than the element
11379         // size (e.g., when the element type is not legal).  Prior to type
11380         // legalization, the types may not match between the two BUILD_VECTORS.
11381         // Truncate one of the operands to make them match.
11382         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11383           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11384         } else {
11385           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11386           VT = RVT;
11387         }
11388       }
11389       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11390                                    LHSOp, RHSOp);
11391       if (FoldOp.getOpcode() != ISD::UNDEF &&
11392           FoldOp.getOpcode() != ISD::Constant &&
11393           FoldOp.getOpcode() != ISD::ConstantFP)
11394         break;
11395       Ops.push_back(FoldOp);
11396       AddToWorklist(FoldOp.getNode());
11397     }
11398
11399     if (Ops.size() == LHS.getNumOperands())
11400       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11401   }
11402
11403   // Type legalization might introduce new shuffles in the DAG.
11404   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11405   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11406   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11407       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11408       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11409       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11410     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11411     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11412
11413     if (SVN0->getMask().equals(SVN1->getMask())) {
11414       EVT VT = N->getValueType(0);
11415       SDValue UndefVector = LHS.getOperand(1);
11416       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11417                                      LHS.getOperand(0), RHS.getOperand(0));
11418       AddUsersToWorklist(N);
11419       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11420                                   &SVN0->getMask()[0]);
11421     }
11422   }
11423
11424   return SDValue();
11425 }
11426
11427 /// Visit a binary vector operation, like FABS/FNEG.
11428 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11429   assert(N->getValueType(0).isVector() &&
11430          "SimplifyVUnaryOp only works on vectors!");
11431
11432   SDValue N0 = N->getOperand(0);
11433
11434   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11435     return SDValue();
11436
11437   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11438   SmallVector<SDValue, 8> Ops;
11439   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11440     SDValue Op = N0.getOperand(i);
11441     if (Op.getOpcode() != ISD::UNDEF &&
11442         Op.getOpcode() != ISD::ConstantFP)
11443       break;
11444     EVT EltVT = Op.getValueType();
11445     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11446     if (FoldOp.getOpcode() != ISD::UNDEF &&
11447         FoldOp.getOpcode() != ISD::ConstantFP)
11448       break;
11449     Ops.push_back(FoldOp);
11450     AddToWorklist(FoldOp.getNode());
11451   }
11452
11453   if (Ops.size() != N0.getNumOperands())
11454     return SDValue();
11455
11456   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11457 }
11458
11459 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11460                                     SDValue N1, SDValue N2){
11461   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11462
11463   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11464                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11465
11466   // If we got a simplified select_cc node back from SimplifySelectCC, then
11467   // break it down into a new SETCC node, and a new SELECT node, and then return
11468   // the SELECT node, since we were called with a SELECT node.
11469   if (SCC.getNode()) {
11470     // Check to see if we got a select_cc back (to turn into setcc/select).
11471     // Otherwise, just return whatever node we got back, like fabs.
11472     if (SCC.getOpcode() == ISD::SELECT_CC) {
11473       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11474                                   N0.getValueType(),
11475                                   SCC.getOperand(0), SCC.getOperand(1),
11476                                   SCC.getOperand(4));
11477       AddToWorklist(SETCC.getNode());
11478       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11479                            SCC.getOperand(2), SCC.getOperand(3));
11480     }
11481
11482     return SCC;
11483   }
11484   return SDValue();
11485 }
11486
11487 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11488 /// being selected between, see if we can simplify the select.  Callers of this
11489 /// should assume that TheSelect is deleted if this returns true.  As such, they
11490 /// should return the appropriate thing (e.g. the node) back to the top-level of
11491 /// the DAG combiner loop to avoid it being looked at.
11492 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11493                                     SDValue RHS) {
11494
11495   // Cannot simplify select with vector condition
11496   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11497
11498   // If this is a select from two identical things, try to pull the operation
11499   // through the select.
11500   if (LHS.getOpcode() != RHS.getOpcode() ||
11501       !LHS.hasOneUse() || !RHS.hasOneUse())
11502     return false;
11503
11504   // If this is a load and the token chain is identical, replace the select
11505   // of two loads with a load through a select of the address to load from.
11506   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11507   // constants have been dropped into the constant pool.
11508   if (LHS.getOpcode() == ISD::LOAD) {
11509     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11510     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11511
11512     // Token chains must be identical.
11513     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11514         // Do not let this transformation reduce the number of volatile loads.
11515         LLD->isVolatile() || RLD->isVolatile() ||
11516         // If this is an EXTLOAD, the VT's must match.
11517         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11518         // If this is an EXTLOAD, the kind of extension must match.
11519         (LLD->getExtensionType() != RLD->getExtensionType() &&
11520          // The only exception is if one of the extensions is anyext.
11521          LLD->getExtensionType() != ISD::EXTLOAD &&
11522          RLD->getExtensionType() != ISD::EXTLOAD) ||
11523         // FIXME: this discards src value information.  This is
11524         // over-conservative. It would be beneficial to be able to remember
11525         // both potential memory locations.  Since we are discarding
11526         // src value info, don't do the transformation if the memory
11527         // locations are not in the default address space.
11528         LLD->getPointerInfo().getAddrSpace() != 0 ||
11529         RLD->getPointerInfo().getAddrSpace() != 0 ||
11530         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11531                                       LLD->getBasePtr().getValueType()))
11532       return false;
11533
11534     // Check that the select condition doesn't reach either load.  If so,
11535     // folding this will induce a cycle into the DAG.  If not, this is safe to
11536     // xform, so create a select of the addresses.
11537     SDValue Addr;
11538     if (TheSelect->getOpcode() == ISD::SELECT) {
11539       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11540       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11541           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11542         return false;
11543       // The loads must not depend on one another.
11544       if (LLD->isPredecessorOf(RLD) ||
11545           RLD->isPredecessorOf(LLD))
11546         return false;
11547       Addr = DAG.getSelect(SDLoc(TheSelect),
11548                            LLD->getBasePtr().getValueType(),
11549                            TheSelect->getOperand(0), LLD->getBasePtr(),
11550                            RLD->getBasePtr());
11551     } else {  // Otherwise SELECT_CC
11552       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11553       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11554
11555       if ((LLD->hasAnyUseOfValue(1) &&
11556            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11557           (RLD->hasAnyUseOfValue(1) &&
11558            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11559         return false;
11560
11561       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11562                          LLD->getBasePtr().getValueType(),
11563                          TheSelect->getOperand(0),
11564                          TheSelect->getOperand(1),
11565                          LLD->getBasePtr(), RLD->getBasePtr(),
11566                          TheSelect->getOperand(4));
11567     }
11568
11569     SDValue Load;
11570     // It is safe to replace the two loads if they have different alignments,
11571     // but the new load must be the minimum (most restrictive) alignment of the
11572     // inputs.
11573     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11574     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11575     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11576       Load = DAG.getLoad(TheSelect->getValueType(0),
11577                          SDLoc(TheSelect),
11578                          // FIXME: Discards pointer and AA info.
11579                          LLD->getChain(), Addr, MachinePointerInfo(),
11580                          LLD->isVolatile(), LLD->isNonTemporal(),
11581                          isInvariant, Alignment);
11582     } else {
11583       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11584                             RLD->getExtensionType() : LLD->getExtensionType(),
11585                             SDLoc(TheSelect),
11586                             TheSelect->getValueType(0),
11587                             // FIXME: Discards pointer and AA info.
11588                             LLD->getChain(), Addr, MachinePointerInfo(),
11589                             LLD->getMemoryVT(), LLD->isVolatile(),
11590                             LLD->isNonTemporal(), isInvariant, Alignment);
11591     }
11592
11593     // Users of the select now use the result of the load.
11594     CombineTo(TheSelect, Load);
11595
11596     // Users of the old loads now use the new load's chain.  We know the
11597     // old-load value is dead now.
11598     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11599     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11600     return true;
11601   }
11602
11603   return false;
11604 }
11605
11606 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11607 /// where 'cond' is the comparison specified by CC.
11608 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11609                                       SDValue N2, SDValue N3,
11610                                       ISD::CondCode CC, bool NotExtCompare) {
11611   // (x ? y : y) -> y.
11612   if (N2 == N3) return N2;
11613
11614   EVT VT = N2.getValueType();
11615   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11616   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11617   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11618
11619   // Determine if the condition we're dealing with is constant
11620   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11621                               N0, N1, CC, DL, false);
11622   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11623   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11624
11625   // fold select_cc true, x, y -> x
11626   if (SCCC && !SCCC->isNullValue())
11627     return N2;
11628   // fold select_cc false, x, y -> y
11629   if (SCCC && SCCC->isNullValue())
11630     return N3;
11631
11632   // Check to see if we can simplify the select into an fabs node
11633   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11634     // Allow either -0.0 or 0.0
11635     if (CFP->getValueAPF().isZero()) {
11636       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11637       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11638           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11639           N2 == N3.getOperand(0))
11640         return DAG.getNode(ISD::FABS, DL, VT, N0);
11641
11642       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11643       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11644           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11645           N2.getOperand(0) == N3)
11646         return DAG.getNode(ISD::FABS, DL, VT, N3);
11647     }
11648   }
11649
11650   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11651   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11652   // in it.  This is a win when the constant is not otherwise available because
11653   // it replaces two constant pool loads with one.  We only do this if the FP
11654   // type is known to be legal, because if it isn't, then we are before legalize
11655   // types an we want the other legalization to happen first (e.g. to avoid
11656   // messing with soft float) and if the ConstantFP is not legal, because if
11657   // it is legal, we may not need to store the FP constant in a constant pool.
11658   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11659     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11660       if (TLI.isTypeLegal(N2.getValueType()) &&
11661           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11662                TargetLowering::Legal &&
11663            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11664            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11665           // If both constants have multiple uses, then we won't need to do an
11666           // extra load, they are likely around in registers for other users.
11667           (TV->hasOneUse() || FV->hasOneUse())) {
11668         Constant *Elts[] = {
11669           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11670           const_cast<ConstantFP*>(TV->getConstantFPValue())
11671         };
11672         Type *FPTy = Elts[0]->getType();
11673         const DataLayout &TD = *TLI.getDataLayout();
11674
11675         // Create a ConstantArray of the two constants.
11676         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11677         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11678                                             TD.getPrefTypeAlignment(FPTy));
11679         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11680
11681         // Get the offsets to the 0 and 1 element of the array so that we can
11682         // select between them.
11683         SDValue Zero = DAG.getIntPtrConstant(0);
11684         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11685         SDValue One = DAG.getIntPtrConstant(EltSize);
11686
11687         SDValue Cond = DAG.getSetCC(DL,
11688                                     getSetCCResultType(N0.getValueType()),
11689                                     N0, N1, CC);
11690         AddToWorklist(Cond.getNode());
11691         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11692                                           Cond, One, Zero);
11693         AddToWorklist(CstOffset.getNode());
11694         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11695                             CstOffset);
11696         AddToWorklist(CPIdx.getNode());
11697         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11698                            MachinePointerInfo::getConstantPool(), false,
11699                            false, false, Alignment);
11700
11701       }
11702     }
11703
11704   // Check to see if we can perform the "gzip trick", transforming
11705   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11706   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11707       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11708        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11709     EVT XType = N0.getValueType();
11710     EVT AType = N2.getValueType();
11711     if (XType.bitsGE(AType)) {
11712       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11713       // single-bit constant.
11714       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11715         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11716         ShCtV = XType.getSizeInBits()-ShCtV-1;
11717         SDValue ShCt = DAG.getConstant(ShCtV,
11718                                        getShiftAmountTy(N0.getValueType()));
11719         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11720                                     XType, N0, ShCt);
11721         AddToWorklist(Shift.getNode());
11722
11723         if (XType.bitsGT(AType)) {
11724           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11725           AddToWorklist(Shift.getNode());
11726         }
11727
11728         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11729       }
11730
11731       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11732                                   XType, N0,
11733                                   DAG.getConstant(XType.getSizeInBits()-1,
11734                                          getShiftAmountTy(N0.getValueType())));
11735       AddToWorklist(Shift.getNode());
11736
11737       if (XType.bitsGT(AType)) {
11738         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11739         AddToWorklist(Shift.getNode());
11740       }
11741
11742       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11743     }
11744   }
11745
11746   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11747   // where y is has a single bit set.
11748   // A plaintext description would be, we can turn the SELECT_CC into an AND
11749   // when the condition can be materialized as an all-ones register.  Any
11750   // single bit-test can be materialized as an all-ones register with
11751   // shift-left and shift-right-arith.
11752   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11753       N0->getValueType(0) == VT &&
11754       N1C && N1C->isNullValue() &&
11755       N2C && N2C->isNullValue()) {
11756     SDValue AndLHS = N0->getOperand(0);
11757     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11758     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11759       // Shift the tested bit over the sign bit.
11760       APInt AndMask = ConstAndRHS->getAPIntValue();
11761       SDValue ShlAmt =
11762         DAG.getConstant(AndMask.countLeadingZeros(),
11763                         getShiftAmountTy(AndLHS.getValueType()));
11764       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11765
11766       // Now arithmetic right shift it all the way over, so the result is either
11767       // all-ones, or zero.
11768       SDValue ShrAmt =
11769         DAG.getConstant(AndMask.getBitWidth()-1,
11770                         getShiftAmountTy(Shl.getValueType()));
11771       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11772
11773       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11774     }
11775   }
11776
11777   // fold select C, 16, 0 -> shl C, 4
11778   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11779       TLI.getBooleanContents(N0.getValueType()) ==
11780           TargetLowering::ZeroOrOneBooleanContent) {
11781
11782     // If the caller doesn't want us to simplify this into a zext of a compare,
11783     // don't do it.
11784     if (NotExtCompare && N2C->getAPIntValue() == 1)
11785       return SDValue();
11786
11787     // Get a SetCC of the condition
11788     // NOTE: Don't create a SETCC if it's not legal on this target.
11789     if (!LegalOperations ||
11790         TLI.isOperationLegal(ISD::SETCC,
11791           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11792       SDValue Temp, SCC;
11793       // cast from setcc result type to select result type
11794       if (LegalTypes) {
11795         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11796                             N0, N1, CC);
11797         if (N2.getValueType().bitsLT(SCC.getValueType()))
11798           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11799                                         N2.getValueType());
11800         else
11801           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11802                              N2.getValueType(), SCC);
11803       } else {
11804         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11805         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11806                            N2.getValueType(), SCC);
11807       }
11808
11809       AddToWorklist(SCC.getNode());
11810       AddToWorklist(Temp.getNode());
11811
11812       if (N2C->getAPIntValue() == 1)
11813         return Temp;
11814
11815       // shl setcc result by log2 n2c
11816       return DAG.getNode(
11817           ISD::SHL, DL, N2.getValueType(), Temp,
11818           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11819                           getShiftAmountTy(Temp.getValueType())));
11820     }
11821   }
11822
11823   // Check to see if this is the equivalent of setcc
11824   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11825   // otherwise, go ahead with the folds.
11826   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11827     EVT XType = N0.getValueType();
11828     if (!LegalOperations ||
11829         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11830       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11831       if (Res.getValueType() != VT)
11832         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11833       return Res;
11834     }
11835
11836     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11837     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11838         (!LegalOperations ||
11839          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11840       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11841       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11842                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11843                                        getShiftAmountTy(Ctlz.getValueType())));
11844     }
11845     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11846     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11847       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11848                                   XType, DAG.getConstant(0, XType), N0);
11849       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11850       return DAG.getNode(ISD::SRL, DL, XType,
11851                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11852                          DAG.getConstant(XType.getSizeInBits()-1,
11853                                          getShiftAmountTy(XType)));
11854     }
11855     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11856     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11857       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11858                                  DAG.getConstant(XType.getSizeInBits()-1,
11859                                          getShiftAmountTy(N0.getValueType())));
11860       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11861     }
11862   }
11863
11864   // Check to see if this is an integer abs.
11865   // select_cc setg[te] X,  0,  X, -X ->
11866   // select_cc setgt    X, -1,  X, -X ->
11867   // select_cc setl[te] X,  0, -X,  X ->
11868   // select_cc setlt    X,  1, -X,  X ->
11869   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11870   if (N1C) {
11871     ConstantSDNode *SubC = nullptr;
11872     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11873          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11874         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11875       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11876     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11877               (N1C->isOne() && CC == ISD::SETLT)) &&
11878              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11879       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11880
11881     EVT XType = N0.getValueType();
11882     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11883       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11884                                   N0,
11885                                   DAG.getConstant(XType.getSizeInBits()-1,
11886                                          getShiftAmountTy(N0.getValueType())));
11887       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11888                                 XType, N0, Shift);
11889       AddToWorklist(Shift.getNode());
11890       AddToWorklist(Add.getNode());
11891       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11892     }
11893   }
11894
11895   return SDValue();
11896 }
11897
11898 /// This is a stub for TargetLowering::SimplifySetCC.
11899 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11900                                    SDValue N1, ISD::CondCode Cond,
11901                                    SDLoc DL, bool foldBooleans) {
11902   TargetLowering::DAGCombinerInfo
11903     DagCombineInfo(DAG, Level, false, this);
11904   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11905 }
11906
11907 /// Given an ISD::SDIV node expressing a divide by constant, return
11908 /// a DAG expression to select that will generate the same value by multiplying
11909 /// by a magic number.
11910 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11911 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11912   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11913   if (!C)
11914     return SDValue();
11915
11916   // Avoid division by zero.
11917   if (!C->getAPIntValue())
11918     return SDValue();
11919
11920   std::vector<SDNode*> Built;
11921   SDValue S =
11922       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11923
11924   for (SDNode *N : Built)
11925     AddToWorklist(N);
11926   return S;
11927 }
11928
11929 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11930 /// DAG expression that will generate the same value by right shifting.
11931 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11932   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11933   if (!C)
11934     return SDValue();
11935
11936   // Avoid division by zero.
11937   if (!C->getAPIntValue())
11938     return SDValue();
11939
11940   std::vector<SDNode *> Built;
11941   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11942
11943   for (SDNode *N : Built)
11944     AddToWorklist(N);
11945   return S;
11946 }
11947
11948 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11949 /// expression that will generate the same value by multiplying by a magic
11950 /// number.
11951 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11952 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11953   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11954   if (!C)
11955     return SDValue();
11956
11957   // Avoid division by zero.
11958   if (!C->getAPIntValue())
11959     return SDValue();
11960
11961   std::vector<SDNode*> Built;
11962   SDValue S =
11963       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11964
11965   for (SDNode *N : Built)
11966     AddToWorklist(N);
11967   return S;
11968 }
11969
11970 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11971   if (Level >= AfterLegalizeDAG)
11972     return SDValue();
11973
11974   // Expose the DAG combiner to the target combiner implementations.
11975   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11976
11977   unsigned Iterations = 0;
11978   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11979     if (Iterations) {
11980       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11981       // For the reciprocal, we need to find the zero of the function:
11982       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11983       //     =>
11984       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11985       //     does not require additional intermediate precision]
11986       EVT VT = Op.getValueType();
11987       SDLoc DL(Op);
11988       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11989
11990       AddToWorklist(Est.getNode());
11991
11992       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11993       for (unsigned i = 0; i < Iterations; ++i) {
11994         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11995         AddToWorklist(NewEst.getNode());
11996
11997         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11998         AddToWorklist(NewEst.getNode());
11999
12000         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12001         AddToWorklist(NewEst.getNode());
12002
12003         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12004         AddToWorklist(Est.getNode());
12005       }
12006     }
12007     return Est;
12008   }
12009
12010   return SDValue();
12011 }
12012
12013 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12014 /// For the reciprocal sqrt, we need to find the zero of the function:
12015 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12016 ///     =>
12017 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12018 /// As a result, we precompute A/2 prior to the iteration loop.
12019 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12020                                           unsigned Iterations) {
12021   EVT VT = Arg.getValueType();
12022   SDLoc DL(Arg);
12023   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12024
12025   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12026   // this entire sequence requires only one FP constant.
12027   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12028   AddToWorklist(HalfArg.getNode());
12029
12030   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12031   AddToWorklist(HalfArg.getNode());
12032
12033   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12034   for (unsigned i = 0; i < Iterations; ++i) {
12035     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12036     AddToWorklist(NewEst.getNode());
12037
12038     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12039     AddToWorklist(NewEst.getNode());
12040
12041     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12042     AddToWorklist(NewEst.getNode());
12043
12044     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12045     AddToWorklist(Est.getNode());
12046   }
12047   return Est;
12048 }
12049
12050 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12051 /// For the reciprocal sqrt, we need to find the zero of the function:
12052 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12053 ///     =>
12054 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12055 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12056                                           unsigned Iterations) {
12057   EVT VT = Arg.getValueType();
12058   SDLoc DL(Arg);
12059   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12060   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12061
12062   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12063   for (unsigned i = 0; i < Iterations; ++i) {
12064     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12065     AddToWorklist(HalfEst.getNode());
12066
12067     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12068     AddToWorklist(Est.getNode());
12069
12070     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12071     AddToWorklist(Est.getNode());
12072
12073     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12074     AddToWorklist(Est.getNode());
12075
12076     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12077     AddToWorklist(Est.getNode());
12078   }
12079   return Est;
12080 }
12081
12082 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12083   if (Level >= AfterLegalizeDAG)
12084     return SDValue();
12085
12086   // Expose the DAG combiner to the target combiner implementations.
12087   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12088   unsigned Iterations = 0;
12089   bool UseOneConstNR = false;
12090   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12091     AddToWorklist(Est.getNode());
12092     if (Iterations) {
12093       Est = UseOneConstNR ?
12094         BuildRsqrtNROneConst(Op, Est, Iterations) :
12095         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12096     }
12097     return Est;
12098   }
12099
12100   return SDValue();
12101 }
12102
12103 /// Return true if base is a frame index, which is known not to alias with
12104 /// anything but itself.  Provides base object and offset as results.
12105 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12106                            const GlobalValue *&GV, const void *&CV) {
12107   // Assume it is a primitive operation.
12108   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12109
12110   // If it's an adding a simple constant then integrate the offset.
12111   if (Base.getOpcode() == ISD::ADD) {
12112     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12113       Base = Base.getOperand(0);
12114       Offset += C->getZExtValue();
12115     }
12116   }
12117
12118   // Return the underlying GlobalValue, and update the Offset.  Return false
12119   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12120   // by multiple nodes with different offsets.
12121   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12122     GV = G->getGlobal();
12123     Offset += G->getOffset();
12124     return false;
12125   }
12126
12127   // Return the underlying Constant value, and update the Offset.  Return false
12128   // for ConstantSDNodes since the same constant pool entry may be represented
12129   // by multiple nodes with different offsets.
12130   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12131     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12132                                          : (const void *)C->getConstVal();
12133     Offset += C->getOffset();
12134     return false;
12135   }
12136   // If it's any of the following then it can't alias with anything but itself.
12137   return isa<FrameIndexSDNode>(Base);
12138 }
12139
12140 /// Return true if there is any possibility that the two addresses overlap.
12141 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12142   // If they are the same then they must be aliases.
12143   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12144
12145   // If they are both volatile then they cannot be reordered.
12146   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12147
12148   // Gather base node and offset information.
12149   SDValue Base1, Base2;
12150   int64_t Offset1, Offset2;
12151   const GlobalValue *GV1, *GV2;
12152   const void *CV1, *CV2;
12153   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12154                                       Base1, Offset1, GV1, CV1);
12155   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12156                                       Base2, Offset2, GV2, CV2);
12157
12158   // If they have a same base address then check to see if they overlap.
12159   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12160     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12161              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12162
12163   // It is possible for different frame indices to alias each other, mostly
12164   // when tail call optimization reuses return address slots for arguments.
12165   // To catch this case, look up the actual index of frame indices to compute
12166   // the real alias relationship.
12167   if (isFrameIndex1 && isFrameIndex2) {
12168     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12169     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12170     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12171     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12172              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12173   }
12174
12175   // Otherwise, if we know what the bases are, and they aren't identical, then
12176   // we know they cannot alias.
12177   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12178     return false;
12179
12180   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12181   // compared to the size and offset of the access, we may be able to prove they
12182   // do not alias.  This check is conservative for now to catch cases created by
12183   // splitting vector types.
12184   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12185       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12186       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12187        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12188       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12189     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12190     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12191
12192     // There is no overlap between these relatively aligned accesses of similar
12193     // size, return no alias.
12194     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12195         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12196       return false;
12197   }
12198
12199   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12200                    ? CombinerGlobalAA
12201                    : DAG.getSubtarget().useAA();
12202 #ifndef NDEBUG
12203   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12204       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12205     UseAA = false;
12206 #endif
12207   if (UseAA &&
12208       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12209     // Use alias analysis information.
12210     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12211                                  Op1->getSrcValueOffset());
12212     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12213         Op0->getSrcValueOffset() - MinOffset;
12214     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12215         Op1->getSrcValueOffset() - MinOffset;
12216     AliasAnalysis::AliasResult AAResult =
12217         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12218                                          Overlap1,
12219                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12220                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12221                                          Overlap2,
12222                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12223     if (AAResult == AliasAnalysis::NoAlias)
12224       return false;
12225   }
12226
12227   // Otherwise we have to assume they alias.
12228   return true;
12229 }
12230
12231 /// Walk up chain skipping non-aliasing memory nodes,
12232 /// looking for aliasing nodes and adding them to the Aliases vector.
12233 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12234                                    SmallVectorImpl<SDValue> &Aliases) {
12235   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12236   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12237
12238   // Get alias information for node.
12239   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12240
12241   // Starting off.
12242   Chains.push_back(OriginalChain);
12243   unsigned Depth = 0;
12244
12245   // Look at each chain and determine if it is an alias.  If so, add it to the
12246   // aliases list.  If not, then continue up the chain looking for the next
12247   // candidate.
12248   while (!Chains.empty()) {
12249     SDValue Chain = Chains.back();
12250     Chains.pop_back();
12251
12252     // For TokenFactor nodes, look at each operand and only continue up the
12253     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12254     // find more and revert to original chain since the xform is unlikely to be
12255     // profitable.
12256     //
12257     // FIXME: The depth check could be made to return the last non-aliasing
12258     // chain we found before we hit a tokenfactor rather than the original
12259     // chain.
12260     if (Depth > 6 || Aliases.size() == 2) {
12261       Aliases.clear();
12262       Aliases.push_back(OriginalChain);
12263       return;
12264     }
12265
12266     // Don't bother if we've been before.
12267     if (!Visited.insert(Chain.getNode()))
12268       continue;
12269
12270     switch (Chain.getOpcode()) {
12271     case ISD::EntryToken:
12272       // Entry token is ideal chain operand, but handled in FindBetterChain.
12273       break;
12274
12275     case ISD::LOAD:
12276     case ISD::STORE: {
12277       // Get alias information for Chain.
12278       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12279           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12280
12281       // If chain is alias then stop here.
12282       if (!(IsLoad && IsOpLoad) &&
12283           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12284         Aliases.push_back(Chain);
12285       } else {
12286         // Look further up the chain.
12287         Chains.push_back(Chain.getOperand(0));
12288         ++Depth;
12289       }
12290       break;
12291     }
12292
12293     case ISD::TokenFactor:
12294       // We have to check each of the operands of the token factor for "small"
12295       // token factors, so we queue them up.  Adding the operands to the queue
12296       // (stack) in reverse order maintains the original order and increases the
12297       // likelihood that getNode will find a matching token factor (CSE.)
12298       if (Chain.getNumOperands() > 16) {
12299         Aliases.push_back(Chain);
12300         break;
12301       }
12302       for (unsigned n = Chain.getNumOperands(); n;)
12303         Chains.push_back(Chain.getOperand(--n));
12304       ++Depth;
12305       break;
12306
12307     default:
12308       // For all other instructions we will just have to take what we can get.
12309       Aliases.push_back(Chain);
12310       break;
12311     }
12312   }
12313
12314   // We need to be careful here to also search for aliases through the
12315   // value operand of a store, etc. Consider the following situation:
12316   //   Token1 = ...
12317   //   L1 = load Token1, %52
12318   //   S1 = store Token1, L1, %51
12319   //   L2 = load Token1, %52+8
12320   //   S2 = store Token1, L2, %51+8
12321   //   Token2 = Token(S1, S2)
12322   //   L3 = load Token2, %53
12323   //   S3 = store Token2, L3, %52
12324   //   L4 = load Token2, %53+8
12325   //   S4 = store Token2, L4, %52+8
12326   // If we search for aliases of S3 (which loads address %52), and we look
12327   // only through the chain, then we'll miss the trivial dependence on L1
12328   // (which also loads from %52). We then might change all loads and
12329   // stores to use Token1 as their chain operand, which could result in
12330   // copying %53 into %52 before copying %52 into %51 (which should
12331   // happen first).
12332   //
12333   // The problem is, however, that searching for such data dependencies
12334   // can become expensive, and the cost is not directly related to the
12335   // chain depth. Instead, we'll rule out such configurations here by
12336   // insisting that we've visited all chain users (except for users
12337   // of the original chain, which is not necessary). When doing this,
12338   // we need to look through nodes we don't care about (otherwise, things
12339   // like register copies will interfere with trivial cases).
12340
12341   SmallVector<const SDNode *, 16> Worklist;
12342   for (const SDNode *N : Visited)
12343     if (N != OriginalChain.getNode())
12344       Worklist.push_back(N);
12345
12346   while (!Worklist.empty()) {
12347     const SDNode *M = Worklist.pop_back_val();
12348
12349     // We have already visited M, and want to make sure we've visited any uses
12350     // of M that we care about. For uses that we've not visisted, and don't
12351     // care about, queue them to the worklist.
12352
12353     for (SDNode::use_iterator UI = M->use_begin(),
12354          UIE = M->use_end(); UI != UIE; ++UI)
12355       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12356         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12357           // We've not visited this use, and we care about it (it could have an
12358           // ordering dependency with the original node).
12359           Aliases.clear();
12360           Aliases.push_back(OriginalChain);
12361           return;
12362         }
12363
12364         // We've not visited this use, but we don't care about it. Mark it as
12365         // visited and enqueue it to the worklist.
12366         Worklist.push_back(*UI);
12367       }
12368   }
12369 }
12370
12371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12372 /// (aliasing node.)
12373 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12374   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12375
12376   // Accumulate all the aliases to this node.
12377   GatherAllAliases(N, OldChain, Aliases);
12378
12379   // If no operands then chain to entry token.
12380   if (Aliases.size() == 0)
12381     return DAG.getEntryNode();
12382
12383   // If a single operand then chain to it.  We don't need to revisit it.
12384   if (Aliases.size() == 1)
12385     return Aliases[0];
12386
12387   // Construct a custom tailored token factor.
12388   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12389 }
12390
12391 /// This is the entry point for the file.
12392 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12393                            CodeGenOpt::Level OptLevel) {
12394   /// This is the main entry point to this class.
12395   DAGCombiner(*this, AA, OptLevel).Run(Level);
12396 }