9f4ced3660af5aab5fa18be53d24fe9171482319
[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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitFP_TO_FP16(SDNode *N);
311
312     SDValue visitFADDForFMACombine(SDNode *N);
313     SDValue visitFSUBForFMACombine(SDNode *N);
314
315     SDValue XformToShuffleWithZero(SDNode *N);
316     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
317
318     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
319
320     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324                              SDValue N3, ISD::CondCode CC,
325                              bool NotExtCompare = false);
326     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327                           SDLoc DL, bool foldBooleans = true);
328
329     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
330                            SDValue &CC) const;
331     bool isOneUseSetCC(SDValue N) const;
332
333     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
334                                          unsigned HiOp);
335     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336     SDValue CombineExtLoad(SDNode *N);
337     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338     SDValue BuildSDIV(SDNode *N);
339     SDValue BuildSDIVPow2(SDNode *N);
340     SDValue BuildUDIV(SDNode *N);
341     SDValue BuildReciprocalEstimate(SDValue Op);
342     SDValue BuildRsqrtEstimate(SDValue Op);
343     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346                                bool DemandHighBits = true);
347     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349                               SDValue InnerPos, SDValue InnerNeg,
350                               unsigned PosOpcode, unsigned NegOpcode,
351                               SDLoc DL);
352     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353     SDValue ReduceLoadWidth(SDNode *N);
354     SDValue ReduceLoadOpStoreWidth(SDNode *N);
355     SDValue TransformFPLoadStorePair(SDNode *N);
356     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
358
359     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
360
361     /// Walk up chain skipping non-aliasing memory nodes,
362     /// looking for aliasing nodes and adding them to the Aliases vector.
363     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364                           SmallVectorImpl<SDValue> &Aliases);
365
366     /// Return true if there is any possibility that the two addresses overlap.
367     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
368
369     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370     /// chain (aliasing node.)
371     SDValue FindBetterChain(SDNode *N, SDValue Chain);
372
373     /// Holds a pointer to an LSBaseSDNode as well as information on where it
374     /// is located in a sequence of memory operations connected by a chain.
375     struct MemOpLink {
376       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378       // Ptr to the mem node.
379       LSBaseSDNode *MemNode;
380       // Offset from the base ptr.
381       int64_t OffsetFromBase;
382       // What is the sequence number of this mem node.
383       // Lowest mem operand in the DAG starts at zero.
384       unsigned SequenceNum;
385     };
386
387     /// This is a helper function for MergeConsecutiveStores. When the source
388     /// elements of the consecutive stores are all constants or all extracted
389     /// vector elements, try to merge them into one larger store.
390     /// \return True if a merged store was created.
391     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392                                          EVT MemVT, unsigned NumElem,
393                                          bool IsConstantSrc, bool UseVector);
394
395     /// Merge consecutive store operations into a wide store.
396     /// This optimization uses wide integers or vectors when possible.
397     /// \return True if some memory operations were changed.
398     bool MergeConsecutiveStores(StoreSDNode *N);
399
400     /// \brief Try to transform a truncation where C is a constant:
401     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
402     ///
403     /// \p N needs to be a truncation and its first operand an AND. Other
404     /// requirements are checked by the function (e.g. that trunc is
405     /// single-use) and if missed an empty SDValue is returned.
406     SDValue distributeTruncateThroughAnd(SDNode *N);
407
408   public:
409     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412       auto *F = DAG.getMachineFunction().getFunction();
413       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414                     F->hasFnAttribute(Attribute::MinSize);
415     }
416
417     /// Runs the dag combiner on all nodes in the work list
418     void Run(CombineLevel AtLevel);
419
420     SelectionDAG &getDAG() const { return DAG; }
421
422     /// Returns a type large enough to hold any valid shift amount - before type
423     /// legalization these can be huge.
424     EVT getShiftAmountTy(EVT LHSTy) {
425       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426       if (LHSTy.isVector())
427         return LHSTy;
428       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429                         : TLI.getPointerTy();
430     }
431
432     /// This method returns true if we are running before type legalization or
433     /// if the specified VT is legal.
434     bool isTypeLegal(const EVT &VT) {
435       if (!LegalTypes) return true;
436       return TLI.isTypeLegal(VT);
437     }
438
439     /// Convenience wrapper around TargetLowering::getSetCCResultType
440     EVT getSetCCResultType(EVT VT) const {
441       return TLI.getSetCCResultType(*DAG.getContext(), VT);
442     }
443   };
444 }
445
446
447 namespace {
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
451   DAGCombiner &DC;
452 public:
453   explicit WorklistRemover(DAGCombiner &dc)
454     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
455
456   void NodeDeleted(SDNode *N, SDNode *E) override {
457     DC.removeFromWorklist(N);
458   }
459 };
460 }
461
462 //===----------------------------------------------------------------------===//
463 //  TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
465
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->AddToWorklist(N);
468 }
469
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471   ((DAGCombiner*)DC)->removeFromWorklist(N);
472 }
473
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
477 }
478
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 }
483
484
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
488 }
489
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
493 }
494
495 //===----------------------------------------------------------------------===//
496 // Helper Functions
497 //===----------------------------------------------------------------------===//
498
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500   removeFromWorklist(N);
501
502   // If the operands of this node are only used by the node, they will now be
503   // dead. Make sure to re-visit them and recursively delete dead nodes.
504   for (const SDValue &Op : N->ops())
505     // For an operand generating multiple values, one of the values may
506     // become dead allowing further simplification (e.g. split index
507     // arithmetic from an indexed load).
508     if (Op->hasOneUse() || Op->getNumValues() > 1)
509       AddToWorklist(Op.getNode());
510
511   DAG.DeleteNode(N);
512 }
513
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518                                const TargetLowering &TLI,
519                                const TargetOptions *Options,
520                                unsigned Depth = 0) {
521   // fneg is removable even if it has multiple uses.
522   if (Op.getOpcode() == ISD::FNEG) return 2;
523
524   // Don't allow anything with multiple uses.
525   if (!Op.hasOneUse()) return 0;
526
527   // Don't recurse exponentially.
528   if (Depth > 6) return 0;
529
530   switch (Op.getOpcode()) {
531   default: return false;
532   case ISD::ConstantFP:
533     // Don't invert constant FP values after legalize.  The negated constant
534     // isn't necessarily legal.
535     return LegalOperations ? 0 : 1;
536   case ISD::FADD:
537     // FIXME: determine better conditions for this xform.
538     if (!Options->UnsafeFPMath) return 0;
539
540     // After operation legalization, it might not be legal to create new FSUBs.
541     if (LegalOperations &&
542         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
543       return 0;
544
545     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
547                                     Options, Depth + 1))
548       return V;
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
551                               Depth + 1);
552   case ISD::FSUB:
553     // We can't turn -(A-B) into B-A when we honor signed zeros.
554     if (!Options->UnsafeFPMath) return 0;
555
556     // fold (fneg (fsub A, B)) -> (fsub B, A)
557     return 1;
558
559   case ISD::FMUL:
560   case ISD::FDIV:
561     if (Options->HonorSignDependentRoundingFPMath()) return 0;
562
563     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570
571   case ISD::FP_EXTEND:
572   case ISD::FP_ROUND:
573   case ISD::FSIN:
574     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575                               Depth + 1);
576   }
577 }
578
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581                                     bool LegalOperations, unsigned Depth = 0) {
582   const TargetOptions &Options = DAG.getTarget().Options;
583   // fneg is removable even if it has multiple uses.
584   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
585
586   // Don't allow anything with multiple uses.
587   assert(Op.hasOneUse() && "Unknown reuse!");
588
589   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590   switch (Op.getOpcode()) {
591   default: llvm_unreachable("Unknown code");
592   case ISD::ConstantFP: {
593     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
594     V.changeSign();
595     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
596   }
597   case ISD::FADD:
598     // FIXME: determine better conditions for this xform.
599     assert(Options.UnsafeFPMath);
600
601     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
604       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605                          GetNegatedExpression(Op.getOperand(0), DAG,
606                                               LegalOperations, Depth+1),
607                          Op.getOperand(1));
608     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610                        GetNegatedExpression(Op.getOperand(1), DAG,
611                                             LegalOperations, Depth+1),
612                        Op.getOperand(0));
613   case ISD::FSUB:
614     // We can't turn -(A-B) into B-A when we honor signed zeros.
615     assert(Options.UnsafeFPMath);
616
617     // fold (fneg (fsub 0, B)) -> B
618     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619       if (N0CFP->getValueAPF().isZero())
620         return Op.getOperand(1);
621
622     // fold (fneg (fsub A, B)) -> (fsub B, A)
623     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624                        Op.getOperand(1), Op.getOperand(0));
625
626   case ISD::FMUL:
627   case ISD::FDIV:
628     assert(!Options.HonorSignDependentRoundingFPMath());
629
630     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
633       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634                          GetNegatedExpression(Op.getOperand(0), DAG,
635                                               LegalOperations, Depth+1),
636                          Op.getOperand(1));
637
638     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
640                        Op.getOperand(0),
641                        GetNegatedExpression(Op.getOperand(1), DAG,
642                                             LegalOperations, Depth+1));
643
644   case ISD::FP_EXTEND:
645   case ISD::FSIN:
646     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647                        GetNegatedExpression(Op.getOperand(0), DAG,
648                                             LegalOperations, Depth+1));
649   case ISD::FP_ROUND:
650       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651                          GetNegatedExpression(Op.getOperand(0), DAG,
652                                               LegalOperations, Depth+1),
653                          Op.getOperand(1));
654   }
655 }
656
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
663                                     SDValue &CC) const {
664   if (N.getOpcode() == ISD::SETCC) {
665     LHS = N.getOperand(0);
666     RHS = N.getOperand(1);
667     CC  = N.getOperand(2);
668     return true;
669   }
670
671   if (N.getOpcode() != ISD::SELECT_CC ||
672       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
674     return false;
675
676   if (TLI.getBooleanContents(N.getValueType()) ==
677       TargetLowering::UndefinedBooleanContent)
678     return false;
679
680   LHS = N.getOperand(0);
681   RHS = N.getOperand(1);
682   CC  = N.getOperand(4);
683   return true;
684 }
685
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
690   SDValue N0, N1, N2;
691   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692     return true;
693   return false;
694 }
695
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700   if (!C)
701     return false;
702
703   APInt SplatUndef;
704   unsigned SplatBitSize;
705   bool HasAnyUndefs;
706   EVT EltVT = N->getValueType(0).getVectorElementType();
707   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
708                              HasAnyUndefs) &&
709           EltVT.getSizeInBits() >= SplatBitSize);
710 }
711
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715   if (isa<ConstantSDNode>(N))
716     return N.getNode();
717   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718     return N.getNode();
719   return nullptr;
720 }
721
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725   if (isa<ConstantFPSDNode>(N))
726     return N.getNode();
727   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728     return N.getNode();
729   return nullptr;
730 }
731
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
733 // int.
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
736     return CN;
737
738   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739     BitVector UndefElements;
740     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
741
742     // BuildVectors can truncate their operands. Ignore that case here.
743     // FIXME: We blindly ignore splats which include undef which is overly
744     // pessimistic.
745     if (CN && UndefElements.none() &&
746         CN->getValueType(0) == N.getValueType().getScalarType())
747       return CN;
748   }
749
750   return nullptr;
751 }
752
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
754 // float.
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
757     return CN;
758
759   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760     BitVector UndefElements;
761     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
762
763     if (CN && UndefElements.none())
764       return CN;
765   }
766
767   return nullptr;
768 }
769
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771                                     SDValue N0, SDValue N1) {
772   EVT VT = N0.getValueType();
773   if (N0.getOpcode() == Opc) {
774     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
778           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
779         return SDValue();
780       }
781       if (N0.hasOneUse()) {
782         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
783         // use
784         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785         if (!OpNode.getNode())
786           return SDValue();
787         AddToWorklist(OpNode.getNode());
788         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
789       }
790     }
791   }
792
793   if (N1.getOpcode() == Opc) {
794     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
798           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N1.hasOneUse()) {
802         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
809       }
810     }
811   }
812
813   return SDValue();
814 }
815
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
817                                bool AddTo) {
818   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
819   ++NodesCombined;
820   DEBUG(dbgs() << "\nReplacing.1 ";
821         N->dump(&DAG);
822         dbgs() << "\nWith: ";
823         To[0].getNode()->dump(&DAG);
824         dbgs() << " and " << NumTo-1 << " other values\n");
825   for (unsigned i = 0, e = NumTo; i != e; ++i)
826     assert((!To[i].getNode() ||
827             N->getValueType(i) == To[i].getValueType()) &&
828            "Cannot combine value to value of different type!");
829
830   WorklistRemover DeadNodes(*this);
831   DAG.ReplaceAllUsesWith(N, To);
832   if (AddTo) {
833     // Push the new nodes and any users onto the worklist
834     for (unsigned i = 0, e = NumTo; i != e; ++i) {
835       if (To[i].getNode()) {
836         AddToWorklist(To[i].getNode());
837         AddUsersToWorklist(To[i].getNode());
838       }
839     }
840   }
841
842   // Finally, if the node is now dead, remove it from the graph.  The node
843   // may not be dead if the replacement process recursively simplified to
844   // something else needing this node.
845   if (N->use_empty())
846     deleteAndRecombine(N);
847   return SDValue(N, 0);
848 }
849
850 void DAGCombiner::
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852   // Replace all uses.  If any nodes become isomorphic to other nodes and
853   // are deleted, make sure to remove them from our worklist.
854   WorklistRemover DeadNodes(*this);
855   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
856
857   // Push the new node and any (possibly new) users onto the worklist.
858   AddToWorklist(TLO.New.getNode());
859   AddUsersToWorklist(TLO.New.getNode());
860
861   // Finally, if the node is now dead, remove it from the graph.  The node
862   // may not be dead if the replacement process recursively simplified to
863   // something else needing this node.
864   if (TLO.Old.getNode()->use_empty())
865     deleteAndRecombine(TLO.Old.getNode());
866 }
867
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872   APInt KnownZero, KnownOne;
873   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
874     return false;
875
876   // Revisit the node.
877   AddToWorklist(Op.getNode());
878
879   // Replace the old value with the new one.
880   ++NodesCombined;
881   DEBUG(dbgs() << "\nReplacing.2 ";
882         TLO.Old.getNode()->dump(&DAG);
883         dbgs() << "\nWith: ";
884         TLO.New.getNode()->dump(&DAG);
885         dbgs() << '\n');
886
887   CommitTargetLoweringOpt(TLO);
888   return true;
889 }
890
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
892   SDLoc dl(Load);
893   EVT VT = Load->getValueType(0);
894   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
895
896   DEBUG(dbgs() << "\nReplacing.9 ";
897         Load->dump(&DAG);
898         dbgs() << "\nWith: ";
899         Trunc.getNode()->dump(&DAG);
900         dbgs() << '\n');
901   WorklistRemover DeadNodes(*this);
902   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904   deleteAndRecombine(Load);
905   AddToWorklist(Trunc.getNode());
906 }
907
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
909   Replace = false;
910   SDLoc dl(Op);
911   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912     EVT MemVT = LD->getMemoryVT();
913     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
915                                                        : ISD::EXTLOAD)
916       : LD->getExtensionType();
917     Replace = true;
918     return DAG.getExtLoad(ExtType, dl, PVT,
919                           LD->getChain(), LD->getBasePtr(),
920                           MemVT, LD->getMemOperand());
921   }
922
923   unsigned Opc = Op.getOpcode();
924   switch (Opc) {
925   default: break;
926   case ISD::AssertSext:
927     return DAG.getNode(ISD::AssertSext, dl, PVT,
928                        SExtPromoteOperand(Op.getOperand(0), PVT),
929                        Op.getOperand(1));
930   case ISD::AssertZext:
931     return DAG.getNode(ISD::AssertZext, dl, PVT,
932                        ZExtPromoteOperand(Op.getOperand(0), PVT),
933                        Op.getOperand(1));
934   case ISD::Constant: {
935     unsigned ExtOpc =
936       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937     return DAG.getNode(ExtOpc, dl, PVT, Op);
938   }
939   }
940
941   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
942     return SDValue();
943   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
944 }
945
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
948     return SDValue();
949   EVT OldVT = Op.getValueType();
950   SDLoc dl(Op);
951   bool Replace = false;
952   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953   if (!NewOp.getNode())
954     return SDValue();
955   AddToWorklist(NewOp.getNode());
956
957   if (Replace)
958     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960                      DAG.getValueType(OldVT));
961 }
962
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964   EVT OldVT = Op.getValueType();
965   SDLoc dl(Op);
966   bool Replace = false;
967   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968   if (!NewOp.getNode())
969     return SDValue();
970   AddToWorklist(NewOp.getNode());
971
972   if (Replace)
973     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
975 }
976
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981   if (!LegalOperations)
982     return SDValue();
983
984   EVT VT = Op.getValueType();
985   if (VT.isVector() || !VT.isInteger())
986     return SDValue();
987
988   // If operation type is 'undesirable', e.g. i16 on x86, consider
989   // promoting it.
990   unsigned Opc = Op.getOpcode();
991   if (TLI.isTypeDesirableForOp(Opc, VT))
992     return SDValue();
993
994   EVT PVT = VT;
995   // Consult target whether it is a good idea to promote this operation and
996   // what's the right type to promote it to.
997   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998     assert(PVT != VT && "Don't know what type to promote to!");
999
1000     bool Replace0 = false;
1001     SDValue N0 = Op.getOperand(0);
1002     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1003     if (!NN0.getNode())
1004       return SDValue();
1005
1006     bool Replace1 = false;
1007     SDValue N1 = Op.getOperand(1);
1008     SDValue NN1;
1009     if (N0 == N1)
1010       NN1 = NN0;
1011     else {
1012       NN1 = PromoteOperand(N1, PVT, Replace1);
1013       if (!NN1.getNode())
1014         return SDValue();
1015     }
1016
1017     AddToWorklist(NN0.getNode());
1018     if (NN1.getNode())
1019       AddToWorklist(NN1.getNode());
1020
1021     if (Replace0)
1022       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1023     if (Replace1)
1024       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1025
1026     DEBUG(dbgs() << "\nPromoting ";
1027           Op.getNode()->dump(&DAG));
1028     SDLoc dl(Op);
1029     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1031   }
1032   return SDValue();
1033 }
1034
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057
1058     bool Replace = false;
1059     SDValue N0 = Op.getOperand(0);
1060     if (Opc == ISD::SRA)
1061       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062     else if (Opc == ISD::SRL)
1063       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1064     else
1065       N0 = PromoteOperand(N0, PVT, Replace);
1066     if (!N0.getNode())
1067       return SDValue();
1068
1069     AddToWorklist(N0.getNode());
1070     if (Replace)
1071       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1078   }
1079   return SDValue();
1080 }
1081
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101     // fold (aext (aext x)) -> (aext x)
1102     // fold (aext (zext x)) -> (zext x)
1103     // fold (aext (sext x)) -> (sext x)
1104     DEBUG(dbgs() << "\nPromoting ";
1105           Op.getNode()->dump(&DAG));
1106     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1107   }
1108   return SDValue();
1109 }
1110
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112   if (!LegalOperations)
1113     return false;
1114
1115   EVT VT = Op.getValueType();
1116   if (VT.isVector() || !VT.isInteger())
1117     return false;
1118
1119   // If operation type is 'undesirable', e.g. i16 on x86, consider
1120   // promoting it.
1121   unsigned Opc = Op.getOpcode();
1122   if (TLI.isTypeDesirableForOp(Opc, VT))
1123     return false;
1124
1125   EVT PVT = VT;
1126   // Consult target whether it is a good idea to promote this operation and
1127   // what's the right type to promote it to.
1128   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129     assert(PVT != VT && "Don't know what type to promote to!");
1130
1131     SDLoc dl(Op);
1132     SDNode *N = Op.getNode();
1133     LoadSDNode *LD = cast<LoadSDNode>(N);
1134     EVT MemVT = LD->getMemoryVT();
1135     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1137                                                        : ISD::EXTLOAD)
1138       : LD->getExtensionType();
1139     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140                                    LD->getChain(), LD->getBasePtr(),
1141                                    MemVT, LD->getMemOperand());
1142     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1143
1144     DEBUG(dbgs() << "\nPromoting ";
1145           N->dump(&DAG);
1146           dbgs() << "\nTo: ";
1147           Result.getNode()->dump(&DAG);
1148           dbgs() << '\n');
1149     WorklistRemover DeadNodes(*this);
1150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152     deleteAndRecombine(N);
1153     AddToWorklist(Result.getNode());
1154     return true;
1155   }
1156   return false;
1157 }
1158
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1161 ///
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166   if (!N->use_empty())
1167     return false;
1168
1169   SmallSetVector<SDNode *, 16> Nodes;
1170   Nodes.insert(N);
1171   do {
1172     N = Nodes.pop_back_val();
1173     if (!N)
1174       continue;
1175
1176     if (N->use_empty()) {
1177       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178         Nodes.insert(N->getOperand(i).getNode());
1179
1180       removeFromWorklist(N);
1181       DAG.DeleteNode(N);
1182     } else {
1183       AddToWorklist(N);
1184     }
1185   } while (!Nodes.empty());
1186   return true;
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //  Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1192
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194   // set the instance variables, so that the various visit routines may use it.
1195   Level = AtLevel;
1196   LegalOperations = Level >= AfterLegalizeVectorOps;
1197   LegalTypes = Level >= AfterLegalizeTypes;
1198
1199   // Add all the dag nodes to the worklist.
1200   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201        E = DAG.allnodes_end(); I != E; ++I)
1202     AddToWorklist(I);
1203
1204   // Create a dummy node (which is not added to allnodes), that adds a reference
1205   // to the root node, preventing it from being deleted, and tracking any
1206   // changes of the root.
1207   HandleSDNode Dummy(DAG.getRoot());
1208
1209   // while the worklist isn't empty, find a node and
1210   // try and combine it.
1211   while (!WorklistMap.empty()) {
1212     SDNode *N;
1213     // The Worklist holds the SDNodes in order, but it may contain null entries.
1214     do {
1215       N = Worklist.pop_back_val();
1216     } while (!N);
1217
1218     bool GoodWorklistEntry = WorklistMap.erase(N);
1219     (void)GoodWorklistEntry;
1220     assert(GoodWorklistEntry &&
1221            "Found a worklist entry without a corresponding map entry!");
1222
1223     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1224     // N is deleted from the DAG, since they too may now be dead or may have a
1225     // reduced number of uses, allowing other xforms.
1226     if (recursivelyDeleteUnusedNodes(N))
1227       continue;
1228
1229     WorklistRemover DeadNodes(*this);
1230
1231     // If this combine is running after legalizing the DAG, re-legalize any
1232     // nodes pulled off the worklist.
1233     if (Level == AfterLegalizeDAG) {
1234       SmallSetVector<SDNode *, 16> UpdatedNodes;
1235       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1236
1237       for (SDNode *LN : UpdatedNodes) {
1238         AddToWorklist(LN);
1239         AddUsersToWorklist(LN);
1240       }
1241       if (!NIsValid)
1242         continue;
1243     }
1244
1245     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1246
1247     // Add any operands of the new node which have not yet been combined to the
1248     // worklist as well. Because the worklist uniques things already, this
1249     // won't repeatedly process the same operand.
1250     CombinedNodes.insert(N);
1251     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253         AddToWorklist(N->getOperand(i).getNode());
1254
1255     SDValue RV = combine(N);
1256
1257     if (!RV.getNode())
1258       continue;
1259
1260     ++NodesCombined;
1261
1262     // If we get back the same node we passed in, rather than a new node or
1263     // zero, we know that the node must have defined multiple values and
1264     // CombineTo was used.  Since CombineTo takes care of the worklist
1265     // mechanics for us, we have no work to do in this case.
1266     if (RV.getNode() == N)
1267       continue;
1268
1269     assert(N->getOpcode() != ISD::DELETED_NODE &&
1270            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271            "Node was deleted but visit returned new node!");
1272
1273     DEBUG(dbgs() << " ... into: ";
1274           RV.getNode()->dump(&DAG));
1275
1276     // Transfer debug value.
1277     DAG.TransferDbgValues(SDValue(N, 0), RV);
1278     if (N->getNumValues() == RV.getNode()->getNumValues())
1279       DAG.ReplaceAllUsesWith(N, RV.getNode());
1280     else {
1281       assert(N->getValueType(0) == RV.getValueType() &&
1282              N->getNumValues() == 1 && "Type mismatch");
1283       SDValue OpV = RV;
1284       DAG.ReplaceAllUsesWith(N, &OpV);
1285     }
1286
1287     // Push the new node and any users onto the worklist
1288     AddToWorklist(RV.getNode());
1289     AddUsersToWorklist(RV.getNode());
1290
1291     // Finally, if the node is now dead, remove it from the graph.  The node
1292     // may not be dead if the replacement process recursively simplified to
1293     // something else needing this node. This will also take care of adding any
1294     // operands which have lost a user to the worklist.
1295     recursivelyDeleteUnusedNodes(N);
1296   }
1297
1298   // If the root changed (e.g. it was a dead load, update the root).
1299   DAG.setRoot(Dummy.getValue());
1300   DAG.RemoveDeadNodes();
1301 }
1302
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304   switch (N->getOpcode()) {
1305   default: break;
1306   case ISD::TokenFactor:        return visitTokenFactor(N);
1307   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1308   case ISD::ADD:                return visitADD(N);
1309   case ISD::SUB:                return visitSUB(N);
1310   case ISD::ADDC:               return visitADDC(N);
1311   case ISD::SUBC:               return visitSUBC(N);
1312   case ISD::ADDE:               return visitADDE(N);
1313   case ISD::SUBE:               return visitSUBE(N);
1314   case ISD::MUL:                return visitMUL(N);
1315   case ISD::SDIV:               return visitSDIV(N);
1316   case ISD::UDIV:               return visitUDIV(N);
1317   case ISD::SREM:               return visitSREM(N);
1318   case ISD::UREM:               return visitUREM(N);
1319   case ISD::MULHU:              return visitMULHU(N);
1320   case ISD::MULHS:              return visitMULHS(N);
1321   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1322   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1323   case ISD::SMULO:              return visitSMULO(N);
1324   case ISD::UMULO:              return visitUMULO(N);
1325   case ISD::SDIVREM:            return visitSDIVREM(N);
1326   case ISD::UDIVREM:            return visitUDIVREM(N);
1327   case ISD::AND:                return visitAND(N);
1328   case ISD::OR:                 return visitOR(N);
1329   case ISD::XOR:                return visitXOR(N);
1330   case ISD::SHL:                return visitSHL(N);
1331   case ISD::SRA:                return visitSRA(N);
1332   case ISD::SRL:                return visitSRL(N);
1333   case ISD::ROTR:
1334   case ISD::ROTL:               return visitRotate(N);
1335   case ISD::CTLZ:               return visitCTLZ(N);
1336   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1337   case ISD::CTTZ:               return visitCTTZ(N);
1338   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1339   case ISD::CTPOP:              return visitCTPOP(N);
1340   case ISD::SELECT:             return visitSELECT(N);
1341   case ISD::VSELECT:            return visitVSELECT(N);
1342   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1343   case ISD::SETCC:              return visitSETCC(N);
1344   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1345   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1346   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1347   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1348   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1349   case ISD::BITCAST:            return visitBITCAST(N);
1350   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1351   case ISD::FADD:               return visitFADD(N);
1352   case ISD::FSUB:               return visitFSUB(N);
1353   case ISD::FMUL:               return visitFMUL(N);
1354   case ISD::FMA:                return visitFMA(N);
1355   case ISD::FDIV:               return visitFDIV(N);
1356   case ISD::FREM:               return visitFREM(N);
1357   case ISD::FSQRT:              return visitFSQRT(N);
1358   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1359   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1360   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1361   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1362   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1363   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1364   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1365   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1366   case ISD::FNEG:               return visitFNEG(N);
1367   case ISD::FABS:               return visitFABS(N);
1368   case ISD::FFLOOR:             return visitFFLOOR(N);
1369   case ISD::FMINNUM:            return visitFMINNUM(N);
1370   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1371   case ISD::FCEIL:              return visitFCEIL(N);
1372   case ISD::FTRUNC:             return visitFTRUNC(N);
1373   case ISD::BRCOND:             return visitBRCOND(N);
1374   case ISD::BR_CC:              return visitBR_CC(N);
1375   case ISD::LOAD:               return visitLOAD(N);
1376   case ISD::STORE:              return visitSTORE(N);
1377   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1378   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1380   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1381   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1382   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1383   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1384   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1385   case ISD::MLOAD:              return visitMLOAD(N);
1386   case ISD::MSTORE:             return visitMSTORE(N);
1387   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1388   }
1389   return SDValue();
1390 }
1391
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393   SDValue RV = visit(N);
1394
1395   // If nothing happened, try a target-specific DAG combine.
1396   if (!RV.getNode()) {
1397     assert(N->getOpcode() != ISD::DELETED_NODE &&
1398            "Node was deleted but visit returned NULL!");
1399
1400     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1402
1403       // Expose the DAG combiner to the target combiner impls.
1404       TargetLowering::DAGCombinerInfo
1405         DagCombineInfo(DAG, Level, false, this);
1406
1407       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1408     }
1409   }
1410
1411   // If nothing happened still, try promoting the operation.
1412   if (!RV.getNode()) {
1413     switch (N->getOpcode()) {
1414     default: break;
1415     case ISD::ADD:
1416     case ISD::SUB:
1417     case ISD::MUL:
1418     case ISD::AND:
1419     case ISD::OR:
1420     case ISD::XOR:
1421       RV = PromoteIntBinOp(SDValue(N, 0));
1422       break;
1423     case ISD::SHL:
1424     case ISD::SRA:
1425     case ISD::SRL:
1426       RV = PromoteIntShiftOp(SDValue(N, 0));
1427       break;
1428     case ISD::SIGN_EXTEND:
1429     case ISD::ZERO_EXTEND:
1430     case ISD::ANY_EXTEND:
1431       RV = PromoteExtend(SDValue(N, 0));
1432       break;
1433     case ISD::LOAD:
1434       if (PromoteLoad(SDValue(N, 0)))
1435         RV = SDValue(N, 0);
1436       break;
1437     }
1438   }
1439
1440   // If N is a commutative binary node, try commuting it to enable more
1441   // sdisel CSE.
1442   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443       N->getNumValues() == 1) {
1444     SDValue N0 = N->getOperand(0);
1445     SDValue N1 = N->getOperand(1);
1446
1447     // Constant operands are canonicalized to RHS.
1448     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449       SDValue Ops[] = {N1, N0};
1450       SDNode *CSENode;
1451       if (const BinaryWithFlagsSDNode *BinNode =
1452               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1454                                       BinNode->Flags.hasNoUnsignedWrap(),
1455                                       BinNode->Flags.hasNoSignedWrap(),
1456                                       BinNode->Flags.hasExact());
1457       } else {
1458         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1459       }
1460       if (CSENode)
1461         return SDValue(CSENode, 0);
1462     }
1463   }
1464
1465   return RV;
1466 }
1467
1468 /// Given a node, return its input chain if it has one, otherwise return a null
1469 /// sd operand.
1470 static SDValue getInputChainForNode(SDNode *N) {
1471   if (unsigned NumOps = N->getNumOperands()) {
1472     if (N->getOperand(0).getValueType() == MVT::Other)
1473       return N->getOperand(0);
1474     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1475       return N->getOperand(NumOps-1);
1476     for (unsigned i = 1; i < NumOps-1; ++i)
1477       if (N->getOperand(i).getValueType() == MVT::Other)
1478         return N->getOperand(i);
1479   }
1480   return SDValue();
1481 }
1482
1483 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1484   // If N has two operands, where one has an input chain equal to the other,
1485   // the 'other' chain is redundant.
1486   if (N->getNumOperands() == 2) {
1487     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1488       return N->getOperand(0);
1489     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1490       return N->getOperand(1);
1491   }
1492
1493   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1494   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1495   SmallPtrSet<SDNode*, 16> SeenOps;
1496   bool Changed = false;             // If we should replace this token factor.
1497
1498   // Start out with this token factor.
1499   TFs.push_back(N);
1500
1501   // Iterate through token factors.  The TFs grows when new token factors are
1502   // encountered.
1503   for (unsigned i = 0; i < TFs.size(); ++i) {
1504     SDNode *TF = TFs[i];
1505
1506     // Check each of the operands.
1507     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1508       SDValue Op = TF->getOperand(i);
1509
1510       switch (Op.getOpcode()) {
1511       case ISD::EntryToken:
1512         // Entry tokens don't need to be added to the list. They are
1513         // redundant.
1514         Changed = true;
1515         break;
1516
1517       case ISD::TokenFactor:
1518         if (Op.hasOneUse() &&
1519             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1520           // Queue up for processing.
1521           TFs.push_back(Op.getNode());
1522           // Clean up in case the token factor is removed.
1523           AddToWorklist(Op.getNode());
1524           Changed = true;
1525           break;
1526         }
1527         // Fall thru
1528
1529       default:
1530         // Only add if it isn't already in the list.
1531         if (SeenOps.insert(Op.getNode()).second)
1532           Ops.push_back(Op);
1533         else
1534           Changed = true;
1535         break;
1536       }
1537     }
1538   }
1539
1540   SDValue Result;
1541
1542   // If we've changed things around then replace token factor.
1543   if (Changed) {
1544     if (Ops.empty()) {
1545       // The entry token is the only possible outcome.
1546       Result = DAG.getEntryNode();
1547     } else {
1548       // New and improved token factor.
1549       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1550     }
1551
1552     // Add users to worklist if AA is enabled, since it may introduce
1553     // a lot of new chained token factors while removing memory deps.
1554     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1555       : DAG.getSubtarget().useAA();
1556     return CombineTo(N, Result, UseAA /*add to worklist*/);
1557   }
1558
1559   return Result;
1560 }
1561
1562 /// MERGE_VALUES can always be eliminated.
1563 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1564   WorklistRemover DeadNodes(*this);
1565   // Replacing results may cause a different MERGE_VALUES to suddenly
1566   // be CSE'd with N, and carry its uses with it. Iterate until no
1567   // uses remain, to ensure that the node can be safely deleted.
1568   // First add the users of this node to the work list so that they
1569   // can be tried again once they have new operands.
1570   AddUsersToWorklist(N);
1571   do {
1572     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1573       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1574   } while (!N->use_empty());
1575   deleteAndRecombine(N);
1576   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1577 }
1578
1579 SDValue DAGCombiner::visitADD(SDNode *N) {
1580   SDValue N0 = N->getOperand(0);
1581   SDValue N1 = N->getOperand(1);
1582   EVT VT = N0.getValueType();
1583
1584   // fold vector ops
1585   if (VT.isVector()) {
1586     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1587       return FoldedVOp;
1588
1589     // fold (add x, 0) -> x, vector edition
1590     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591       return N0;
1592     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1593       return N1;
1594   }
1595
1596   // fold (add x, undef) -> undef
1597   if (N0.getOpcode() == ISD::UNDEF)
1598     return N0;
1599   if (N1.getOpcode() == ISD::UNDEF)
1600     return N1;
1601   // fold (add c1, c2) -> c1+c2
1602   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604   if (N0C && N1C)
1605     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1606   // canonicalize constant to RHS
1607   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1608      !isConstantIntBuildVectorOrConstantInt(N1))
1609     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1610   // fold (add x, 0) -> x
1611   if (N1C && N1C->isNullValue())
1612     return N0;
1613   // fold (add Sym, c) -> Sym+c
1614   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1615     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1616         GA->getOpcode() == ISD::GlobalAddress)
1617       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618                                   GA->getOffset() +
1619                                     (uint64_t)N1C->getSExtValue());
1620   // fold ((c1-A)+c2) -> (c1+c2)-A
1621   if (N1C && N0.getOpcode() == ISD::SUB)
1622     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1623       SDLoc DL(N);
1624       return DAG.getNode(ISD::SUB, DL, VT,
1625                          DAG.getConstant(N1C->getAPIntValue()+
1626                                          N0C->getAPIntValue(), DL, VT),
1627                          N0.getOperand(1));
1628     }
1629   // reassociate add
1630   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1631     return RADD;
1632   // fold ((0-A) + B) -> B-A
1633   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1634       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1635     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1636   // fold (A + (0-B)) -> A-B
1637   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1638       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1640   // fold (A+(B-A)) -> B
1641   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1642     return N1.getOperand(0);
1643   // fold ((B-A)+A) -> B
1644   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1645     return N0.getOperand(0);
1646   // fold (A+(B-(A+C))) to (B-C)
1647   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1648       N0 == N1.getOperand(1).getOperand(0))
1649     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1650                        N1.getOperand(1).getOperand(1));
1651   // fold (A+(B-(C+A))) to (B-C)
1652   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1653       N0 == N1.getOperand(1).getOperand(1))
1654     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1655                        N1.getOperand(1).getOperand(0));
1656   // fold (A+((B-A)+or-C)) to (B+or-C)
1657   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1658       N1.getOperand(0).getOpcode() == ISD::SUB &&
1659       N0 == N1.getOperand(0).getOperand(1))
1660     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1661                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1662
1663   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1664   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1665     SDValue N00 = N0.getOperand(0);
1666     SDValue N01 = N0.getOperand(1);
1667     SDValue N10 = N1.getOperand(0);
1668     SDValue N11 = N1.getOperand(1);
1669
1670     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1671       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1672                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1673                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1674   }
1675
1676   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1677     return SDValue(N, 0);
1678
1679   // fold (a+b) -> (a|b) iff a and b share no bits.
1680   if (VT.isInteger() && !VT.isVector()) {
1681     APInt LHSZero, LHSOne;
1682     APInt RHSZero, RHSOne;
1683     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1684
1685     if (LHSZero.getBoolValue()) {
1686       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1687
1688       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1689       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1690       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1691         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1692           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1693       }
1694     }
1695   }
1696
1697   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1698   if (N1.getOpcode() == ISD::SHL &&
1699       N1.getOperand(0).getOpcode() == ISD::SUB)
1700     if (ConstantSDNode *C =
1701           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1702       if (C->getAPIntValue() == 0)
1703         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1704                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1705                                        N1.getOperand(0).getOperand(1),
1706                                        N1.getOperand(1)));
1707   if (N0.getOpcode() == ISD::SHL &&
1708       N0.getOperand(0).getOpcode() == ISD::SUB)
1709     if (ConstantSDNode *C =
1710           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1711       if (C->getAPIntValue() == 0)
1712         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1713                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1714                                        N0.getOperand(0).getOperand(1),
1715                                        N0.getOperand(1)));
1716
1717   if (N1.getOpcode() == ISD::AND) {
1718     SDValue AndOp0 = N1.getOperand(0);
1719     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1720     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1721     unsigned DestBits = VT.getScalarType().getSizeInBits();
1722
1723     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1724     // and similar xforms where the inner op is either ~0 or 0.
1725     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1726       SDLoc DL(N);
1727       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1728     }
1729   }
1730
1731   // add (sext i1), X -> sub X, (zext i1)
1732   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1733       N0.getOperand(0).getValueType() == MVT::i1 &&
1734       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1735     SDLoc DL(N);
1736     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1737     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1738   }
1739
1740   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1741   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1742     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1743     if (TN->getVT() == MVT::i1) {
1744       SDLoc DL(N);
1745       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1746                                  DAG.getConstant(1, DL, VT));
1747       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1748     }
1749   }
1750
1751   return SDValue();
1752 }
1753
1754 SDValue DAGCombiner::visitADDC(SDNode *N) {
1755   SDValue N0 = N->getOperand(0);
1756   SDValue N1 = N->getOperand(1);
1757   EVT VT = N0.getValueType();
1758
1759   // If the flag result is dead, turn this into an ADD.
1760   if (!N->hasAnyUseOfValue(1))
1761     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1762                      DAG.getNode(ISD::CARRY_FALSE,
1763                                  SDLoc(N), MVT::Glue));
1764
1765   // canonicalize constant to RHS.
1766   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1767   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1770
1771   // fold (addc x, 0) -> x + no carry out
1772   if (N1C && N1C->isNullValue())
1773     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1774                                         SDLoc(N), MVT::Glue));
1775
1776   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1777   APInt LHSZero, LHSOne;
1778   APInt RHSZero, RHSOne;
1779   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1780
1781   if (LHSZero.getBoolValue()) {
1782     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1783
1784     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1785     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1786     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1787       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1788                        DAG.getNode(ISD::CARRY_FALSE,
1789                                    SDLoc(N), MVT::Glue));
1790   }
1791
1792   return SDValue();
1793 }
1794
1795 SDValue DAGCombiner::visitADDE(SDNode *N) {
1796   SDValue N0 = N->getOperand(0);
1797   SDValue N1 = N->getOperand(1);
1798   SDValue CarryIn = N->getOperand(2);
1799
1800   // canonicalize constant to RHS
1801   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1803   if (N0C && !N1C)
1804     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1805                        N1, N0, CarryIn);
1806
1807   // fold (adde x, y, false) -> (addc x, y)
1808   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1809     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1810
1811   return SDValue();
1812 }
1813
1814 // Since it may not be valid to emit a fold to zero for vector initializers
1815 // check if we can before folding.
1816 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1817                              SelectionDAG &DAG,
1818                              bool LegalOperations, bool LegalTypes) {
1819   if (!VT.isVector())
1820     return DAG.getConstant(0, DL, VT);
1821   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1822     return DAG.getConstant(0, DL, VT);
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitSUB(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   EVT VT = N0.getValueType();
1830
1831   // fold vector ops
1832   if (VT.isVector()) {
1833     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1834       return FoldedVOp;
1835
1836     // fold (sub x, 0) -> x, vector edition
1837     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1838       return N0;
1839   }
1840
1841   // fold (sub x, x) -> 0
1842   // FIXME: Refactor this and xor and other similar operations together.
1843   if (N0 == N1)
1844     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1845   // fold (sub c1, c2) -> c1-c2
1846   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1848   if (N0C && N1C)
1849     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1850   // fold (sub x, c) -> (add x, -c)
1851   if (N1C) {
1852     SDLoc DL(N);
1853     return DAG.getNode(ISD::ADD, DL, VT, N0,
1854                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1855   }
1856   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1857   if (N0C && N0C->isAllOnesValue())
1858     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1859   // fold A-(A-B) -> B
1860   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1861     return N1.getOperand(1);
1862   // fold (A+B)-A -> B
1863   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1864     return N0.getOperand(1);
1865   // fold (A+B)-B -> A
1866   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1867     return N0.getOperand(0);
1868   // fold C2-(A+C1) -> (C2-C1)-A
1869   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1870     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1871   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1872     SDLoc DL(N);
1873     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1874                                    DL, VT);
1875     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1876                        N1.getOperand(0));
1877   }
1878   // fold ((A+(B+or-C))-B) -> A+or-C
1879   if (N0.getOpcode() == ISD::ADD &&
1880       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1881        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1882       N0.getOperand(1).getOperand(0) == N1)
1883     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1884                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1885   // fold ((A+(C+B))-B) -> A+C
1886   if (N0.getOpcode() == ISD::ADD &&
1887       N0.getOperand(1).getOpcode() == ISD::ADD &&
1888       N0.getOperand(1).getOperand(1) == N1)
1889     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1890                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1891   // fold ((A-(B-C))-C) -> A-B
1892   if (N0.getOpcode() == ISD::SUB &&
1893       N0.getOperand(1).getOpcode() == ISD::SUB &&
1894       N0.getOperand(1).getOperand(1) == N1)
1895     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1896                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1897
1898   // If either operand of a sub is undef, the result is undef
1899   if (N0.getOpcode() == ISD::UNDEF)
1900     return N0;
1901   if (N1.getOpcode() == ISD::UNDEF)
1902     return N1;
1903
1904   // If the relocation model supports it, consider symbol offsets.
1905   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1906     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1907       // fold (sub Sym, c) -> Sym-c
1908       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1909         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1910                                     GA->getOffset() -
1911                                       (uint64_t)N1C->getSExtValue());
1912       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1913       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1914         if (GA->getGlobal() == GB->getGlobal())
1915           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1916                                  SDLoc(N), VT);
1917     }
1918
1919   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1920   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1921     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1922     if (TN->getVT() == MVT::i1) {
1923       SDLoc DL(N);
1924       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1925                                  DAG.getConstant(1, DL, VT));
1926       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1927     }
1928   }
1929
1930   return SDValue();
1931 }
1932
1933 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1934   SDValue N0 = N->getOperand(0);
1935   SDValue N1 = N->getOperand(1);
1936   EVT VT = N0.getValueType();
1937
1938   // If the flag result is dead, turn this into an SUB.
1939   if (!N->hasAnyUseOfValue(1))
1940     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1941                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1942                                  MVT::Glue));
1943
1944   // fold (subc x, x) -> 0 + no borrow
1945   if (N0 == N1) {
1946     SDLoc DL(N);
1947     return CombineTo(N, DAG.getConstant(0, DL, VT),
1948                      DAG.getNode(ISD::CARRY_FALSE, DL,
1949                                  MVT::Glue));
1950   }
1951
1952   // fold (subc x, 0) -> x + no borrow
1953   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1954   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1955   if (N1C && N1C->isNullValue())
1956     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1957                                         MVT::Glue));
1958
1959   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1960   if (N0C && N0C->isAllOnesValue())
1961     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1962                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963                                  MVT::Glue));
1964
1965   return SDValue();
1966 }
1967
1968 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1969   SDValue N0 = N->getOperand(0);
1970   SDValue N1 = N->getOperand(1);
1971   SDValue CarryIn = N->getOperand(2);
1972
1973   // fold (sube x, y, false) -> (subc x, y)
1974   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1975     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1976
1977   return SDValue();
1978 }
1979
1980 SDValue DAGCombiner::visitMUL(SDNode *N) {
1981   SDValue N0 = N->getOperand(0);
1982   SDValue N1 = N->getOperand(1);
1983   EVT VT = N0.getValueType();
1984
1985   // fold (mul x, undef) -> 0
1986   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1987     return DAG.getConstant(0, SDLoc(N), VT);
1988
1989   bool N0IsConst = false;
1990   bool N1IsConst = false;
1991   APInt ConstValue0, ConstValue1;
1992   // fold vector ops
1993   if (VT.isVector()) {
1994     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1995       return FoldedVOp;
1996
1997     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1998     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1999   } else {
2000     N0IsConst = isa<ConstantSDNode>(N0);
2001     if (N0IsConst)
2002       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2003     N1IsConst = isa<ConstantSDNode>(N1);
2004     if (N1IsConst)
2005       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2006   }
2007
2008   // fold (mul c1, c2) -> c1*c2
2009   if (N0IsConst && N1IsConst)
2010     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2011                                       N0.getNode(), N1.getNode());
2012
2013   // canonicalize constant to RHS (vector doesn't have to splat)
2014   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2015      !isConstantIntBuildVectorOrConstantInt(N1))
2016     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2017   // fold (mul x, 0) -> 0
2018   if (N1IsConst && ConstValue1 == 0)
2019     return N1;
2020   // We require a splat of the entire scalar bit width for non-contiguous
2021   // bit patterns.
2022   bool IsFullSplat =
2023     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2024   // fold (mul x, 1) -> x
2025   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2026     return N0;
2027   // fold (mul x, -1) -> 0-x
2028   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2029     SDLoc DL(N);
2030     return DAG.getNode(ISD::SUB, DL, VT,
2031                        DAG.getConstant(0, DL, VT), N0);
2032   }
2033   // fold (mul x, (1 << c)) -> x << c
2034   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2035     SDLoc DL(N);
2036     return DAG.getNode(ISD::SHL, DL, VT, N0,
2037                        DAG.getConstant(ConstValue1.logBase2(), DL,
2038                                        getShiftAmountTy(N0.getValueType())));
2039   }
2040   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2041   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2042     unsigned Log2Val = (-ConstValue1).logBase2();
2043     SDLoc DL(N);
2044     // FIXME: If the input is something that is easily negated (e.g. a
2045     // single-use add), we should put the negate there.
2046     return DAG.getNode(ISD::SUB, DL, VT,
2047                        DAG.getConstant(0, DL, VT),
2048                        DAG.getNode(ISD::SHL, DL, VT, N0,
2049                             DAG.getConstant(Log2Val, DL,
2050                                       getShiftAmountTy(N0.getValueType()))));
2051   }
2052
2053   APInt Val;
2054   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2055   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2056       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2057                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2058     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                              N1, N0.getOperand(1));
2060     AddToWorklist(C3.getNode());
2061     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062                        N0.getOperand(0), C3);
2063   }
2064
2065   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2066   // use.
2067   {
2068     SDValue Sh(nullptr,0), Y(nullptr,0);
2069     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2070     if (N0.getOpcode() == ISD::SHL &&
2071         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2072                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2073         N0.getNode()->hasOneUse()) {
2074       Sh = N0; Y = N1;
2075     } else if (N1.getOpcode() == ISD::SHL &&
2076                isa<ConstantSDNode>(N1.getOperand(1)) &&
2077                N1.getNode()->hasOneUse()) {
2078       Sh = N1; Y = N0;
2079     }
2080
2081     if (Sh.getNode()) {
2082       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083                                 Sh.getOperand(0), Y);
2084       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2085                          Mul, Sh.getOperand(1));
2086     }
2087   }
2088
2089   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2090   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2091       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2092                      isa<ConstantSDNode>(N0.getOperand(1))))
2093     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2094                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2095                                    N0.getOperand(0), N1),
2096                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2097                                    N0.getOperand(1), N1));
2098
2099   // reassociate mul
2100   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2101     return RMUL;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold vector ops
2112   if (VT.isVector())
2113     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2114       return FoldedVOp;
2115
2116   // fold (sdiv c1, c2) -> c1/c2
2117   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119   if (N0C && N1C && !N1C->isNullValue())
2120     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2121   // fold (sdiv X, 1) -> X
2122   if (N1C && N1C->getAPIntValue() == 1LL)
2123     return N0;
2124   // fold (sdiv X, -1) -> 0-X
2125   if (N1C && N1C->isAllOnesValue()) {
2126     SDLoc DL(N);
2127     return DAG.getNode(ISD::SUB, DL, VT,
2128                        DAG.getConstant(0, DL, VT), N0);
2129   }
2130   // If we know the sign bits of both operands are zero, strength reduce to a
2131   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2132   if (!VT.isVector()) {
2133     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2135                          N0, N1);
2136   }
2137
2138   // fold (sdiv X, pow2) -> simple ops after legalize
2139   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2140                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2141     // If dividing by powers of two is cheap, then don't perform the following
2142     // fold.
2143     if (TLI.isPow2SDivCheap())
2144       return SDValue();
2145
2146     // Target-specific implementation of sdiv x, pow2.
2147     SDValue Res = BuildSDIVPow2(N);
2148     if (Res.getNode())
2149       return Res;
2150
2151     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2152     SDLoc DL(N);
2153
2154     // Splat the sign bit into the register
2155     SDValue SGN =
2156         DAG.getNode(ISD::SRA, DL, VT, N0,
2157                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2158                                     getShiftAmountTy(N0.getValueType())));
2159     AddToWorklist(SGN.getNode());
2160
2161     // Add (N0 < 0) ? abs2 - 1 : 0;
2162     SDValue SRL =
2163         DAG.getNode(ISD::SRL, DL, VT, SGN,
2164                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2165                                     getShiftAmountTy(SGN.getValueType())));
2166     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2167     AddToWorklist(SRL.getNode());
2168     AddToWorklist(ADD.getNode());    // Divide by pow2
2169     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2170                   DAG.getConstant(lg2, DL,
2171                                   getShiftAmountTy(ADD.getValueType())));
2172
2173     // If we're dividing by a positive value, we're done.  Otherwise, we must
2174     // negate the result.
2175     if (N1C->getAPIntValue().isNonNegative())
2176       return SRA;
2177
2178     AddToWorklist(SRA.getNode());
2179     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2180   }
2181
2182   // If integer divide is expensive and we satisfy the requirements, emit an
2183   // alternate sequence.
2184   if (N1C && !TLI.isIntDivCheap()) {
2185     SDValue Op = BuildSDIV(N);
2186     if (Op.getNode()) return Op;
2187   }
2188
2189   // undef / X -> 0
2190   if (N0.getOpcode() == ISD::UNDEF)
2191     return DAG.getConstant(0, SDLoc(N), VT);
2192   // X / undef -> undef
2193   if (N1.getOpcode() == ISD::UNDEF)
2194     return N1;
2195
2196   return SDValue();
2197 }
2198
2199 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2200   SDValue N0 = N->getOperand(0);
2201   SDValue N1 = N->getOperand(1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold vector ops
2205   if (VT.isVector())
2206     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2207       return FoldedVOp;
2208
2209   // fold (udiv c1, c2) -> c1/c2
2210   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212   if (N0C && N1C && !N1C->isNullValue())
2213     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2214   // fold (udiv x, (1 << c)) -> x >>u c
2215   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2216     SDLoc DL(N);
2217     return DAG.getNode(ISD::SRL, DL, VT, N0,
2218                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2219                                        getShiftAmountTy(N0.getValueType())));
2220   }
2221   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2222   if (N1.getOpcode() == ISD::SHL) {
2223     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224       if (SHC->getAPIntValue().isPowerOf2()) {
2225         EVT ADDVT = N1.getOperand(1).getValueType();
2226         SDLoc DL(N);
2227         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2228                                   N1.getOperand(1),
2229                                   DAG.getConstant(SHC->getAPIntValue()
2230                                                                   .logBase2(),
2231                                                   DL, ADDVT));
2232         AddToWorklist(Add.getNode());
2233         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2234       }
2235     }
2236   }
2237   // fold (udiv x, c) -> alternate
2238   if (N1C && !TLI.isIntDivCheap()) {
2239     SDValue Op = BuildUDIV(N);
2240     if (Op.getNode()) return Op;
2241   }
2242
2243   // undef / X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, SDLoc(N), VT);
2246   // X / undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitSREM(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   EVT VT = N->getValueType(0);
2257
2258   // fold (srem c1, c2) -> c1%c2
2259   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261   if (N0C && N1C && !N1C->isNullValue())
2262     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2268   }
2269
2270   // If X/C can be simplified by the division-by-constant logic, lower
2271   // X%C to the equivalent of X-X/C*C.
2272   if (N1C && !N1C->isNullValue()) {
2273     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2274     AddToWorklist(Div.getNode());
2275     SDValue OptimizedDiv = combine(Div.getNode());
2276     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278                                 OptimizedDiv, N1);
2279       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280       AddToWorklist(Mul.getNode());
2281       return Sub;
2282     }
2283   }
2284
2285   // undef % X -> 0
2286   if (N0.getOpcode() == ISD::UNDEF)
2287     return DAG.getConstant(0, SDLoc(N), VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitUREM(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   EVT VT = N->getValueType(0);
2299
2300   // fold (urem c1, c2) -> c1%c2
2301   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2303   if (N0C && N1C && !N1C->isNullValue())
2304     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2305   // fold (urem x, pow2) -> (and x, pow2-1)
2306   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2307     SDLoc DL(N);
2308     return DAG.getNode(ISD::AND, DL, VT, N0,
2309                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2310   }
2311   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2312   if (N1.getOpcode() == ISD::SHL) {
2313     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2314       if (SHC->getAPIntValue().isPowerOf2()) {
2315         SDLoc DL(N);
2316         SDValue Add =
2317           DAG.getNode(ISD::ADD, DL, VT, N1,
2318                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2319                                  VT));
2320         AddToWorklist(Add.getNode());
2321         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2322       }
2323     }
2324   }
2325
2326   // If X/C can be simplified by the division-by-constant logic, lower
2327   // X%C to the equivalent of X-X/C*C.
2328   if (N1C && !N1C->isNullValue()) {
2329     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2330     AddToWorklist(Div.getNode());
2331     SDValue OptimizedDiv = combine(Div.getNode());
2332     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2334                                 OptimizedDiv, N1);
2335       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336       AddToWorklist(Mul.getNode());
2337       return Sub;
2338     }
2339   }
2340
2341   // undef % X -> 0
2342   if (N0.getOpcode() == ISD::UNDEF)
2343     return DAG.getConstant(0, SDLoc(N), VT);
2344   // X % undef -> undef
2345   if (N1.getOpcode() == ISD::UNDEF)
2346     return N1;
2347
2348   return SDValue();
2349 }
2350
2351 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2352   SDValue N0 = N->getOperand(0);
2353   SDValue N1 = N->getOperand(1);
2354   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2355   EVT VT = N->getValueType(0);
2356   SDLoc DL(N);
2357
2358   // fold (mulhs x, 0) -> 0
2359   if (N1C && N1C->isNullValue())
2360     return N1;
2361   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2362   if (N1C && N1C->getAPIntValue() == 1) {
2363     SDLoc DL(N);
2364     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2365                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2366                                        DL,
2367                                        getShiftAmountTy(N0.getValueType())));
2368   }
2369   // fold (mulhs x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, SDLoc(N), VT);
2372
2373   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, DL,
2385                             getShiftAmountTy(N1.getValueType())));
2386       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2387     }
2388   }
2389
2390   return SDValue();
2391 }
2392
2393 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2397   EVT VT = N->getValueType(0);
2398   SDLoc DL(N);
2399
2400   // fold (mulhu x, 0) -> 0
2401   if (N1C && N1C->isNullValue())
2402     return N1;
2403   // fold (mulhu x, 1) -> 0
2404   if (N1C && N1C->getAPIntValue() == 1)
2405     return DAG.getConstant(0, DL, N0.getValueType());
2406   // fold (mulhu x, undef) -> 0
2407   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408     return DAG.getConstant(0, DL, VT);
2409
2410   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2411   // plus a shift.
2412   if (VT.isSimple() && !VT.isVector()) {
2413     MVT Simple = VT.getSimpleVT();
2414     unsigned SimpleSize = Simple.getSizeInBits();
2415     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2418       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2419       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421             DAG.getConstant(SimpleSize, DL,
2422                             getShiftAmountTy(N1.getValueType())));
2423       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2424     }
2425   }
2426
2427   return SDValue();
2428 }
2429
2430 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2431 /// give the opcodes for the two computations that are being performed. Return
2432 /// true if a simplification was made.
2433 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2434                                                 unsigned HiOp) {
2435   // If the high half is not needed, just compute the low half.
2436   bool HiExists = N->hasAnyUseOfValue(1);
2437   if (!HiExists &&
2438       (!LegalOperations ||
2439        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2440     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2441     return CombineTo(N, Res, Res);
2442   }
2443
2444   // If the low half is not needed, just compute the high half.
2445   bool LoExists = N->hasAnyUseOfValue(0);
2446   if (!LoExists &&
2447       (!LegalOperations ||
2448        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2449     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2450     return CombineTo(N, Res, Res);
2451   }
2452
2453   // If both halves are used, return as it is.
2454   if (LoExists && HiExists)
2455     return SDValue();
2456
2457   // If the two computed results can be simplified separately, separate them.
2458   if (LoExists) {
2459     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2460     AddToWorklist(Lo.getNode());
2461     SDValue LoOpt = combine(Lo.getNode());
2462     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2463         (!LegalOperations ||
2464          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2465       return CombineTo(N, LoOpt, LoOpt);
2466   }
2467
2468   if (HiExists) {
2469     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2470     AddToWorklist(Hi.getNode());
2471     SDValue HiOpt = combine(Hi.getNode());
2472     if (HiOpt.getNode() && HiOpt != Hi &&
2473         (!LegalOperations ||
2474          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2475       return CombineTo(N, HiOpt, HiOpt);
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2482   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2483   if (Res.getNode()) return Res;
2484
2485   EVT VT = N->getValueType(0);
2486   SDLoc DL(N);
2487
2488   // If the type is twice as wide is legal, transform the mulhu to a wider
2489   // multiply plus a shift.
2490   if (VT.isSimple() && !VT.isVector()) {
2491     MVT Simple = VT.getSimpleVT();
2492     unsigned SimpleSize = Simple.getSizeInBits();
2493     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2496       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2497       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2498       // Compute the high part as N1.
2499       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2500             DAG.getConstant(SimpleSize, DL,
2501                             getShiftAmountTy(Lo.getValueType())));
2502       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503       // Compute the low part as N0.
2504       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505       return CombineTo(N, Lo, Hi);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2513   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2514   if (Res.getNode()) return Res;
2515
2516   EVT VT = N->getValueType(0);
2517   SDLoc DL(N);
2518
2519   // If the type is twice as wide is legal, transform the mulhu to a wider
2520   // multiply plus a shift.
2521   if (VT.isSimple() && !VT.isVector()) {
2522     MVT Simple = VT.getSimpleVT();
2523     unsigned SimpleSize = Simple.getSizeInBits();
2524     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2527       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2528       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529       // Compute the high part as N1.
2530       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531             DAG.getConstant(SimpleSize, DL,
2532                             getShiftAmountTy(Lo.getValueType())));
2533       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534       // Compute the low part as N0.
2535       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536       return CombineTo(N, Lo, Hi);
2537     }
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2544   // (smulo x, 2) -> (saddo x, x)
2545   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2546     if (C2->getAPIntValue() == 2)
2547       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2548                          N->getOperand(0), N->getOperand(0));
2549
2550   return SDValue();
2551 }
2552
2553 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2554   // (umulo x, 2) -> (uaddo x, x)
2555   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2556     if (C2->getAPIntValue() == 2)
2557       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2558                          N->getOperand(0), N->getOperand(0));
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2564   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2565   if (Res.getNode()) return Res;
2566
2567   return SDValue();
2568 }
2569
2570 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2571   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2572   if (Res.getNode()) return Res;
2573
2574   return SDValue();
2575 }
2576
2577 /// If this is a binary operator with two operands of the same opcode, try to
2578 /// simplify it.
2579 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2580   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2581   EVT VT = N0.getValueType();
2582   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2583
2584   // Bail early if none of these transforms apply.
2585   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2586
2587   // For each of OP in AND/OR/XOR:
2588   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2589   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2590   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2591   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2592   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2593   //
2594   // do not sink logical op inside of a vector extend, since it may combine
2595   // into a vsetcc.
2596   EVT Op0VT = N0.getOperand(0).getValueType();
2597   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2598        N0.getOpcode() == ISD::SIGN_EXTEND ||
2599        N0.getOpcode() == ISD::BSWAP ||
2600        // Avoid infinite looping with PromoteIntBinOp.
2601        (N0.getOpcode() == ISD::ANY_EXTEND &&
2602         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2603        (N0.getOpcode() == ISD::TRUNCATE &&
2604         (!TLI.isZExtFree(VT, Op0VT) ||
2605          !TLI.isTruncateFree(Op0VT, VT)) &&
2606         TLI.isTypeLegal(Op0VT))) &&
2607       !VT.isVector() &&
2608       Op0VT == N1.getOperand(0).getValueType() &&
2609       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2610     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2611                                  N0.getOperand(0).getValueType(),
2612                                  N0.getOperand(0), N1.getOperand(0));
2613     AddToWorklist(ORNode.getNode());
2614     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2615   }
2616
2617   // For each of OP in SHL/SRL/SRA/AND...
2618   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2619   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2620   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2621   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2622        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2623       N0.getOperand(1) == N1.getOperand(1)) {
2624     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2625                                  N0.getOperand(0).getValueType(),
2626                                  N0.getOperand(0), N1.getOperand(0));
2627     AddToWorklist(ORNode.getNode());
2628     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2629                        ORNode, N0.getOperand(1));
2630   }
2631
2632   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2633   // Only perform this optimization after type legalization and before
2634   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2635   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2636   // we don't want to undo this promotion.
2637   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2638   // on scalars.
2639   if ((N0.getOpcode() == ISD::BITCAST ||
2640        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2641       Level == AfterLegalizeTypes) {
2642     SDValue In0 = N0.getOperand(0);
2643     SDValue In1 = N1.getOperand(0);
2644     EVT In0Ty = In0.getValueType();
2645     EVT In1Ty = In1.getValueType();
2646     SDLoc DL(N);
2647     // If both incoming values are integers, and the original types are the
2648     // same.
2649     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2650       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2651       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2652       AddToWorklist(Op.getNode());
2653       return BC;
2654     }
2655   }
2656
2657   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2658   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2659   // If both shuffles use the same mask, and both shuffle within a single
2660   // vector, then it is worthwhile to move the swizzle after the operation.
2661   // The type-legalizer generates this pattern when loading illegal
2662   // vector types from memory. In many cases this allows additional shuffle
2663   // optimizations.
2664   // There are other cases where moving the shuffle after the xor/and/or
2665   // is profitable even if shuffles don't perform a swizzle.
2666   // If both shuffles use the same mask, and both shuffles have the same first
2667   // or second operand, then it might still be profitable to move the shuffle
2668   // after the xor/and/or operation.
2669   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2670     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2671     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2672
2673     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2674            "Inputs to shuffles are not the same type");
2675
2676     // Check that both shuffles use the same mask. The masks are known to be of
2677     // the same length because the result vector type is the same.
2678     // Check also that shuffles have only one use to avoid introducing extra
2679     // instructions.
2680     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2681         SVN0->getMask().equals(SVN1->getMask())) {
2682       SDValue ShOp = N0->getOperand(1);
2683
2684       // Don't try to fold this node if it requires introducing a
2685       // build vector of all zeros that might be illegal at this stage.
2686       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2687         if (!LegalTypes)
2688           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2689         else
2690           ShOp = SDValue();
2691       }
2692
2693       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2694       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2695       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2696       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2697         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2698                                       N0->getOperand(0), N1->getOperand(0));
2699         AddToWorklist(NewNode.getNode());
2700         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2701                                     &SVN0->getMask()[0]);
2702       }
2703
2704       // Don't try to fold this node if it requires introducing a
2705       // build vector of all zeros that might be illegal at this stage.
2706       ShOp = N0->getOperand(0);
2707       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2708         if (!LegalTypes)
2709           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2710         else
2711           ShOp = SDValue();
2712       }
2713
2714       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2715       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2716       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2717       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2718         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2719                                       N0->getOperand(1), N1->getOperand(1));
2720         AddToWorklist(NewNode.getNode());
2721         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2722                                     &SVN0->getMask()[0]);
2723       }
2724     }
2725   }
2726
2727   return SDValue();
2728 }
2729
2730 /// This contains all DAGCombine rules which reduce two values combined by
2731 /// an And operation to a single value. This makes them reusable in the context
2732 /// of visitSELECT(). Rules involving constants are not included as
2733 /// visitSELECT() already handles those cases.
2734 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2735                                   SDNode *LocReference) {
2736   EVT VT = N1.getValueType();
2737
2738   // fold (and x, undef) -> 0
2739   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2740     return DAG.getConstant(0, SDLoc(LocReference), VT);
2741   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2742   SDValue LL, LR, RL, RR, CC0, CC1;
2743   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2744     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2745     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2746
2747     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2748         LL.getValueType().isInteger()) {
2749       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2750       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2751         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2752                                      LR.getValueType(), LL, RL);
2753         AddToWorklist(ORNode.getNode());
2754         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2755       }
2756       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2757       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2758         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2759                                       LR.getValueType(), LL, RL);
2760         AddToWorklist(ANDNode.getNode());
2761         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2762       }
2763       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2764       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2765         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766                                      LR.getValueType(), LL, RL);
2767         AddToWorklist(ORNode.getNode());
2768         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2769       }
2770     }
2771     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2772     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2773         Op0 == Op1 && LL.getValueType().isInteger() &&
2774       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2775                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2776                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2777                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2778       SDLoc DL(N0);
2779       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2780                                     LL, DAG.getConstant(1, DL,
2781                                                         LL.getValueType()));
2782       AddToWorklist(ADDNode.getNode());
2783       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2784                           DAG.getConstant(2, DL, LL.getValueType()),
2785                           ISD::SETUGE);
2786     }
2787     // canonicalize equivalent to ll == rl
2788     if (LL == RR && LR == RL) {
2789       Op1 = ISD::getSetCCSwappedOperands(Op1);
2790       std::swap(RL, RR);
2791     }
2792     if (LL == RL && LR == RR) {
2793       bool isInteger = LL.getValueType().isInteger();
2794       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795       if (Result != ISD::SETCC_INVALID &&
2796           (!LegalOperations ||
2797            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798             TLI.isOperationLegal(ISD::SETCC,
2799                             getSetCCResultType(N0.getSimpleValueType())))))
2800         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2801                             LL, LR, Result);
2802     }
2803   }
2804
2805   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2806       VT.getSizeInBits() <= 64) {
2807     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2808       APInt ADDC = ADDI->getAPIntValue();
2809       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2810         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2811         // immediate for an add, but it is legal if its top c2 bits are set,
2812         // transform the ADD so the immediate doesn't need to be materialized
2813         // in a register.
2814         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2815           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2816                                              SRLI->getZExtValue());
2817           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2818             ADDC |= Mask;
2819             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2820               SDLoc DL(N0);
2821               SDValue NewAdd =
2822                 DAG.getNode(ISD::ADD, DL, VT,
2823                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2824               CombineTo(N0.getNode(), NewAdd);
2825               // Return N so it doesn't get rechecked!
2826               return SDValue(LocReference, 0);
2827             }
2828           }
2829         }
2830       }
2831     }
2832   }
2833
2834   return SDValue();
2835 }
2836
2837 SDValue DAGCombiner::visitAND(SDNode *N) {
2838   SDValue N0 = N->getOperand(0);
2839   SDValue N1 = N->getOperand(1);
2840   EVT VT = N1.getValueType();
2841
2842   // fold vector ops
2843   if (VT.isVector()) {
2844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2845       return FoldedVOp;
2846
2847     // fold (and x, 0) -> 0, vector edition
2848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2849       // do not return N0, because undef node may exist in N0
2850       return DAG.getConstant(
2851           APInt::getNullValue(
2852               N0.getValueType().getScalarType().getSizeInBits()),
2853           SDLoc(N), N0.getValueType());
2854     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2855       // do not return N1, because undef node may exist in N1
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N1.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N1.getValueType());
2860
2861     // fold (and x, -1) -> x, vector edition
2862     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2863       return N1;
2864     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2865       return N0;
2866   }
2867
2868   // fold (and c1, c2) -> c1&c2
2869   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2871   if (N0C && N1C)
2872     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2873   // canonicalize constant to RHS
2874   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2875      !isConstantIntBuildVectorOrConstantInt(N1))
2876     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2877   // fold (and x, -1) -> x
2878   if (N1C && N1C->isAllOnesValue())
2879     return N0;
2880   // if (and x, c) is known to be zero, return 0
2881   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2882   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2883                                    APInt::getAllOnesValue(BitWidth)))
2884     return DAG.getConstant(0, SDLoc(N), VT);
2885   // reassociate and
2886   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2887     return RAND;
2888   // fold (and (or x, C), D) -> D if (C & D) == D
2889   if (N1C && N0.getOpcode() == ISD::OR)
2890     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2891       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2892         return N1;
2893   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2894   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2895     SDValue N0Op0 = N0.getOperand(0);
2896     APInt Mask = ~N1C->getAPIntValue();
2897     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2898     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2899       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2900                                  N0.getValueType(), N0Op0);
2901
2902       // Replace uses of the AND with uses of the Zero extend node.
2903       CombineTo(N, Zext);
2904
2905       // We actually want to replace all uses of the any_extend with the
2906       // zero_extend, to avoid duplicating things.  This will later cause this
2907       // AND to be folded.
2908       CombineTo(N0.getNode(), Zext);
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2913   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2914   // already be zero by virtue of the width of the base type of the load.
2915   //
2916   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2917   // more cases.
2918   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2919        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2920       N0.getOpcode() == ISD::LOAD) {
2921     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2922                                          N0 : N0.getOperand(0) );
2923
2924     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2925     // This can be a pure constant or a vector splat, in which case we treat the
2926     // vector as a scalar and use the splat value.
2927     APInt Constant = APInt::getNullValue(1);
2928     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2929       Constant = C->getAPIntValue();
2930     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2931       APInt SplatValue, SplatUndef;
2932       unsigned SplatBitSize;
2933       bool HasAnyUndefs;
2934       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2935                                              SplatBitSize, HasAnyUndefs);
2936       if (IsSplat) {
2937         // Undef bits can contribute to a possible optimisation if set, so
2938         // set them.
2939         SplatValue |= SplatUndef;
2940
2941         // The splat value may be something like "0x00FFFFFF", which means 0 for
2942         // the first vector value and FF for the rest, repeating. We need a mask
2943         // that will apply equally to all members of the vector, so AND all the
2944         // lanes of the constant together.
2945         EVT VT = Vector->getValueType(0);
2946         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2947
2948         // If the splat value has been compressed to a bitlength lower
2949         // than the size of the vector lane, we need to re-expand it to
2950         // the lane size.
2951         if (BitWidth > SplatBitSize)
2952           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2953                SplatBitSize < BitWidth;
2954                SplatBitSize = SplatBitSize * 2)
2955             SplatValue |= SplatValue.shl(SplatBitSize);
2956
2957         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2958         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2959         if (SplatBitSize % BitWidth == 0) {
2960           Constant = APInt::getAllOnesValue(BitWidth);
2961           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2962             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2963         }
2964       }
2965     }
2966
2967     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2968     // actually legal and isn't going to get expanded, else this is a false
2969     // optimisation.
2970     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2971                                                     Load->getValueType(0),
2972                                                     Load->getMemoryVT());
2973
2974     // Resize the constant to the same size as the original memory access before
2975     // extension. If it is still the AllOnesValue then this AND is completely
2976     // unneeded.
2977     Constant =
2978       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2979
2980     bool B;
2981     switch (Load->getExtensionType()) {
2982     default: B = false; break;
2983     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2984     case ISD::ZEXTLOAD:
2985     case ISD::NON_EXTLOAD: B = true; break;
2986     }
2987
2988     if (B && Constant.isAllOnesValue()) {
2989       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2990       // preserve semantics once we get rid of the AND.
2991       SDValue NewLoad(Load, 0);
2992       if (Load->getExtensionType() == ISD::EXTLOAD) {
2993         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2994                               Load->getValueType(0), SDLoc(Load),
2995                               Load->getChain(), Load->getBasePtr(),
2996                               Load->getOffset(), Load->getMemoryVT(),
2997                               Load->getMemOperand());
2998         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2999         if (Load->getNumValues() == 3) {
3000           // PRE/POST_INC loads have 3 values.
3001           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3002                            NewLoad.getValue(2) };
3003           CombineTo(Load, To, 3, true);
3004         } else {
3005           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3006         }
3007       }
3008
3009       // Fold the AND away, taking care not to fold to the old load node if we
3010       // replaced it.
3011       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3012
3013       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3014     }
3015   }
3016
3017   // fold (and (load x), 255) -> (zextload x, i8)
3018   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3019   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3020   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3021               (N0.getOpcode() == ISD::ANY_EXTEND &&
3022                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3023     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3024     LoadSDNode *LN0 = HasAnyExt
3025       ? cast<LoadSDNode>(N0.getOperand(0))
3026       : cast<LoadSDNode>(N0);
3027     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3028         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3029       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3030       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3031         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3032         EVT LoadedVT = LN0->getMemoryVT();
3033         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3034
3035         if (ExtVT == LoadedVT &&
3036             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3037                                                     ExtVT))) {
3038
3039           SDValue NewLoad =
3040             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3041                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3042                            LN0->getMemOperand());
3043           AddToWorklist(N);
3044           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3045           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3046         }
3047
3048         // Do not change the width of a volatile load.
3049         // Do not generate loads of non-round integer types since these can
3050         // be expensive (and would be wrong if the type is not byte sized).
3051         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3052             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3053                                                     ExtVT))) {
3054           EVT PtrType = LN0->getOperand(1).getValueType();
3055
3056           unsigned Alignment = LN0->getAlignment();
3057           SDValue NewPtr = LN0->getBasePtr();
3058
3059           // For big endian targets, we need to add an offset to the pointer
3060           // to load the correct bytes.  For little endian systems, we merely
3061           // need to read fewer bytes from the same pointer.
3062           if (TLI.isBigEndian()) {
3063             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3064             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3065             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3066             SDLoc DL(LN0);
3067             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3068                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3069             Alignment = MinAlign(Alignment, PtrOff);
3070           }
3071
3072           AddToWorklist(NewPtr.getNode());
3073
3074           SDValue Load =
3075             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3076                            LN0->getChain(), NewPtr,
3077                            LN0->getPointerInfo(),
3078                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3079                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3080           AddToWorklist(N);
3081           CombineTo(LN0, Load, Load.getValue(1));
3082           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3083         }
3084       }
3085     }
3086   }
3087
3088   if (SDValue Combined = visitANDLike(N0, N1, N))
3089     return Combined;
3090
3091   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3092   if (N0.getOpcode() == N1.getOpcode()) {
3093     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3094     if (Tmp.getNode()) return Tmp;
3095   }
3096
3097   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3098   // fold (and (sra)) -> (and (srl)) when possible.
3099   if (!VT.isVector() &&
3100       SimplifyDemandedBits(SDValue(N, 0)))
3101     return SDValue(N, 0);
3102
3103   // fold (zext_inreg (extload x)) -> (zextload x)
3104   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3105     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3106     EVT MemVT = LN0->getMemoryVT();
3107     // If we zero all the possible extended bits, then we can turn this into
3108     // a zextload if we are running before legalize or the operation is legal.
3109     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3110     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3111                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3112         ((!LegalOperations && !LN0->isVolatile()) ||
3113          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3114       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3115                                        LN0->getChain(), LN0->getBasePtr(),
3116                                        MemVT, LN0->getMemOperand());
3117       AddToWorklist(N);
3118       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3120     }
3121   }
3122   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3123   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3124       N0.hasOneUse()) {
3125     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3126     EVT MemVT = LN0->getMemoryVT();
3127     // If we zero all the possible extended bits, then we can turn this into
3128     // a zextload if we are running before legalize or the operation is legal.
3129     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3130     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3131                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3132         ((!LegalOperations && !LN0->isVolatile()) ||
3133          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3134       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3135                                        LN0->getChain(), LN0->getBasePtr(),
3136                                        MemVT, LN0->getMemOperand());
3137       AddToWorklist(N);
3138       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3140     }
3141   }
3142   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3143   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3144     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3145                                        N0.getOperand(1), false);
3146     if (BSwap.getNode())
3147       return BSwap;
3148   }
3149
3150   return SDValue();
3151 }
3152
3153 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3154 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3155                                         bool DemandHighBits) {
3156   if (!LegalOperations)
3157     return SDValue();
3158
3159   EVT VT = N->getValueType(0);
3160   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3161     return SDValue();
3162   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163     return SDValue();
3164
3165   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3166   bool LookPassAnd0 = false;
3167   bool LookPassAnd1 = false;
3168   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3169       std::swap(N0, N1);
3170   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3171       std::swap(N0, N1);
3172   if (N0.getOpcode() == ISD::AND) {
3173     if (!N0.getNode()->hasOneUse())
3174       return SDValue();
3175     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3176     if (!N01C || N01C->getZExtValue() != 0xFF00)
3177       return SDValue();
3178     N0 = N0.getOperand(0);
3179     LookPassAnd0 = true;
3180   }
3181
3182   if (N1.getOpcode() == ISD::AND) {
3183     if (!N1.getNode()->hasOneUse())
3184       return SDValue();
3185     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3186     if (!N11C || N11C->getZExtValue() != 0xFF)
3187       return SDValue();
3188     N1 = N1.getOperand(0);
3189     LookPassAnd1 = true;
3190   }
3191
3192   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3193     std::swap(N0, N1);
3194   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3195     return SDValue();
3196   if (!N0.getNode()->hasOneUse() ||
3197       !N1.getNode()->hasOneUse())
3198     return SDValue();
3199
3200   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3202   if (!N01C || !N11C)
3203     return SDValue();
3204   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3205     return SDValue();
3206
3207   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3208   SDValue N00 = N0->getOperand(0);
3209   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3210     if (!N00.getNode()->hasOneUse())
3211       return SDValue();
3212     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3213     if (!N001C || N001C->getZExtValue() != 0xFF)
3214       return SDValue();
3215     N00 = N00.getOperand(0);
3216     LookPassAnd0 = true;
3217   }
3218
3219   SDValue N10 = N1->getOperand(0);
3220   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3221     if (!N10.getNode()->hasOneUse())
3222       return SDValue();
3223     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3224     if (!N101C || N101C->getZExtValue() != 0xFF00)
3225       return SDValue();
3226     N10 = N10.getOperand(0);
3227     LookPassAnd1 = true;
3228   }
3229
3230   if (N00 != N10)
3231     return SDValue();
3232
3233   // Make sure everything beyond the low halfword gets set to zero since the SRL
3234   // 16 will clear the top bits.
3235   unsigned OpSizeInBits = VT.getSizeInBits();
3236   if (DemandHighBits && OpSizeInBits > 16) {
3237     // If the left-shift isn't masked out then the only way this is a bswap is
3238     // if all bits beyond the low 8 are 0. In that case the entire pattern
3239     // reduces to a left shift anyway: leave it for other parts of the combiner.
3240     if (!LookPassAnd0)
3241       return SDValue();
3242
3243     // However, if the right shift isn't masked out then it might be because
3244     // it's not needed. See if we can spot that too.
3245     if (!LookPassAnd1 &&
3246         !DAG.MaskedValueIsZero(
3247             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3248       return SDValue();
3249   }
3250
3251   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3252   if (OpSizeInBits > 16) {
3253     SDLoc DL(N);
3254     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3255                       DAG.getConstant(OpSizeInBits - 16, DL,
3256                                       getShiftAmountTy(VT)));
3257   }
3258   return Res;
3259 }
3260
3261 /// Return true if the specified node is an element that makes up a 32-bit
3262 /// packed halfword byteswap.
3263 /// ((x & 0x000000ff) << 8) |
3264 /// ((x & 0x0000ff00) >> 8) |
3265 /// ((x & 0x00ff0000) << 8) |
3266 /// ((x & 0xff000000) >> 8)
3267 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3268   if (!N.getNode()->hasOneUse())
3269     return false;
3270
3271   unsigned Opc = N.getOpcode();
3272   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3273     return false;
3274
3275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276   if (!N1C)
3277     return false;
3278
3279   unsigned Num;
3280   switch (N1C->getZExtValue()) {
3281   default:
3282     return false;
3283   case 0xFF:       Num = 0; break;
3284   case 0xFF00:     Num = 1; break;
3285   case 0xFF0000:   Num = 2; break;
3286   case 0xFF000000: Num = 3; break;
3287   }
3288
3289   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3290   SDValue N0 = N.getOperand(0);
3291   if (Opc == ISD::AND) {
3292     if (Num == 0 || Num == 2) {
3293       // (x >> 8) & 0xff
3294       // (x >> 8) & 0xff0000
3295       if (N0.getOpcode() != ISD::SRL)
3296         return false;
3297       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3298       if (!C || C->getZExtValue() != 8)
3299         return false;
3300     } else {
3301       // (x << 8) & 0xff00
3302       // (x << 8) & 0xff000000
3303       if (N0.getOpcode() != ISD::SHL)
3304         return false;
3305       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306       if (!C || C->getZExtValue() != 8)
3307         return false;
3308     }
3309   } else if (Opc == ISD::SHL) {
3310     // (x & 0xff) << 8
3311     // (x & 0xff0000) << 8
3312     if (Num != 0 && Num != 2)
3313       return false;
3314     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3315     if (!C || C->getZExtValue() != 8)
3316       return false;
3317   } else { // Opc == ISD::SRL
3318     // (x & 0xff00) >> 8
3319     // (x & 0xff000000) >> 8
3320     if (Num != 1 && Num != 3)
3321       return false;
3322     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323     if (!C || C->getZExtValue() != 8)
3324       return false;
3325   }
3326
3327   if (Parts[Num])
3328     return false;
3329
3330   Parts[Num] = N0.getOperand(0).getNode();
3331   return true;
3332 }
3333
3334 /// Match a 32-bit packed halfword bswap. That is
3335 /// ((x & 0x000000ff) << 8) |
3336 /// ((x & 0x0000ff00) >> 8) |
3337 /// ((x & 0x00ff0000) << 8) |
3338 /// ((x & 0xff000000) >> 8)
3339 /// => (rotl (bswap x), 16)
3340 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3341   if (!LegalOperations)
3342     return SDValue();
3343
3344   EVT VT = N->getValueType(0);
3345   if (VT != MVT::i32)
3346     return SDValue();
3347   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3348     return SDValue();
3349
3350   // Look for either
3351   // (or (or (and), (and)), (or (and), (and)))
3352   // (or (or (or (and), (and)), (and)), (and))
3353   if (N0.getOpcode() != ISD::OR)
3354     return SDValue();
3355   SDValue N00 = N0.getOperand(0);
3356   SDValue N01 = N0.getOperand(1);
3357   SDNode *Parts[4] = {};
3358
3359   if (N1.getOpcode() == ISD::OR &&
3360       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3361     // (or (or (and), (and)), (or (and), (and)))
3362     SDValue N000 = N00.getOperand(0);
3363     if (!isBSwapHWordElement(N000, Parts))
3364       return SDValue();
3365
3366     SDValue N001 = N00.getOperand(1);
3367     if (!isBSwapHWordElement(N001, Parts))
3368       return SDValue();
3369     SDValue N010 = N01.getOperand(0);
3370     if (!isBSwapHWordElement(N010, Parts))
3371       return SDValue();
3372     SDValue N011 = N01.getOperand(1);
3373     if (!isBSwapHWordElement(N011, Parts))
3374       return SDValue();
3375   } else {
3376     // (or (or (or (and), (and)), (and)), (and))
3377     if (!isBSwapHWordElement(N1, Parts))
3378       return SDValue();
3379     if (!isBSwapHWordElement(N01, Parts))
3380       return SDValue();
3381     if (N00.getOpcode() != ISD::OR)
3382       return SDValue();
3383     SDValue N000 = N00.getOperand(0);
3384     if (!isBSwapHWordElement(N000, Parts))
3385       return SDValue();
3386     SDValue N001 = N00.getOperand(1);
3387     if (!isBSwapHWordElement(N001, Parts))
3388       return SDValue();
3389   }
3390
3391   // Make sure the parts are all coming from the same node.
3392   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3393     return SDValue();
3394
3395   SDLoc DL(N);
3396   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3397                               SDValue(Parts[0], 0));
3398
3399   // Result of the bswap should be rotated by 16. If it's not legal, then
3400   // do  (x << 16) | (x >> 16).
3401   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3402   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3403     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3404   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3405     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3406   return DAG.getNode(ISD::OR, DL, VT,
3407                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3408                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3409 }
3410
3411 /// This contains all DAGCombine rules which reduce two values combined by
3412 /// an Or operation to a single value \see visitANDLike().
3413 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3414   EVT VT = N1.getValueType();
3415   // fold (or x, undef) -> -1
3416   if (!LegalOperations &&
3417       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3418     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3419     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3420                            SDLoc(LocReference), VT);
3421   }
3422   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3423   SDValue LL, LR, RL, RR, CC0, CC1;
3424   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3425     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3426     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3427
3428     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3429         LL.getValueType().isInteger()) {
3430       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3431       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3432       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3433           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3434         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3435                                      LR.getValueType(), LL, RL);
3436         AddToWorklist(ORNode.getNode());
3437         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3438       }
3439       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3440       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3441       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3442           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3443         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3444                                       LR.getValueType(), LL, RL);
3445         AddToWorklist(ANDNode.getNode());
3446         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3447       }
3448     }
3449     // canonicalize equivalent to ll == rl
3450     if (LL == RR && LR == RL) {
3451       Op1 = ISD::getSetCCSwappedOperands(Op1);
3452       std::swap(RL, RR);
3453     }
3454     if (LL == RL && LR == RR) {
3455       bool isInteger = LL.getValueType().isInteger();
3456       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3457       if (Result != ISD::SETCC_INVALID &&
3458           (!LegalOperations ||
3459            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3460             TLI.isOperationLegal(ISD::SETCC,
3461               getSetCCResultType(N0.getValueType())))))
3462         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3463                             LL, LR, Result);
3464     }
3465   }
3466
3467   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3468   if (N0.getOpcode() == ISD::AND &&
3469       N1.getOpcode() == ISD::AND &&
3470       N0.getOperand(1).getOpcode() == ISD::Constant &&
3471       N1.getOperand(1).getOpcode() == ISD::Constant &&
3472       // Don't increase # computations.
3473       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3474     // We can only do this xform if we know that bits from X that are set in C2
3475     // but not in C1 are already zero.  Likewise for Y.
3476     const APInt &LHSMask =
3477       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3478     const APInt &RHSMask =
3479       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3480
3481     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3482         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3483       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3484                               N0.getOperand(0), N1.getOperand(0));
3485       SDLoc DL(LocReference);
3486       return DAG.getNode(ISD::AND, DL, VT, X,
3487                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3488     }
3489   }
3490
3491   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3492   if (N0.getOpcode() == ISD::AND &&
3493       N1.getOpcode() == ISD::AND &&
3494       N0.getOperand(0) == N1.getOperand(0) &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3498                             N0.getOperand(1), N1.getOperand(1));
3499     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3500   }
3501
3502   return SDValue();
3503 }
3504
3505 SDValue DAGCombiner::visitOR(SDNode *N) {
3506   SDValue N0 = N->getOperand(0);
3507   SDValue N1 = N->getOperand(1);
3508   EVT VT = N1.getValueType();
3509
3510   // fold vector ops
3511   if (VT.isVector()) {
3512     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3513       return FoldedVOp;
3514
3515     // fold (or x, 0) -> x, vector edition
3516     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3517       return N1;
3518     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3519       return N0;
3520
3521     // fold (or x, -1) -> -1, vector edition
3522     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3523       // do not return N0, because undef node may exist in N0
3524       return DAG.getConstant(
3525           APInt::getAllOnesValue(
3526               N0.getValueType().getScalarType().getSizeInBits()),
3527           SDLoc(N), N0.getValueType());
3528     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3529       // do not return N1, because undef node may exist in N1
3530       return DAG.getConstant(
3531           APInt::getAllOnesValue(
3532               N1.getValueType().getScalarType().getSizeInBits()),
3533           SDLoc(N), N1.getValueType());
3534
3535     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3536     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3537     // Do this only if the resulting shuffle is legal.
3538     if (isa<ShuffleVectorSDNode>(N0) &&
3539         isa<ShuffleVectorSDNode>(N1) &&
3540         // Avoid folding a node with illegal type.
3541         TLI.isTypeLegal(VT) &&
3542         N0->getOperand(1) == N1->getOperand(1) &&
3543         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3544       bool CanFold = true;
3545       unsigned NumElts = VT.getVectorNumElements();
3546       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3547       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3548       // We construct two shuffle masks:
3549       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3550       // and N1 as the second operand.
3551       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3552       // and N0 as the second operand.
3553       // We do this because OR is commutable and therefore there might be
3554       // two ways to fold this node into a shuffle.
3555       SmallVector<int,4> Mask1;
3556       SmallVector<int,4> Mask2;
3557
3558       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3559         int M0 = SV0->getMaskElt(i);
3560         int M1 = SV1->getMaskElt(i);
3561
3562         // Both shuffle indexes are undef. Propagate Undef.
3563         if (M0 < 0 && M1 < 0) {
3564           Mask1.push_back(M0);
3565           Mask2.push_back(M0);
3566           continue;
3567         }
3568
3569         if (M0 < 0 || M1 < 0 ||
3570             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3571             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3572           CanFold = false;
3573           break;
3574         }
3575
3576         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3577         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3578       }
3579
3580       if (CanFold) {
3581         // Fold this sequence only if the resulting shuffle is 'legal'.
3582         if (TLI.isShuffleMaskLegal(Mask1, VT))
3583           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3584                                       N1->getOperand(0), &Mask1[0]);
3585         if (TLI.isShuffleMaskLegal(Mask2, VT))
3586           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3587                                       N0->getOperand(0), &Mask2[0]);
3588       }
3589     }
3590   }
3591
3592   // fold (or c1, c2) -> c1|c2
3593   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3594   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3595   if (N0C && N1C)
3596     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3597   // canonicalize constant to RHS
3598   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3599      !isConstantIntBuildVectorOrConstantInt(N1))
3600     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3601   // fold (or x, 0) -> x
3602   if (N1C && N1C->isNullValue())
3603     return N0;
3604   // fold (or x, -1) -> -1
3605   if (N1C && N1C->isAllOnesValue())
3606     return N1;
3607   // fold (or x, c) -> c iff (x & ~c) == 0
3608   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3609     return N1;
3610
3611   if (SDValue Combined = visitORLike(N0, N1, N))
3612     return Combined;
3613
3614   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3615   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3616   if (BSwap.getNode())
3617     return BSwap;
3618   BSwap = MatchBSwapHWordLow(N, N0, N1);
3619   if (BSwap.getNode())
3620     return BSwap;
3621
3622   // reassociate or
3623   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3624     return ROR;
3625   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3626   // iff (c1 & c2) == 0.
3627   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3628              isa<ConstantSDNode>(N0.getOperand(1))) {
3629     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3630     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3631       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3632                                                    N1C, C1))
3633         return DAG.getNode(
3634             ISD::AND, SDLoc(N), VT,
3635             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3636       return SDValue();
3637     }
3638   }
3639   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3640   if (N0.getOpcode() == N1.getOpcode()) {
3641     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3642     if (Tmp.getNode()) return Tmp;
3643   }
3644
3645   // See if this is some rotate idiom.
3646   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3647     return SDValue(Rot, 0);
3648
3649   // Simplify the operands using demanded-bits information.
3650   if (!VT.isVector() &&
3651       SimplifyDemandedBits(SDValue(N, 0)))
3652     return SDValue(N, 0);
3653
3654   return SDValue();
3655 }
3656
3657 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3658 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3659   if (Op.getOpcode() == ISD::AND) {
3660     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3661       Mask = Op.getOperand(1);
3662       Op = Op.getOperand(0);
3663     } else {
3664       return false;
3665     }
3666   }
3667
3668   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3669     Shift = Op;
3670     return true;
3671   }
3672
3673   return false;
3674 }
3675
3676 // Return true if we can prove that, whenever Neg and Pos are both in the
3677 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3678 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3679 //
3680 //     (or (shift1 X, Neg), (shift2 X, Pos))
3681 //
3682 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3683 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3684 // to consider shift amounts with defined behavior.
3685 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3686   // If OpSize is a power of 2 then:
3687   //
3688   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3689   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3690   //
3691   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3692   // for the stronger condition:
3693   //
3694   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3695   //
3696   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3697   // we can just replace Neg with Neg' for the rest of the function.
3698   //
3699   // In other cases we check for the even stronger condition:
3700   //
3701   //     Neg == OpSize - Pos                                    [B]
3702   //
3703   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3704   // behavior if Pos == 0 (and consequently Neg == OpSize).
3705   //
3706   // We could actually use [A] whenever OpSize is a power of 2, but the
3707   // only extra cases that it would match are those uninteresting ones
3708   // where Neg and Pos are never in range at the same time.  E.g. for
3709   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3710   // as well as (sub 32, Pos), but:
3711   //
3712   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3713   //
3714   // always invokes undefined behavior for 32-bit X.
3715   //
3716   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3717   unsigned MaskLoBits = 0;
3718   if (Neg.getOpcode() == ISD::AND &&
3719       isPowerOf2_64(OpSize) &&
3720       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3721       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3722     Neg = Neg.getOperand(0);
3723     MaskLoBits = Log2_64(OpSize);
3724   }
3725
3726   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3727   if (Neg.getOpcode() != ISD::SUB)
3728     return 0;
3729   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3730   if (!NegC)
3731     return 0;
3732   SDValue NegOp1 = Neg.getOperand(1);
3733
3734   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3735   // Pos'.  The truncation is redundant for the purpose of the equality.
3736   if (MaskLoBits &&
3737       Pos.getOpcode() == ISD::AND &&
3738       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3739       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3740     Pos = Pos.getOperand(0);
3741
3742   // The condition we need is now:
3743   //
3744   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3745   //
3746   // If NegOp1 == Pos then we need:
3747   //
3748   //              OpSize & Mask == NegC & Mask
3749   //
3750   // (because "x & Mask" is a truncation and distributes through subtraction).
3751   APInt Width;
3752   if (Pos == NegOp1)
3753     Width = NegC->getAPIntValue();
3754   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3755   // Then the condition we want to prove becomes:
3756   //
3757   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3758   //
3759   // which, again because "x & Mask" is a truncation, becomes:
3760   //
3761   //                NegC & Mask == (OpSize - PosC) & Mask
3762   //              OpSize & Mask == (NegC + PosC) & Mask
3763   else if (Pos.getOpcode() == ISD::ADD &&
3764            Pos.getOperand(0) == NegOp1 &&
3765            Pos.getOperand(1).getOpcode() == ISD::Constant)
3766     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3767              NegC->getAPIntValue());
3768   else
3769     return false;
3770
3771   // Now we just need to check that OpSize & Mask == Width & Mask.
3772   if (MaskLoBits)
3773     // Opsize & Mask is 0 since Mask is Opsize - 1.
3774     return Width.getLoBits(MaskLoBits) == 0;
3775   return Width == OpSize;
3776 }
3777
3778 // A subroutine of MatchRotate used once we have found an OR of two opposite
3779 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3780 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3781 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3782 // Neg with outer conversions stripped away.
3783 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3784                                        SDValue Neg, SDValue InnerPos,
3785                                        SDValue InnerNeg, unsigned PosOpcode,
3786                                        unsigned NegOpcode, SDLoc DL) {
3787   // fold (or (shl x, (*ext y)),
3788   //          (srl x, (*ext (sub 32, y)))) ->
3789   //   (rotl x, y) or (rotr x, (sub 32, y))
3790   //
3791   // fold (or (shl x, (*ext (sub 32, y))),
3792   //          (srl x, (*ext y))) ->
3793   //   (rotr x, y) or (rotl x, (sub 32, y))
3794   EVT VT = Shifted.getValueType();
3795   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3796     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3797     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3798                        HasPos ? Pos : Neg).getNode();
3799   }
3800
3801   return nullptr;
3802 }
3803
3804 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3805 // idioms for rotate, and if the target supports rotation instructions, generate
3806 // a rot[lr].
3807 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3808   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3809   EVT VT = LHS.getValueType();
3810   if (!TLI.isTypeLegal(VT)) return nullptr;
3811
3812   // The target must have at least one rotate flavor.
3813   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3814   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3815   if (!HasROTL && !HasROTR) return nullptr;
3816
3817   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3818   SDValue LHSShift;   // The shift.
3819   SDValue LHSMask;    // AND value if any.
3820   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3821     return nullptr; // Not part of a rotate.
3822
3823   SDValue RHSShift;   // The shift.
3824   SDValue RHSMask;    // AND value if any.
3825   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3826     return nullptr; // Not part of a rotate.
3827
3828   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3829     return nullptr;   // Not shifting the same value.
3830
3831   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3832     return nullptr;   // Shifts must disagree.
3833
3834   // Canonicalize shl to left side in a shl/srl pair.
3835   if (RHSShift.getOpcode() == ISD::SHL) {
3836     std::swap(LHS, RHS);
3837     std::swap(LHSShift, RHSShift);
3838     std::swap(LHSMask , RHSMask );
3839   }
3840
3841   unsigned OpSizeInBits = VT.getSizeInBits();
3842   SDValue LHSShiftArg = LHSShift.getOperand(0);
3843   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3844   SDValue RHSShiftArg = RHSShift.getOperand(0);
3845   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3846
3847   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3848   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3849   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3850       RHSShiftAmt.getOpcode() == ISD::Constant) {
3851     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3852     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3853     if ((LShVal + RShVal) != OpSizeInBits)
3854       return nullptr;
3855
3856     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3857                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3858
3859     // If there is an AND of either shifted operand, apply it to the result.
3860     if (LHSMask.getNode() || RHSMask.getNode()) {
3861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3862
3863       if (LHSMask.getNode()) {
3864         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3865         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3866       }
3867       if (RHSMask.getNode()) {
3868         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3869         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3870       }
3871
3872       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3873     }
3874
3875     return Rot.getNode();
3876   }
3877
3878   // If there is a mask here, and we have a variable shift, we can't be sure
3879   // that we're masking out the right stuff.
3880   if (LHSMask.getNode() || RHSMask.getNode())
3881     return nullptr;
3882
3883   // If the shift amount is sign/zext/any-extended just peel it off.
3884   SDValue LExtOp0 = LHSShiftAmt;
3885   SDValue RExtOp0 = RHSShiftAmt;
3886   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3887        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3889        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3890       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3894     LExtOp0 = LHSShiftAmt.getOperand(0);
3895     RExtOp0 = RHSShiftAmt.getOperand(0);
3896   }
3897
3898   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3899                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3900   if (TryL)
3901     return TryL;
3902
3903   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3904                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3905   if (TryR)
3906     return TryR;
3907
3908   return nullptr;
3909 }
3910
3911 SDValue DAGCombiner::visitXOR(SDNode *N) {
3912   SDValue N0 = N->getOperand(0);
3913   SDValue N1 = N->getOperand(1);
3914   EVT VT = N0.getValueType();
3915
3916   // fold vector ops
3917   if (VT.isVector()) {
3918     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3919       return FoldedVOp;
3920
3921     // fold (xor x, 0) -> x, vector edition
3922     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3923       return N1;
3924     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3925       return N0;
3926   }
3927
3928   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3929   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3930     return DAG.getConstant(0, SDLoc(N), VT);
3931   // fold (xor x, undef) -> undef
3932   if (N0.getOpcode() == ISD::UNDEF)
3933     return N0;
3934   if (N1.getOpcode() == ISD::UNDEF)
3935     return N1;
3936   // fold (xor c1, c2) -> c1^c2
3937   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3938   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3939   if (N0C && N1C)
3940     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3941   // canonicalize constant to RHS
3942   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3943      !isConstantIntBuildVectorOrConstantInt(N1))
3944     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3945   // fold (xor x, 0) -> x
3946   if (N1C && N1C->isNullValue())
3947     return N0;
3948   // reassociate xor
3949   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3950     return RXOR;
3951
3952   // fold !(x cc y) -> (x !cc y)
3953   SDValue LHS, RHS, CC;
3954   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3955     bool isInt = LHS.getValueType().isInteger();
3956     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3957                                                isInt);
3958
3959     if (!LegalOperations ||
3960         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3961       switch (N0.getOpcode()) {
3962       default:
3963         llvm_unreachable("Unhandled SetCC Equivalent!");
3964       case ISD::SETCC:
3965         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3966       case ISD::SELECT_CC:
3967         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3968                                N0.getOperand(3), NotCC);
3969       }
3970     }
3971   }
3972
3973   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3974   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3975       N0.getNode()->hasOneUse() &&
3976       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3977     SDValue V = N0.getOperand(0);
3978     SDLoc DL(N0);
3979     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3980                     DAG.getConstant(1, DL, V.getValueType()));
3981     AddToWorklist(V.getNode());
3982     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3983   }
3984
3985   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3986   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3987       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3988     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3989     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3990       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3991       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3992       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3993       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3994       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3995     }
3996   }
3997   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3998   if (N1C && N1C->isAllOnesValue() &&
3999       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4000     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4001     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4002       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4003       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4004       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4005       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4006       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4007     }
4008   }
4009   // fold (xor (and x, y), y) -> (and (not x), y)
4010   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4011       N0->getOperand(1) == N1) {
4012     SDValue X = N0->getOperand(0);
4013     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4014     AddToWorklist(NotX.getNode());
4015     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4016   }
4017   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4018   if (N1C && N0.getOpcode() == ISD::XOR) {
4019     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4020     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4021     if (N00C) {
4022       SDLoc DL(N);
4023       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4024                          DAG.getConstant(N1C->getAPIntValue() ^
4025                                          N00C->getAPIntValue(), DL, VT));
4026     }
4027     if (N01C) {
4028       SDLoc DL(N);
4029       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4030                          DAG.getConstant(N1C->getAPIntValue() ^
4031                                          N01C->getAPIntValue(), DL, VT));
4032     }
4033   }
4034   // fold (xor x, x) -> 0
4035   if (N0 == N1)
4036     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4037
4038   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4039   // Here is a concrete example of this equivalence:
4040   // i16   x ==  14
4041   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4042   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4043   //
4044   // =>
4045   //
4046   // i16     ~1      == 0b1111111111111110
4047   // i16 rol(~1, 14) == 0b1011111111111111
4048   //
4049   // Some additional tips to help conceptualize this transform:
4050   // - Try to see the operation as placing a single zero in a value of all ones.
4051   // - There exists no value for x which would allow the result to contain zero.
4052   // - Values of x larger than the bitwidth are undefined and do not require a
4053   //   consistent result.
4054   // - Pushing the zero left requires shifting one bits in from the right.
4055   // A rotate left of ~1 is a nice way of achieving the desired result.
4056   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4057     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4058       if (N0.getOpcode() == ISD::SHL)
4059         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4060           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4061             SDLoc DL(N);
4062             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4063                                N0.getOperand(1));
4064           }
4065
4066   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4067   if (N0.getOpcode() == N1.getOpcode()) {
4068     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4069     if (Tmp.getNode()) return Tmp;
4070   }
4071
4072   // Simplify the expression using non-local knowledge.
4073   if (!VT.isVector() &&
4074       SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   return SDValue();
4078 }
4079
4080 /// Handle transforms common to the three shifts, when the shift amount is a
4081 /// constant.
4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4083   // We can't and shouldn't fold opaque constants.
4084   if (Amt->isOpaque())
4085     return SDValue();
4086
4087   SDNode *LHS = N->getOperand(0).getNode();
4088   if (!LHS->hasOneUse()) return SDValue();
4089
4090   // We want to pull some binops through shifts, so that we have (and (shift))
4091   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4092   // thing happens with address calculations, so it's important to canonicalize
4093   // it.
4094   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4095
4096   switch (LHS->getOpcode()) {
4097   default: return SDValue();
4098   case ISD::OR:
4099   case ISD::XOR:
4100     HighBitSet = false; // We can only transform sra if the high bit is clear.
4101     break;
4102   case ISD::AND:
4103     HighBitSet = true;  // We can only transform sra if the high bit is set.
4104     break;
4105   case ISD::ADD:
4106     if (N->getOpcode() != ISD::SHL)
4107       return SDValue(); // only shl(add) not sr[al](add).
4108     HighBitSet = false; // We can only transform sra if the high bit is clear.
4109     break;
4110   }
4111
4112   // We require the RHS of the binop to be a constant and not opaque as well.
4113   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4114   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115
4116   // FIXME: disable this unless the input to the binop is a shift by a constant.
4117   // If it is not a shift, it pessimizes some common cases like:
4118   //
4119   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4120   //    int bar(int *X, int i) { return X[i & 255]; }
4121   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4122   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4123        BinOpLHSVal->getOpcode() != ISD::SRA &&
4124        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4126     return SDValue();
4127
4128   EVT VT = N->getValueType(0);
4129
4130   // If this is a signed shift right, and the high bit is modified by the
4131   // logical operation, do not perform the transformation. The highBitSet
4132   // boolean indicates the value of the high bit of the constant which would
4133   // cause it to be modified for this operation.
4134   if (N->getOpcode() == ISD::SRA) {
4135     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136     if (BinOpRHSSignSet != HighBitSet)
4137       return SDValue();
4138   }
4139
4140   if (!TLI.isDesirableToCommuteWithShift(LHS))
4141     return SDValue();
4142
4143   // Fold the constants, shifting the binop RHS by the shift amount.
4144   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145                                N->getValueType(0),
4146                                LHS->getOperand(1), N->getOperand(1));
4147   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148
4149   // Create the new shift.
4150   SDValue NewShift = DAG.getNode(N->getOpcode(),
4151                                  SDLoc(LHS->getOperand(0)),
4152                                  VT, LHS->getOperand(0), N->getOperand(1));
4153
4154   // Create the new binop.
4155   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4156 }
4157
4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159   assert(N->getOpcode() == ISD::TRUNCATE);
4160   assert(N->getOperand(0).getOpcode() == ISD::AND);
4161
4162   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164     SDValue N01 = N->getOperand(0).getOperand(1);
4165
4166     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4167       EVT TruncVT = N->getValueType(0);
4168       SDValue N00 = N->getOperand(0).getOperand(0);
4169       APInt TruncC = N01C->getAPIntValue();
4170       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4171       SDLoc DL(N);
4172
4173       return DAG.getNode(ISD::AND, DL, TruncVT,
4174                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175                          DAG.getConstant(TruncC, DL, TruncVT));
4176     }
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 SDValue DAGCombiner::visitRotate(SDNode *N) {
4183   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187     if (NewOp1.getNode())
4188       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189                          N->getOperand(0), NewOp1);
4190   }
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitSHL(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   SDValue N1 = N->getOperand(1);
4197   EVT VT = N0.getValueType();
4198   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4199
4200   // fold vector ops
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   if (VT.isVector()) {
4203     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4204       return FoldedVOp;
4205
4206     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207     // If setcc produces all-one true value then:
4208     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4209     if (N1CV && N1CV->isConstant()) {
4210       if (N0.getOpcode() == ISD::AND) {
4211         SDValue N00 = N0->getOperand(0);
4212         SDValue N01 = N0->getOperand(1);
4213         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214
4215         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4218           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219                                                      N01CV, N1CV))
4220             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4221         }
4222       } else {
4223         N1C = isConstOrConstSplat(N1);
4224       }
4225     }
4226   }
4227
4228   // fold (shl c1, c2) -> c1<<c2
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   if (N0C && N1C)
4231     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4232   // fold (shl 0, x) -> 0
4233   if (N0C && N0C->isNullValue())
4234     return N0;
4235   // fold (shl x, c >= size(x)) -> undef
4236   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4237     return DAG.getUNDEF(VT);
4238   // fold (shl x, 0) -> x
4239   if (N1C && N1C->isNullValue())
4240     return N0;
4241   // fold (shl undef, x) -> 0
4242   if (N0.getOpcode() == ISD::UNDEF)
4243     return DAG.getConstant(0, SDLoc(N), VT);
4244   // if (shl x, c) is known to be zero, return 0
4245   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4246                             APInt::getAllOnesValue(OpSizeInBits)))
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4249   if (N1.getOpcode() == ISD::TRUNCATE &&
4250       N1.getOperand(0).getOpcode() == ISD::AND) {
4251     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252     if (NewOp1.getNode())
4253       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4254   }
4255
4256   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257     return SDValue(N, 0);
4258
4259   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4260   if (N1C && N0.getOpcode() == ISD::SHL) {
4261     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262       uint64_t c1 = N0C1->getZExtValue();
4263       uint64_t c2 = N1C->getZExtValue();
4264       SDLoc DL(N);
4265       if (c1 + c2 >= OpSizeInBits)
4266         return DAG.getConstant(0, DL, VT);
4267       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4269     }
4270   }
4271
4272   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273   // For this to be valid, the second form must not preserve any of the bits
4274   // that are shifted out by the inner shift in the first form.  This means
4275   // the outer shift size must be >= the number of bits added by the ext.
4276   // As a corollary, we don't care what kind of ext it is.
4277   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278               N0.getOpcode() == ISD::ANY_EXTEND ||
4279               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4280       N0.getOperand(0).getOpcode() == ISD::SHL) {
4281     SDValue N0Op0 = N0.getOperand(0);
4282     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283       uint64_t c1 = N0Op0C1->getZExtValue();
4284       uint64_t c2 = N1C->getZExtValue();
4285       EVT InnerShiftVT = N0Op0.getValueType();
4286       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287       if (c2 >= OpSizeInBits - InnerShiftSize) {
4288         SDLoc DL(N0);
4289         if (c1 + c2 >= OpSizeInBits)
4290           return DAG.getConstant(0, DL, VT);
4291         return DAG.getNode(ISD::SHL, DL, VT,
4292                            DAG.getNode(N0.getOpcode(), DL, VT,
4293                                        N0Op0->getOperand(0)),
4294                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4295       }
4296     }
4297   }
4298
4299   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300   // Only fold this if the inner zext has no other uses to avoid increasing
4301   // the total number of instructions.
4302   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4303       N0.getOperand(0).getOpcode() == ISD::SRL) {
4304     SDValue N0Op0 = N0.getOperand(0);
4305     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306       uint64_t c1 = N0Op0C1->getZExtValue();
4307       if (c1 < VT.getScalarSizeInBits()) {
4308         uint64_t c2 = N1C->getZExtValue();
4309         if (c1 == c2) {
4310           SDValue NewOp0 = N0.getOperand(0);
4311           EVT CountVT = NewOp0.getOperand(1).getValueType();
4312           SDLoc DL(N);
4313           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314                                        NewOp0,
4315                                        DAG.getConstant(c2, DL, CountVT));
4316           AddToWorklist(NewSHL.getNode());
4317           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4318         }
4319       }
4320     }
4321   }
4322
4323   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324   //                               (and (srl x, (sub c1, c2), MASK)
4325   // Only fold this if the inner shift has no other uses -- if it does, folding
4326   // this will increase the total number of instructions.
4327   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329       uint64_t c1 = N0C1->getZExtValue();
4330       if (c1 < OpSizeInBits) {
4331         uint64_t c2 = N1C->getZExtValue();
4332         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4333         SDValue Shift;
4334         if (c2 > c1) {
4335           Mask = Mask.shl(c2 - c1);
4336           SDLoc DL(N);
4337           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339         } else {
4340           Mask = Mask.lshr(c1 - c2);
4341           SDLoc DL(N);
4342           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4344         }
4345         SDLoc DL(N0);
4346         return DAG.getNode(ISD::AND, DL, VT, Shift,
4347                            DAG.getConstant(Mask, DL, VT));
4348       }
4349     }
4350   }
4351   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4352   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4353     unsigned BitSize = VT.getScalarSizeInBits();
4354     SDLoc DL(N);
4355     SDValue HiBitsMask =
4356       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4357                                             BitSize - N1C->getZExtValue()),
4358                       DL, VT);
4359     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4360                        HiBitsMask);
4361   }
4362
4363   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364   // Variant of version done on multiply, except mul by a power of 2 is turned
4365   // into a shift.
4366   APInt Val;
4367   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4373   }
4374
4375   if (N1C) {
4376     SDValue NewSHL = visitShiftByConstant(N, N1C);
4377     if (NewSHL.getNode())
4378       return NewSHL;
4379   }
4380
4381   return SDValue();
4382 }
4383
4384 SDValue DAGCombiner::visitSRA(SDNode *N) {
4385   SDValue N0 = N->getOperand(0);
4386   SDValue N1 = N->getOperand(1);
4387   EVT VT = N0.getValueType();
4388   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4389
4390   // fold vector ops
4391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392   if (VT.isVector()) {
4393     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4394       return FoldedVOp;
4395
4396     N1C = isConstOrConstSplat(N1);
4397   }
4398
4399   // fold (sra c1, c2) -> (sra c1, c2)
4400   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401   if (N0C && N1C)
4402     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4403   // fold (sra 0, x) -> 0
4404   if (N0C && N0C->isNullValue())
4405     return N0;
4406   // fold (sra -1, x) -> -1
4407   if (N0C && N0C->isAllOnesValue())
4408     return N0;
4409   // fold (sra x, (setge c, size(x))) -> undef
4410   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4411     return DAG.getUNDEF(VT);
4412   // fold (sra x, 0) -> x
4413   if (N1C && N1C->isNullValue())
4414     return N0;
4415   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416   // sext_inreg.
4417   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4418     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4419     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420     if (VT.isVector())
4421       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422                                ExtVT, VT.getVectorNumElements());
4423     if ((!LegalOperations ||
4424          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4425       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4426                          N0.getOperand(0), DAG.getValueType(ExtVT));
4427   }
4428
4429   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4430   if (N1C && N0.getOpcode() == ISD::SRA) {
4431     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4432       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4433       if (Sum >= OpSizeInBits)
4434         Sum = OpSizeInBits - 1;
4435       SDLoc DL(N);
4436       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437                          DAG.getConstant(Sum, DL, N1.getValueType()));
4438     }
4439   }
4440
4441   // fold (sra (shl X, m), (sub result_size, n))
4442   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4443   // result_size - n != m.
4444   // If truncate is free for the target sext(shl) is likely to result in better
4445   // code.
4446   if (N0.getOpcode() == ISD::SHL && N1C) {
4447     // Get the two constanst of the shifts, CN0 = m, CN = n.
4448     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449     if (N01C) {
4450       LLVMContext &Ctx = *DAG.getContext();
4451       // Determine what the truncate's result bitsize and type would be.
4452       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4453
4454       if (VT.isVector())
4455         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456
4457       // Determine the residual right-shift amount.
4458       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459
4460       // If the shift is not a no-op (in which case this should be just a sign
4461       // extend already), the truncated to type is legal, sign_extend is legal
4462       // on that type, and the truncate to that type is both legal and free,
4463       // perform the transform.
4464       if ((ShiftAmt > 0) &&
4465           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4467           TLI.isTruncateFree(VT, TruncVT)) {
4468
4469         SDLoc DL(N);
4470         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471             getShiftAmountTy(N0.getOperand(0).getValueType()));
4472         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473                                     N0.getOperand(0), Amt);
4474         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475                                     Shift);
4476         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477                            N->getValueType(0), Trunc);
4478       }
4479     }
4480   }
4481
4482   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486     if (NewOp1.getNode())
4487       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4488   }
4489
4490   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4491   //      if c1 is equal to the number of bits the trunc removes
4492   if (N0.getOpcode() == ISD::TRUNCATE &&
4493       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495       N0.getOperand(0).hasOneUse() &&
4496       N0.getOperand(0).getOperand(1).hasOneUse() &&
4497       N1C) {
4498     SDValue N0Op0 = N0.getOperand(0);
4499     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500       unsigned LargeShiftVal = LargeShift->getZExtValue();
4501       EVT LargeVT = N0Op0.getValueType();
4502
4503       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4504         SDLoc DL(N);
4505         SDValue Amt =
4506           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4507                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4508         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4509                                   N0Op0.getOperand(0), Amt);
4510         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4511       }
4512     }
4513   }
4514
4515   // Simplify, based on bits shifted out of the LHS.
4516   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517     return SDValue(N, 0);
4518
4519
4520   // If the sign bit is known to be zero, switch this to a SRL.
4521   if (DAG.SignBitIsZero(N0))
4522     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4523
4524   if (N1C) {
4525     SDValue NewSRA = visitShiftByConstant(N, N1C);
4526     if (NewSRA.getNode())
4527       return NewSRA;
4528   }
4529
4530   return SDValue();
4531 }
4532
4533 SDValue DAGCombiner::visitSRL(SDNode *N) {
4534   SDValue N0 = N->getOperand(0);
4535   SDValue N1 = N->getOperand(1);
4536   EVT VT = N0.getValueType();
4537   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4538
4539   // fold vector ops
4540   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4541   if (VT.isVector()) {
4542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4543       return FoldedVOp;
4544
4545     N1C = isConstOrConstSplat(N1);
4546   }
4547
4548   // fold (srl c1, c2) -> c1 >>u c2
4549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550   if (N0C && N1C)
4551     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4552   // fold (srl 0, x) -> 0
4553   if (N0C && N0C->isNullValue())
4554     return N0;
4555   // fold (srl x, c >= size(x)) -> undef
4556   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4557     return DAG.getUNDEF(VT);
4558   // fold (srl x, 0) -> x
4559   if (N1C && N1C->isNullValue())
4560     return N0;
4561   // if (srl x, c) is known to be zero, return 0
4562   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4563                                    APInt::getAllOnesValue(OpSizeInBits)))
4564     return DAG.getConstant(0, SDLoc(N), VT);
4565
4566   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4567   if (N1C && N0.getOpcode() == ISD::SRL) {
4568     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569       uint64_t c1 = N01C->getZExtValue();
4570       uint64_t c2 = N1C->getZExtValue();
4571       SDLoc DL(N);
4572       if (c1 + c2 >= OpSizeInBits)
4573         return DAG.getConstant(0, DL, VT);
4574       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4576     }
4577   }
4578
4579   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4580   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581       N0.getOperand(0).getOpcode() == ISD::SRL &&
4582       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583     uint64_t c1 =
4584       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585     uint64_t c2 = N1C->getZExtValue();
4586     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4588     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4589     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4590     if (c1 + OpSizeInBits == InnerShiftSize) {
4591       SDLoc DL(N0);
4592       if (c1 + c2 >= InnerShiftSize)
4593         return DAG.getConstant(0, DL, VT);
4594       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4596                                      N0.getOperand(0)->getOperand(0),
4597                                      DAG.getConstant(c1 + c2, DL,
4598                                                      ShiftCountVT)));
4599     }
4600   }
4601
4602   // fold (srl (shl x, c), c) -> (and x, cst2)
4603   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604     unsigned BitSize = N0.getScalarValueSizeInBits();
4605     if (BitSize <= 64) {
4606       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607       SDLoc DL(N);
4608       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4610     }
4611   }
4612
4613   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4614   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615     // Shifting in all undef bits?
4616     EVT SmallVT = N0.getOperand(0).getValueType();
4617     unsigned BitSize = SmallVT.getScalarSizeInBits();
4618     if (N1C->getZExtValue() >= BitSize)
4619       return DAG.getUNDEF(VT);
4620
4621     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4622       uint64_t ShiftAmt = N1C->getZExtValue();
4623       SDLoc DL0(N0);
4624       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625                                        N0.getOperand(0),
4626                           DAG.getConstant(ShiftAmt, DL0,
4627                                           getShiftAmountTy(SmallVT)));
4628       AddToWorklist(SmallShift.getNode());
4629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630       SDLoc DL(N);
4631       return DAG.getNode(ISD::AND, DL, VT,
4632                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633                          DAG.getConstant(Mask, DL, VT));
4634     }
4635   }
4636
4637   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4638   // bit, which is unmodified by sra.
4639   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4640     if (N0.getOpcode() == ISD::SRA)
4641       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4642   }
4643
4644   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4645   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4646       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4647     APInt KnownZero, KnownOne;
4648     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649
4650     // If any of the input bits are KnownOne, then the input couldn't be all
4651     // zeros, thus the result of the srl will always be zero.
4652     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653
4654     // If all of the bits input the to ctlz node are known to be zero, then
4655     // the result of the ctlz is "32" and the result of the shift is one.
4656     APInt UnknownBits = ~KnownZero;
4657     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658
4659     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4660     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4661       // Okay, we know that only that the single bit specified by UnknownBits
4662       // could be set on input to the CTLZ node. If this bit is set, the SRL
4663       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664       // to an SRL/XOR pair, which is likely to simplify more.
4665       unsigned ShAmt = UnknownBits.countTrailingZeros();
4666       SDValue Op = N0.getOperand(0);
4667
4668       if (ShAmt) {
4669         SDLoc DL(N0);
4670         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671                   DAG.getConstant(ShAmt, DL,
4672                                   getShiftAmountTy(Op.getValueType())));
4673         AddToWorklist(Op.getNode());
4674       }
4675
4676       SDLoc DL(N);
4677       return DAG.getNode(ISD::XOR, DL, VT,
4678                          Op, DAG.getConstant(1, DL, VT));
4679     }
4680   }
4681
4682   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4683   if (N1.getOpcode() == ISD::TRUNCATE &&
4684       N1.getOperand(0).getOpcode() == ISD::AND) {
4685     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686     if (NewOp1.getNode())
4687       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4688   }
4689
4690   // fold operands of srl based on knowledge that the low bits are not
4691   // demanded.
4692   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693     return SDValue(N, 0);
4694
4695   if (N1C) {
4696     SDValue NewSRL = visitShiftByConstant(N, N1C);
4697     if (NewSRL.getNode())
4698       return NewSRL;
4699   }
4700
4701   // Attempt to convert a srl of a load into a narrower zero-extending load.
4702   SDValue NarrowLoad = ReduceLoadWidth(N);
4703   if (NarrowLoad.getNode())
4704     return NarrowLoad;
4705
4706   // Here is a common situation. We want to optimize:
4707   //
4708   //   %a = ...
4709   //   %b = and i32 %a, 2
4710   //   %c = srl i32 %b, 1
4711   //   brcond i32 %c ...
4712   //
4713   // into
4714   //
4715   //   %a = ...
4716   //   %b = and %a, 2
4717   //   %c = setcc eq %b, 0
4718   //   brcond %c ...
4719   //
4720   // However when after the source operand of SRL is optimized into AND, the SRL
4721   // itself may not be optimized further. Look for it and add the BRCOND into
4722   // the worklist.
4723   if (N->hasOneUse()) {
4724     SDNode *Use = *N->use_begin();
4725     if (Use->getOpcode() == ISD::BRCOND)
4726       AddToWorklist(Use);
4727     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728       // Also look pass the truncate.
4729       Use = *Use->use_begin();
4730       if (Use->getOpcode() == ISD::BRCOND)
4731         AddToWorklist(Use);
4732     }
4733   }
4734
4735   return SDValue();
4736 }
4737
4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739   SDValue N0 = N->getOperand(0);
4740   EVT VT = N->getValueType(0);
4741
4742   // fold (ctlz c1) -> c2
4743   if (isa<ConstantSDNode>(N0))
4744     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4745   return SDValue();
4746 }
4747
4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749   SDValue N0 = N->getOperand(0);
4750   EVT VT = N->getValueType(0);
4751
4752   // fold (ctlz_zero_undef c1) -> c2
4753   if (isa<ConstantSDNode>(N0))
4754     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4755   return SDValue();
4756 }
4757
4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759   SDValue N0 = N->getOperand(0);
4760   EVT VT = N->getValueType(0);
4761
4762   // fold (cttz c1) -> c2
4763   if (isa<ConstantSDNode>(N0))
4764     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4765   return SDValue();
4766 }
4767
4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769   SDValue N0 = N->getOperand(0);
4770   EVT VT = N->getValueType(0);
4771
4772   // fold (cttz_zero_undef c1) -> c2
4773   if (isa<ConstantSDNode>(N0))
4774     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4775   return SDValue();
4776 }
4777
4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779   SDValue N0 = N->getOperand(0);
4780   EVT VT = N->getValueType(0);
4781
4782   // fold (ctpop c1) -> c2
4783   if (isa<ConstantSDNode>(N0))
4784     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4785   return SDValue();
4786 }
4787
4788
4789 /// \brief Generate Min/Max node
4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791                                    SDValue True, SDValue False,
4792                                    ISD::CondCode CC, const TargetLowering &TLI,
4793                                    SelectionDAG &DAG) {
4794   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4795     return SDValue();
4796
4797   switch (CC) {
4798   case ISD::SETOLT:
4799   case ISD::SETOLE:
4800   case ISD::SETLT:
4801   case ISD::SETLE:
4802   case ISD::SETULT:
4803   case ISD::SETULE: {
4804     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805     if (TLI.isOperationLegal(Opcode, VT))
4806       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4807     return SDValue();
4808   }
4809   case ISD::SETOGT:
4810   case ISD::SETOGE:
4811   case ISD::SETGT:
4812   case ISD::SETGE:
4813   case ISD::SETUGT:
4814   case ISD::SETUGE: {
4815     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816     if (TLI.isOperationLegal(Opcode, VT))
4817       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4818     return SDValue();
4819   }
4820   default:
4821     return SDValue();
4822   }
4823 }
4824
4825 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   SDValue N1 = N->getOperand(1);
4828   SDValue N2 = N->getOperand(2);
4829   EVT VT = N->getValueType(0);
4830   EVT VT0 = N0.getValueType();
4831
4832   // fold (select C, X, X) -> X
4833   if (N1 == N2)
4834     return N1;
4835   // fold (select true, X, Y) -> X
4836   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4837   if (N0C && !N0C->isNullValue())
4838     return N1;
4839   // fold (select false, X, Y) -> Y
4840   if (N0C && N0C->isNullValue())
4841     return N2;
4842   // fold (select C, 1, X) -> (or C, X)
4843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4844   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4845     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4846   // fold (select C, 0, 1) -> (xor C, 1)
4847   // We can't do this reliably if integer based booleans have different contents
4848   // to floating point based booleans. This is because we can't tell whether we
4849   // have an integer-based boolean or a floating-point-based boolean unless we
4850   // can find the SETCC that produced it and inspect its operands. This is
4851   // fairly easy if C is the SETCC node, but it can potentially be
4852   // undiscoverable (or not reasonably discoverable). For example, it could be
4853   // in another basic block or it could require searching a complicated
4854   // expression.
4855   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4856   if (VT.isInteger() &&
4857       (VT0 == MVT::i1 || (VT0.isInteger() &&
4858                           TLI.getBooleanContents(false, false) ==
4859                               TLI.getBooleanContents(false, true) &&
4860                           TLI.getBooleanContents(false, false) ==
4861                               TargetLowering::ZeroOrOneBooleanContent)) &&
4862       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4863     SDValue XORNode;
4864     if (VT == VT0) {
4865       SDLoc DL(N);
4866       return DAG.getNode(ISD::XOR, DL, VT0,
4867                          N0, DAG.getConstant(1, DL, VT0));
4868     }
4869     SDLoc DL0(N0);
4870     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4871                           N0, DAG.getConstant(1, DL0, VT0));
4872     AddToWorklist(XORNode.getNode());
4873     if (VT.bitsGT(VT0))
4874       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4875     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4876   }
4877   // fold (select C, 0, X) -> (and (not C), X)
4878   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4879     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4880     AddToWorklist(NOTNode.getNode());
4881     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4882   }
4883   // fold (select C, X, 1) -> (or (not C), X)
4884   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4885     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4886     AddToWorklist(NOTNode.getNode());
4887     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4888   }
4889   // fold (select C, X, 0) -> (and C, X)
4890   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4891     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4892   // fold (select X, X, Y) -> (or X, Y)
4893   // fold (select X, 1, Y) -> (or X, Y)
4894   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4895     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4896   // fold (select X, Y, X) -> (and X, Y)
4897   // fold (select X, Y, 0) -> (and X, Y)
4898   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4899     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4900
4901   // If we can fold this based on the true/false value, do so.
4902   if (SimplifySelectOps(N, N1, N2))
4903     return SDValue(N, 0);  // Don't revisit N.
4904
4905   // fold selects based on a setcc into other things, such as min/max/abs
4906   if (N0.getOpcode() == ISD::SETCC) {
4907     // select x, y (fcmp lt x, y) -> fminnum x, y
4908     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4909     //
4910     // This is OK if we don't care about what happens if either operand is a
4911     // NaN.
4912     //
4913
4914     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4915     // no signed zeros as well as no nans.
4916     const TargetOptions &Options = DAG.getTarget().Options;
4917     if (Options.UnsafeFPMath &&
4918         VT.isFloatingPoint() && N0.hasOneUse() &&
4919         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4920       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4921
4922       SDValue FMinMax =
4923           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4924                               N1, N2, CC, TLI, DAG);
4925       if (FMinMax)
4926         return FMinMax;
4927     }
4928
4929     if ((!LegalOperations &&
4930          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4931         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4932       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4933                          N0.getOperand(0), N0.getOperand(1),
4934                          N1, N2, N0.getOperand(2));
4935     return SimplifySelect(SDLoc(N), N0, N1, N2);
4936   }
4937
4938   if (VT0 == MVT::i1) {
4939     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4940       // select (and Cond0, Cond1), X, Y
4941       //   -> select Cond0, (select Cond1, X, Y), Y
4942       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4943         SDValue Cond0 = N0->getOperand(0);
4944         SDValue Cond1 = N0->getOperand(1);
4945         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4946                                           N1.getValueType(), Cond1, N1, N2);
4947         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4948                            InnerSelect, N2);
4949       }
4950       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4951       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4952         SDValue Cond0 = N0->getOperand(0);
4953         SDValue Cond1 = N0->getOperand(1);
4954         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4955                                           N1.getValueType(), Cond1, N1, N2);
4956         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4957                            InnerSelect);
4958       }
4959     }
4960
4961     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4962     if (N1->getOpcode() == ISD::SELECT) {
4963       SDValue N1_0 = N1->getOperand(0);
4964       SDValue N1_1 = N1->getOperand(1);
4965       SDValue N1_2 = N1->getOperand(2);
4966       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4967         // Create the actual and node if we can generate good code for it.
4968         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4969           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4970                                     N0, N1_0);
4971           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4972                              N1_1, N2);
4973         }
4974         // Otherwise see if we can optimize the "and" to a better pattern.
4975         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4976           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4977                              N1_1, N2);
4978       }
4979     }
4980     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4981     if (N2->getOpcode() == ISD::SELECT) {
4982       SDValue N2_0 = N2->getOperand(0);
4983       SDValue N2_1 = N2->getOperand(1);
4984       SDValue N2_2 = N2->getOperand(2);
4985       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4986         // Create the actual or node if we can generate good code for it.
4987         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4988           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4989                                    N0, N2_0);
4990           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4991                              N1, N2_2);
4992         }
4993         // Otherwise see if we can optimize to a better pattern.
4994         if (SDValue Combined = visitORLike(N0, N2_0, N))
4995           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4996                              N1, N2_2);
4997       }
4998     }
4999   }
5000
5001   return SDValue();
5002 }
5003
5004 static
5005 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5006   SDLoc DL(N);
5007   EVT LoVT, HiVT;
5008   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5009
5010   // Split the inputs.
5011   SDValue Lo, Hi, LL, LH, RL, RH;
5012   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5013   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5014
5015   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5016   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5017
5018   return std::make_pair(Lo, Hi);
5019 }
5020
5021 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5022 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5023 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5024   SDLoc dl(N);
5025   SDValue Cond = N->getOperand(0);
5026   SDValue LHS = N->getOperand(1);
5027   SDValue RHS = N->getOperand(2);
5028   EVT VT = N->getValueType(0);
5029   int NumElems = VT.getVectorNumElements();
5030   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5031          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5032          Cond.getOpcode() == ISD::BUILD_VECTOR);
5033
5034   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5035   // binary ones here.
5036   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5037     return SDValue();
5038
5039   // We're sure we have an even number of elements due to the
5040   // concat_vectors we have as arguments to vselect.
5041   // Skip BV elements until we find one that's not an UNDEF
5042   // After we find an UNDEF element, keep looping until we get to half the
5043   // length of the BV and see if all the non-undef nodes are the same.
5044   ConstantSDNode *BottomHalf = nullptr;
5045   for (int i = 0; i < NumElems / 2; ++i) {
5046     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5047       continue;
5048
5049     if (BottomHalf == nullptr)
5050       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5051     else if (Cond->getOperand(i).getNode() != BottomHalf)
5052       return SDValue();
5053   }
5054
5055   // Do the same for the second half of the BuildVector
5056   ConstantSDNode *TopHalf = nullptr;
5057   for (int i = NumElems / 2; i < NumElems; ++i) {
5058     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5059       continue;
5060
5061     if (TopHalf == nullptr)
5062       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5063     else if (Cond->getOperand(i).getNode() != TopHalf)
5064       return SDValue();
5065   }
5066
5067   assert(TopHalf && BottomHalf &&
5068          "One half of the selector was all UNDEFs and the other was all the "
5069          "same value. This should have been addressed before this function.");
5070   return DAG.getNode(
5071       ISD::CONCAT_VECTORS, dl, VT,
5072       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5073       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5074 }
5075
5076 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5077
5078   if (Level >= AfterLegalizeTypes)
5079     return SDValue();
5080
5081   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5082   SDValue Mask = MST->getMask();
5083   SDValue Data  = MST->getValue();
5084   SDLoc DL(N);
5085
5086   // If the MSTORE data type requires splitting and the mask is provided by a
5087   // SETCC, then split both nodes and its operands before legalization. This
5088   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5089   // and enables future optimizations (e.g. min/max pattern matching on X86).
5090   if (Mask.getOpcode() == ISD::SETCC) {
5091
5092     // Check if any splitting is required.
5093     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5094         TargetLowering::TypeSplitVector)
5095       return SDValue();
5096
5097     SDValue MaskLo, MaskHi, Lo, Hi;
5098     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5099
5100     EVT LoVT, HiVT;
5101     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5102
5103     SDValue Chain = MST->getChain();
5104     SDValue Ptr   = MST->getBasePtr();
5105
5106     EVT MemoryVT = MST->getMemoryVT();
5107     unsigned Alignment = MST->getOriginalAlignment();
5108
5109     // if Alignment is equal to the vector size,
5110     // take the half of it for the second part
5111     unsigned SecondHalfAlignment =
5112       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5113          Alignment/2 : Alignment;
5114
5115     EVT LoMemVT, HiMemVT;
5116     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5117
5118     SDValue DataLo, DataHi;
5119     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5120
5121     MachineMemOperand *MMO = DAG.getMachineFunction().
5122       getMachineMemOperand(MST->getPointerInfo(),
5123                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5124                            Alignment, MST->getAAInfo(), MST->getRanges());
5125
5126     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5127                             MST->isTruncatingStore());
5128
5129     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5130     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5131                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5132
5133     MMO = DAG.getMachineFunction().
5134       getMachineMemOperand(MST->getPointerInfo(),
5135                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5136                            SecondHalfAlignment, MST->getAAInfo(),
5137                            MST->getRanges());
5138
5139     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5140                             MST->isTruncatingStore());
5141
5142     AddToWorklist(Lo.getNode());
5143     AddToWorklist(Hi.getNode());
5144
5145     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5146   }
5147   return SDValue();
5148 }
5149
5150 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5151
5152   if (Level >= AfterLegalizeTypes)
5153     return SDValue();
5154
5155   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5156   SDValue Mask = MLD->getMask();
5157   SDLoc DL(N);
5158
5159   // If the MLOAD result requires splitting and the mask is provided by a
5160   // SETCC, then split both nodes and its operands before legalization. This
5161   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5162   // and enables future optimizations (e.g. min/max pattern matching on X86).
5163
5164   if (Mask.getOpcode() == ISD::SETCC) {
5165     EVT VT = N->getValueType(0);
5166
5167     // Check if any splitting is required.
5168     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5169         TargetLowering::TypeSplitVector)
5170       return SDValue();
5171
5172     SDValue MaskLo, MaskHi, Lo, Hi;
5173     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5174
5175     SDValue Src0 = MLD->getSrc0();
5176     SDValue Src0Lo, Src0Hi;
5177     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5178
5179     EVT LoVT, HiVT;
5180     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5181
5182     SDValue Chain = MLD->getChain();
5183     SDValue Ptr   = MLD->getBasePtr();
5184     EVT MemoryVT = MLD->getMemoryVT();
5185     unsigned Alignment = MLD->getOriginalAlignment();
5186
5187     // if Alignment is equal to the vector size,
5188     // take the half of it for the second part
5189     unsigned SecondHalfAlignment =
5190       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5191          Alignment/2 : Alignment;
5192
5193     EVT LoMemVT, HiMemVT;
5194     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5195
5196     MachineMemOperand *MMO = DAG.getMachineFunction().
5197     getMachineMemOperand(MLD->getPointerInfo(),
5198                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5199                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5200
5201     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5202                            ISD::NON_EXTLOAD);
5203
5204     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5205     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5206                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5207
5208     MMO = DAG.getMachineFunction().
5209     getMachineMemOperand(MLD->getPointerInfo(),
5210                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5211                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5212
5213     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5214                            ISD::NON_EXTLOAD);
5215
5216     AddToWorklist(Lo.getNode());
5217     AddToWorklist(Hi.getNode());
5218
5219     // Build a factor node to remember that this load is independent of the
5220     // other one.
5221     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5222                         Hi.getValue(1));
5223
5224     // Legalized the chain result - switch anything that used the old chain to
5225     // use the new one.
5226     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5227
5228     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5229
5230     SDValue RetOps[] = { LoadRes, Chain };
5231     return DAG.getMergeValues(RetOps, DL);
5232   }
5233   return SDValue();
5234 }
5235
5236 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5237   SDValue N0 = N->getOperand(0);
5238   SDValue N1 = N->getOperand(1);
5239   SDValue N2 = N->getOperand(2);
5240   SDLoc DL(N);
5241
5242   // Canonicalize integer abs.
5243   // vselect (setg[te] X,  0),  X, -X ->
5244   // vselect (setgt    X, -1),  X, -X ->
5245   // vselect (setl[te] X,  0), -X,  X ->
5246   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5247   if (N0.getOpcode() == ISD::SETCC) {
5248     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5249     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5250     bool isAbs = false;
5251     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5252
5253     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5254          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5255         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5256       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5257     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5258              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5259       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5260
5261     if (isAbs) {
5262       EVT VT = LHS.getValueType();
5263       SDValue Shift = DAG.getNode(
5264           ISD::SRA, DL, VT, LHS,
5265           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5266       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5267       AddToWorklist(Shift.getNode());
5268       AddToWorklist(Add.getNode());
5269       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5270     }
5271   }
5272
5273   if (SimplifySelectOps(N, N1, N2))
5274     return SDValue(N, 0);  // Don't revisit N.
5275
5276   // If the VSELECT result requires splitting and the mask is provided by a
5277   // SETCC, then split both nodes and its operands before legalization. This
5278   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5279   // and enables future optimizations (e.g. min/max pattern matching on X86).
5280   if (N0.getOpcode() == ISD::SETCC) {
5281     EVT VT = N->getValueType(0);
5282
5283     // Check if any splitting is required.
5284     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5285         TargetLowering::TypeSplitVector)
5286       return SDValue();
5287
5288     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5289     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5290     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5291     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5292
5293     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5294     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5295
5296     // Add the new VSELECT nodes to the work list in case they need to be split
5297     // again.
5298     AddToWorklist(Lo.getNode());
5299     AddToWorklist(Hi.getNode());
5300
5301     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5302   }
5303
5304   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5305   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5306     return N1;
5307   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5308   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5309     return N2;
5310
5311   // The ConvertSelectToConcatVector function is assuming both the above
5312   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5313   // and addressed.
5314   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5315       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5316       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5317     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5318     if (CV.getNode())
5319       return CV;
5320   }
5321
5322   return SDValue();
5323 }
5324
5325 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5326   SDValue N0 = N->getOperand(0);
5327   SDValue N1 = N->getOperand(1);
5328   SDValue N2 = N->getOperand(2);
5329   SDValue N3 = N->getOperand(3);
5330   SDValue N4 = N->getOperand(4);
5331   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5332
5333   // fold select_cc lhs, rhs, x, x, cc -> x
5334   if (N2 == N3)
5335     return N2;
5336
5337   // Determine if the condition we're dealing with is constant
5338   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5339                               N0, N1, CC, SDLoc(N), false);
5340   if (SCC.getNode()) {
5341     AddToWorklist(SCC.getNode());
5342
5343     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5344       if (!SCCC->isNullValue())
5345         return N2;    // cond always true -> true val
5346       else
5347         return N3;    // cond always false -> false val
5348     } else if (SCC->getOpcode() == ISD::UNDEF) {
5349       // When the condition is UNDEF, just return the first operand. This is
5350       // coherent the DAG creation, no setcc node is created in this case
5351       return N2;
5352     } else if (SCC.getOpcode() == ISD::SETCC) {
5353       // Fold to a simpler select_cc
5354       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5355                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5356                          SCC.getOperand(2));
5357     }
5358   }
5359
5360   // If we can fold this based on the true/false value, do so.
5361   if (SimplifySelectOps(N, N2, N3))
5362     return SDValue(N, 0);  // Don't revisit N.
5363
5364   // fold select_cc into other things, such as min/max/abs
5365   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5366 }
5367
5368 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5369   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5370                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5371                        SDLoc(N));
5372 }
5373
5374 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5375 // dag node into a ConstantSDNode or a build_vector of constants.
5376 // This function is called by the DAGCombiner when visiting sext/zext/aext
5377 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5378 // Vector extends are not folded if operations are legal; this is to
5379 // avoid introducing illegal build_vector dag nodes.
5380 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5381                                          SelectionDAG &DAG, bool LegalTypes,
5382                                          bool LegalOperations) {
5383   unsigned Opcode = N->getOpcode();
5384   SDValue N0 = N->getOperand(0);
5385   EVT VT = N->getValueType(0);
5386
5387   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5388          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5389
5390   // fold (sext c1) -> c1
5391   // fold (zext c1) -> c1
5392   // fold (aext c1) -> c1
5393   if (isa<ConstantSDNode>(N0))
5394     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5395
5396   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5397   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5398   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5399   EVT SVT = VT.getScalarType();
5400   if (!(VT.isVector() &&
5401       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5402       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5403     return nullptr;
5404
5405   // We can fold this node into a build_vector.
5406   unsigned VTBits = SVT.getSizeInBits();
5407   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5408   unsigned ShAmt = VTBits - EVTBits;
5409   SmallVector<SDValue, 8> Elts;
5410   unsigned NumElts = N0->getNumOperands();
5411   SDLoc DL(N);
5412
5413   for (unsigned i=0; i != NumElts; ++i) {
5414     SDValue Op = N0->getOperand(i);
5415     if (Op->getOpcode() == ISD::UNDEF) {
5416       Elts.push_back(DAG.getUNDEF(SVT));
5417       continue;
5418     }
5419
5420     SDLoc DL(Op);
5421     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5422     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5423     if (Opcode == ISD::SIGN_EXTEND)
5424       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5425                                      DL, SVT));
5426     else
5427       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5428                                      DL, SVT));
5429   }
5430
5431   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5432 }
5433
5434 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5435 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5436 // transformation. Returns true if extension are possible and the above
5437 // mentioned transformation is profitable.
5438 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5439                                     unsigned ExtOpc,
5440                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5441                                     const TargetLowering &TLI) {
5442   bool HasCopyToRegUses = false;
5443   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5444   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5445                             UE = N0.getNode()->use_end();
5446        UI != UE; ++UI) {
5447     SDNode *User = *UI;
5448     if (User == N)
5449       continue;
5450     if (UI.getUse().getResNo() != N0.getResNo())
5451       continue;
5452     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5453     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5454       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5455       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5456         // Sign bits will be lost after a zext.
5457         return false;
5458       bool Add = false;
5459       for (unsigned i = 0; i != 2; ++i) {
5460         SDValue UseOp = User->getOperand(i);
5461         if (UseOp == N0)
5462           continue;
5463         if (!isa<ConstantSDNode>(UseOp))
5464           return false;
5465         Add = true;
5466       }
5467       if (Add)
5468         ExtendNodes.push_back(User);
5469       continue;
5470     }
5471     // If truncates aren't free and there are users we can't
5472     // extend, it isn't worthwhile.
5473     if (!isTruncFree)
5474       return false;
5475     // Remember if this value is live-out.
5476     if (User->getOpcode() == ISD::CopyToReg)
5477       HasCopyToRegUses = true;
5478   }
5479
5480   if (HasCopyToRegUses) {
5481     bool BothLiveOut = false;
5482     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5483          UI != UE; ++UI) {
5484       SDUse &Use = UI.getUse();
5485       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5486         BothLiveOut = true;
5487         break;
5488       }
5489     }
5490     if (BothLiveOut)
5491       // Both unextended and extended values are live out. There had better be
5492       // a good reason for the transformation.
5493       return ExtendNodes.size();
5494   }
5495   return true;
5496 }
5497
5498 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5499                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5500                                   ISD::NodeType ExtType) {
5501   // Extend SetCC uses if necessary.
5502   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5503     SDNode *SetCC = SetCCs[i];
5504     SmallVector<SDValue, 4> Ops;
5505
5506     for (unsigned j = 0; j != 2; ++j) {
5507       SDValue SOp = SetCC->getOperand(j);
5508       if (SOp == Trunc)
5509         Ops.push_back(ExtLoad);
5510       else
5511         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5512     }
5513
5514     Ops.push_back(SetCC->getOperand(2));
5515     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5516   }
5517 }
5518
5519 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5520 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5521   SDValue N0 = N->getOperand(0);
5522   EVT DstVT = N->getValueType(0);
5523   EVT SrcVT = N0.getValueType();
5524
5525   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5526           N->getOpcode() == ISD::ZERO_EXTEND) &&
5527          "Unexpected node type (not an extend)!");
5528
5529   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5530   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5531   //   (v8i32 (sext (v8i16 (load x))))
5532   // into:
5533   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5534   //                          (v4i32 (sextload (x + 16)))))
5535   // Where uses of the original load, i.e.:
5536   //   (v8i16 (load x))
5537   // are replaced with:
5538   //   (v8i16 (truncate
5539   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5540   //                            (v4i32 (sextload (x + 16)))))))
5541   //
5542   // This combine is only applicable to illegal, but splittable, vectors.
5543   // All legal types, and illegal non-vector types, are handled elsewhere.
5544   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5545   //
5546   if (N0->getOpcode() != ISD::LOAD)
5547     return SDValue();
5548
5549   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5550
5551   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5552       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5553       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5554     return SDValue();
5555
5556   SmallVector<SDNode *, 4> SetCCs;
5557   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5558     return SDValue();
5559
5560   ISD::LoadExtType ExtType =
5561       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5562
5563   // Try to split the vector types to get down to legal types.
5564   EVT SplitSrcVT = SrcVT;
5565   EVT SplitDstVT = DstVT;
5566   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5567          SplitSrcVT.getVectorNumElements() > 1) {
5568     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5569     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5570   }
5571
5572   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5573     return SDValue();
5574
5575   SDLoc DL(N);
5576   const unsigned NumSplits =
5577       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5578   const unsigned Stride = SplitSrcVT.getStoreSize();
5579   SmallVector<SDValue, 4> Loads;
5580   SmallVector<SDValue, 4> Chains;
5581
5582   SDValue BasePtr = LN0->getBasePtr();
5583   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5584     const unsigned Offset = Idx * Stride;
5585     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5586
5587     SDValue SplitLoad = DAG.getExtLoad(
5588         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5589         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5590         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5591         Align, LN0->getAAInfo());
5592
5593     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5594                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5595
5596     Loads.push_back(SplitLoad.getValue(0));
5597     Chains.push_back(SplitLoad.getValue(1));
5598   }
5599
5600   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5601   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5602
5603   CombineTo(N, NewValue);
5604
5605   // Replace uses of the original load (before extension)
5606   // with a truncate of the concatenated sextloaded vectors.
5607   SDValue Trunc =
5608       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5609   CombineTo(N0.getNode(), Trunc, NewChain);
5610   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5611                   (ISD::NodeType)N->getOpcode());
5612   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5613 }
5614
5615 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5616   SDValue N0 = N->getOperand(0);
5617   EVT VT = N->getValueType(0);
5618
5619   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5620                                               LegalOperations))
5621     return SDValue(Res, 0);
5622
5623   // fold (sext (sext x)) -> (sext x)
5624   // fold (sext (aext x)) -> (sext x)
5625   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5626     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5627                        N0.getOperand(0));
5628
5629   if (N0.getOpcode() == ISD::TRUNCATE) {
5630     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5631     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5632     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5633     if (NarrowLoad.getNode()) {
5634       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5635       if (NarrowLoad.getNode() != N0.getNode()) {
5636         CombineTo(N0.getNode(), NarrowLoad);
5637         // CombineTo deleted the truncate, if needed, but not what's under it.
5638         AddToWorklist(oye);
5639       }
5640       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5641     }
5642
5643     // See if the value being truncated is already sign extended.  If so, just
5644     // eliminate the trunc/sext pair.
5645     SDValue Op = N0.getOperand(0);
5646     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5647     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5648     unsigned DestBits = VT.getScalarType().getSizeInBits();
5649     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5650
5651     if (OpBits == DestBits) {
5652       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5653       // bits, it is already ready.
5654       if (NumSignBits > DestBits-MidBits)
5655         return Op;
5656     } else if (OpBits < DestBits) {
5657       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5658       // bits, just sext from i32.
5659       if (NumSignBits > OpBits-MidBits)
5660         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5661     } else {
5662       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5663       // bits, just truncate to i32.
5664       if (NumSignBits > OpBits-MidBits)
5665         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5666     }
5667
5668     // fold (sext (truncate x)) -> (sextinreg x).
5669     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5670                                                  N0.getValueType())) {
5671       if (OpBits < DestBits)
5672         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5673       else if (OpBits > DestBits)
5674         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5675       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5676                          DAG.getValueType(N0.getValueType()));
5677     }
5678   }
5679
5680   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5681   // Only generate vector extloads when 1) they're legal, and 2) they are
5682   // deemed desirable by the target.
5683   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5684       ((!LegalOperations && !VT.isVector() &&
5685         !cast<LoadSDNode>(N0)->isVolatile()) ||
5686        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5687     bool DoXform = true;
5688     SmallVector<SDNode*, 4> SetCCs;
5689     if (!N0.hasOneUse())
5690       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5691     if (VT.isVector())
5692       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5693     if (DoXform) {
5694       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5696                                        LN0->getChain(),
5697                                        LN0->getBasePtr(), N0.getValueType(),
5698                                        LN0->getMemOperand());
5699       CombineTo(N, ExtLoad);
5700       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5701                                   N0.getValueType(), ExtLoad);
5702       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5703       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5704                       ISD::SIGN_EXTEND);
5705       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5706     }
5707   }
5708
5709   // fold (sext (load x)) to multiple smaller sextloads.
5710   // Only on illegal but splittable vectors.
5711   if (SDValue ExtLoad = CombineExtLoad(N))
5712     return ExtLoad;
5713
5714   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5715   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5716   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5717       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5718     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5719     EVT MemVT = LN0->getMemoryVT();
5720     if ((!LegalOperations && !LN0->isVolatile()) ||
5721         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5722       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5723                                        LN0->getChain(),
5724                                        LN0->getBasePtr(), MemVT,
5725                                        LN0->getMemOperand());
5726       CombineTo(N, ExtLoad);
5727       CombineTo(N0.getNode(),
5728                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5729                             N0.getValueType(), ExtLoad),
5730                 ExtLoad.getValue(1));
5731       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5732     }
5733   }
5734
5735   // fold (sext (and/or/xor (load x), cst)) ->
5736   //      (and/or/xor (sextload x), (sext cst))
5737   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5738        N0.getOpcode() == ISD::XOR) &&
5739       isa<LoadSDNode>(N0.getOperand(0)) &&
5740       N0.getOperand(1).getOpcode() == ISD::Constant &&
5741       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5742       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5743     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5744     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5745       bool DoXform = true;
5746       SmallVector<SDNode*, 4> SetCCs;
5747       if (!N0.hasOneUse())
5748         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5749                                           SetCCs, TLI);
5750       if (DoXform) {
5751         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5752                                          LN0->getChain(), LN0->getBasePtr(),
5753                                          LN0->getMemoryVT(),
5754                                          LN0->getMemOperand());
5755         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5756         Mask = Mask.sext(VT.getSizeInBits());
5757         SDLoc DL(N);
5758         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5759                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5760         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5761                                     SDLoc(N0.getOperand(0)),
5762                                     N0.getOperand(0).getValueType(), ExtLoad);
5763         CombineTo(N, And);
5764         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5765         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5766                         ISD::SIGN_EXTEND);
5767         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5768       }
5769     }
5770   }
5771
5772   if (N0.getOpcode() == ISD::SETCC) {
5773     EVT N0VT = N0.getOperand(0).getValueType();
5774     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5775     // Only do this before legalize for now.
5776     if (VT.isVector() && !LegalOperations &&
5777         TLI.getBooleanContents(N0VT) ==
5778             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5779       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5780       // of the same size as the compared operands. Only optimize sext(setcc())
5781       // if this is the case.
5782       EVT SVT = getSetCCResultType(N0VT);
5783
5784       // We know that the # elements of the results is the same as the
5785       // # elements of the compare (and the # elements of the compare result
5786       // for that matter).  Check to see that they are the same size.  If so,
5787       // we know that the element size of the sext'd result matches the
5788       // element size of the compare operands.
5789       if (VT.getSizeInBits() == SVT.getSizeInBits())
5790         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5791                              N0.getOperand(1),
5792                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5793
5794       // If the desired elements are smaller or larger than the source
5795       // elements we can use a matching integer vector type and then
5796       // truncate/sign extend
5797       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5798       if (SVT == MatchingVectorType) {
5799         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5800                                N0.getOperand(0), N0.getOperand(1),
5801                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5802         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5803       }
5804     }
5805
5806     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5807     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5808     SDLoc DL(N);
5809     SDValue NegOne =
5810       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5811     SDValue SCC =
5812       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5813                        NegOne, DAG.getConstant(0, DL, VT),
5814                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5815     if (SCC.getNode()) return SCC;
5816
5817     if (!VT.isVector()) {
5818       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5819       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5820         SDLoc DL(N);
5821         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5822         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5823                                      N0.getOperand(0), N0.getOperand(1), CC);
5824         return DAG.getSelect(DL, VT, SetCC,
5825                              NegOne, DAG.getConstant(0, DL, VT));
5826       }
5827     }
5828   }
5829
5830   // fold (sext x) -> (zext x) if the sign bit is known zero.
5831   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5832       DAG.SignBitIsZero(N0))
5833     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5834
5835   return SDValue();
5836 }
5837
5838 // isTruncateOf - If N is a truncate of some other value, return true, record
5839 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5840 // This function computes KnownZero to avoid a duplicated call to
5841 // computeKnownBits in the caller.
5842 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5843                          APInt &KnownZero) {
5844   APInt KnownOne;
5845   if (N->getOpcode() == ISD::TRUNCATE) {
5846     Op = N->getOperand(0);
5847     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5848     return true;
5849   }
5850
5851   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5852       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5853     return false;
5854
5855   SDValue Op0 = N->getOperand(0);
5856   SDValue Op1 = N->getOperand(1);
5857   assert(Op0.getValueType() == Op1.getValueType());
5858
5859   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5860   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5861   if (COp0 && COp0->isNullValue())
5862     Op = Op1;
5863   else if (COp1 && COp1->isNullValue())
5864     Op = Op0;
5865   else
5866     return false;
5867
5868   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5869
5870   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5871     return false;
5872
5873   return true;
5874 }
5875
5876 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5877   SDValue N0 = N->getOperand(0);
5878   EVT VT = N->getValueType(0);
5879
5880   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5881                                               LegalOperations))
5882     return SDValue(Res, 0);
5883
5884   // fold (zext (zext x)) -> (zext x)
5885   // fold (zext (aext x)) -> (zext x)
5886   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5887     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5888                        N0.getOperand(0));
5889
5890   // fold (zext (truncate x)) -> (zext x) or
5891   //      (zext (truncate x)) -> (truncate x)
5892   // This is valid when the truncated bits of x are already zero.
5893   // FIXME: We should extend this to work for vectors too.
5894   SDValue Op;
5895   APInt KnownZero;
5896   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5897     APInt TruncatedBits =
5898       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5899       APInt(Op.getValueSizeInBits(), 0) :
5900       APInt::getBitsSet(Op.getValueSizeInBits(),
5901                         N0.getValueSizeInBits(),
5902                         std::min(Op.getValueSizeInBits(),
5903                                  VT.getSizeInBits()));
5904     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5905       if (VT.bitsGT(Op.getValueType()))
5906         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5907       if (VT.bitsLT(Op.getValueType()))
5908         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5909
5910       return Op;
5911     }
5912   }
5913
5914   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5915   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5916   if (N0.getOpcode() == ISD::TRUNCATE) {
5917     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5918     if (NarrowLoad.getNode()) {
5919       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5920       if (NarrowLoad.getNode() != N0.getNode()) {
5921         CombineTo(N0.getNode(), NarrowLoad);
5922         // CombineTo deleted the truncate, if needed, but not what's under it.
5923         AddToWorklist(oye);
5924       }
5925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5926     }
5927   }
5928
5929   // fold (zext (truncate x)) -> (and x, mask)
5930   if (N0.getOpcode() == ISD::TRUNCATE &&
5931       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5932
5933     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5934     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5935     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5936     if (NarrowLoad.getNode()) {
5937       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5938       if (NarrowLoad.getNode() != N0.getNode()) {
5939         CombineTo(N0.getNode(), NarrowLoad);
5940         // CombineTo deleted the truncate, if needed, but not what's under it.
5941         AddToWorklist(oye);
5942       }
5943       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5944     }
5945
5946     SDValue Op = N0.getOperand(0);
5947     if (Op.getValueType().bitsLT(VT)) {
5948       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5949       AddToWorklist(Op.getNode());
5950     } else if (Op.getValueType().bitsGT(VT)) {
5951       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5952       AddToWorklist(Op.getNode());
5953     }
5954     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5955                                   N0.getValueType().getScalarType());
5956   }
5957
5958   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5959   // if either of the casts is not free.
5960   if (N0.getOpcode() == ISD::AND &&
5961       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5962       N0.getOperand(1).getOpcode() == ISD::Constant &&
5963       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5964                            N0.getValueType()) ||
5965        !TLI.isZExtFree(N0.getValueType(), VT))) {
5966     SDValue X = N0.getOperand(0).getOperand(0);
5967     if (X.getValueType().bitsLT(VT)) {
5968       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5969     } else if (X.getValueType().bitsGT(VT)) {
5970       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5971     }
5972     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5973     Mask = Mask.zext(VT.getSizeInBits());
5974     SDLoc DL(N);
5975     return DAG.getNode(ISD::AND, DL, VT,
5976                        X, DAG.getConstant(Mask, DL, VT));
5977   }
5978
5979   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5980   // Only generate vector extloads when 1) they're legal, and 2) they are
5981   // deemed desirable by the target.
5982   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5983       ((!LegalOperations && !VT.isVector() &&
5984         !cast<LoadSDNode>(N0)->isVolatile()) ||
5985        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5986     bool DoXform = true;
5987     SmallVector<SDNode*, 4> SetCCs;
5988     if (!N0.hasOneUse())
5989       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5990     if (VT.isVector())
5991       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5992     if (DoXform) {
5993       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5994       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5995                                        LN0->getChain(),
5996                                        LN0->getBasePtr(), N0.getValueType(),
5997                                        LN0->getMemOperand());
5998       CombineTo(N, ExtLoad);
5999       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6000                                   N0.getValueType(), ExtLoad);
6001       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6002
6003       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6004                       ISD::ZERO_EXTEND);
6005       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6006     }
6007   }
6008
6009   // fold (zext (load x)) to multiple smaller zextloads.
6010   // Only on illegal but splittable vectors.
6011   if (SDValue ExtLoad = CombineExtLoad(N))
6012     return ExtLoad;
6013
6014   // fold (zext (and/or/xor (load x), cst)) ->
6015   //      (and/or/xor (zextload x), (zext cst))
6016   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6017        N0.getOpcode() == ISD::XOR) &&
6018       isa<LoadSDNode>(N0.getOperand(0)) &&
6019       N0.getOperand(1).getOpcode() == ISD::Constant &&
6020       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6021       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6022     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6023     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6024       bool DoXform = true;
6025       SmallVector<SDNode*, 4> SetCCs;
6026       if (!N0.hasOneUse())
6027         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6028                                           SetCCs, TLI);
6029       if (DoXform) {
6030         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6031                                          LN0->getChain(), LN0->getBasePtr(),
6032                                          LN0->getMemoryVT(),
6033                                          LN0->getMemOperand());
6034         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6035         Mask = Mask.zext(VT.getSizeInBits());
6036         SDLoc DL(N);
6037         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6038                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6039         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6040                                     SDLoc(N0.getOperand(0)),
6041                                     N0.getOperand(0).getValueType(), ExtLoad);
6042         CombineTo(N, And);
6043         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6044         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6045                         ISD::ZERO_EXTEND);
6046         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6047       }
6048     }
6049   }
6050
6051   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6052   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6053   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6054       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6055     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6056     EVT MemVT = LN0->getMemoryVT();
6057     if ((!LegalOperations && !LN0->isVolatile()) ||
6058         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6059       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6060                                        LN0->getChain(),
6061                                        LN0->getBasePtr(), MemVT,
6062                                        LN0->getMemOperand());
6063       CombineTo(N, ExtLoad);
6064       CombineTo(N0.getNode(),
6065                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6066                             ExtLoad),
6067                 ExtLoad.getValue(1));
6068       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6069     }
6070   }
6071
6072   if (N0.getOpcode() == ISD::SETCC) {
6073     if (!LegalOperations && VT.isVector() &&
6074         N0.getValueType().getVectorElementType() == MVT::i1) {
6075       EVT N0VT = N0.getOperand(0).getValueType();
6076       if (getSetCCResultType(N0VT) == N0.getValueType())
6077         return SDValue();
6078
6079       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6080       // Only do this before legalize for now.
6081       EVT EltVT = VT.getVectorElementType();
6082       SDLoc DL(N);
6083       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6084                                     DAG.getConstant(1, DL, EltVT));
6085       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6086         // We know that the # elements of the results is the same as the
6087         // # elements of the compare (and the # elements of the compare result
6088         // for that matter).  Check to see that they are the same size.  If so,
6089         // we know that the element size of the sext'd result matches the
6090         // element size of the compare operands.
6091         return DAG.getNode(ISD::AND, DL, VT,
6092                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6093                                          N0.getOperand(1),
6094                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6095                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6096                                        OneOps));
6097
6098       // If the desired elements are smaller or larger than the source
6099       // elements we can use a matching integer vector type and then
6100       // truncate/sign extend
6101       EVT MatchingElementType =
6102         EVT::getIntegerVT(*DAG.getContext(),
6103                           N0VT.getScalarType().getSizeInBits());
6104       EVT MatchingVectorType =
6105         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6106                          N0VT.getVectorNumElements());
6107       SDValue VsetCC =
6108         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6109                       N0.getOperand(1),
6110                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6111       return DAG.getNode(ISD::AND, DL, VT,
6112                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6113                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6114     }
6115
6116     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6117     SDLoc DL(N);
6118     SDValue SCC =
6119       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6120                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6121                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6122     if (SCC.getNode()) return SCC;
6123   }
6124
6125   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6126   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6127       isa<ConstantSDNode>(N0.getOperand(1)) &&
6128       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6129       N0.hasOneUse()) {
6130     SDValue ShAmt = N0.getOperand(1);
6131     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6132     if (N0.getOpcode() == ISD::SHL) {
6133       SDValue InnerZExt = N0.getOperand(0);
6134       // If the original shl may be shifting out bits, do not perform this
6135       // transformation.
6136       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6137         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6138       if (ShAmtVal > KnownZeroBits)
6139         return SDValue();
6140     }
6141
6142     SDLoc DL(N);
6143
6144     // Ensure that the shift amount is wide enough for the shifted value.
6145     if (VT.getSizeInBits() >= 256)
6146       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6147
6148     return DAG.getNode(N0.getOpcode(), DL, VT,
6149                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6150                        ShAmt);
6151   }
6152
6153   return SDValue();
6154 }
6155
6156 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6157   SDValue N0 = N->getOperand(0);
6158   EVT VT = N->getValueType(0);
6159
6160   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6161                                               LegalOperations))
6162     return SDValue(Res, 0);
6163
6164   // fold (aext (aext x)) -> (aext x)
6165   // fold (aext (zext x)) -> (zext x)
6166   // fold (aext (sext x)) -> (sext x)
6167   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6168       N0.getOpcode() == ISD::ZERO_EXTEND ||
6169       N0.getOpcode() == ISD::SIGN_EXTEND)
6170     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6171
6172   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6173   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6174   if (N0.getOpcode() == ISD::TRUNCATE) {
6175     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6176     if (NarrowLoad.getNode()) {
6177       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6178       if (NarrowLoad.getNode() != N0.getNode()) {
6179         CombineTo(N0.getNode(), NarrowLoad);
6180         // CombineTo deleted the truncate, if needed, but not what's under it.
6181         AddToWorklist(oye);
6182       }
6183       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6184     }
6185   }
6186
6187   // fold (aext (truncate x))
6188   if (N0.getOpcode() == ISD::TRUNCATE) {
6189     SDValue TruncOp = N0.getOperand(0);
6190     if (TruncOp.getValueType() == VT)
6191       return TruncOp; // x iff x size == zext size.
6192     if (TruncOp.getValueType().bitsGT(VT))
6193       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6194     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6195   }
6196
6197   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6198   // if the trunc is not free.
6199   if (N0.getOpcode() == ISD::AND &&
6200       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6201       N0.getOperand(1).getOpcode() == ISD::Constant &&
6202       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6203                           N0.getValueType())) {
6204     SDValue X = N0.getOperand(0).getOperand(0);
6205     if (X.getValueType().bitsLT(VT)) {
6206       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6207     } else if (X.getValueType().bitsGT(VT)) {
6208       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6209     }
6210     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6211     Mask = Mask.zext(VT.getSizeInBits());
6212     SDLoc DL(N);
6213     return DAG.getNode(ISD::AND, DL, VT,
6214                        X, DAG.getConstant(Mask, DL, VT));
6215   }
6216
6217   // fold (aext (load x)) -> (aext (truncate (extload x)))
6218   // None of the supported targets knows how to perform load and any_ext
6219   // on vectors in one instruction.  We only perform this transformation on
6220   // scalars.
6221   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6222       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6223       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6224     bool DoXform = true;
6225     SmallVector<SDNode*, 4> SetCCs;
6226     if (!N0.hasOneUse())
6227       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6228     if (DoXform) {
6229       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6230       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6231                                        LN0->getChain(),
6232                                        LN0->getBasePtr(), N0.getValueType(),
6233                                        LN0->getMemOperand());
6234       CombineTo(N, ExtLoad);
6235       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6236                                   N0.getValueType(), ExtLoad);
6237       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6238       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6239                       ISD::ANY_EXTEND);
6240       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6241     }
6242   }
6243
6244   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6245   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6246   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6247   if (N0.getOpcode() == ISD::LOAD &&
6248       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6249       N0.hasOneUse()) {
6250     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6251     ISD::LoadExtType ExtType = LN0->getExtensionType();
6252     EVT MemVT = LN0->getMemoryVT();
6253     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6254       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6255                                        VT, LN0->getChain(), LN0->getBasePtr(),
6256                                        MemVT, LN0->getMemOperand());
6257       CombineTo(N, ExtLoad);
6258       CombineTo(N0.getNode(),
6259                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6260                             N0.getValueType(), ExtLoad),
6261                 ExtLoad.getValue(1));
6262       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6263     }
6264   }
6265
6266   if (N0.getOpcode() == ISD::SETCC) {
6267     // For vectors:
6268     // aext(setcc) -> vsetcc
6269     // aext(setcc) -> truncate(vsetcc)
6270     // aext(setcc) -> aext(vsetcc)
6271     // Only do this before legalize for now.
6272     if (VT.isVector() && !LegalOperations) {
6273       EVT N0VT = N0.getOperand(0).getValueType();
6274         // We know that the # elements of the results is the same as the
6275         // # elements of the compare (and the # elements of the compare result
6276         // for that matter).  Check to see that they are the same size.  If so,
6277         // we know that the element size of the sext'd result matches the
6278         // element size of the compare operands.
6279       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6280         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6281                              N0.getOperand(1),
6282                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6283       // If the desired elements are smaller or larger than the source
6284       // elements we can use a matching integer vector type and then
6285       // truncate/any extend
6286       else {
6287         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6288         SDValue VsetCC =
6289           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6290                         N0.getOperand(1),
6291                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6292         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6293       }
6294     }
6295
6296     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6297     SDLoc DL(N);
6298     SDValue SCC =
6299       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6300                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6301                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6302     if (SCC.getNode())
6303       return SCC;
6304   }
6305
6306   return SDValue();
6307 }
6308
6309 /// See if the specified operand can be simplified with the knowledge that only
6310 /// the bits specified by Mask are used.  If so, return the simpler operand,
6311 /// otherwise return a null SDValue.
6312 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6313   switch (V.getOpcode()) {
6314   default: break;
6315   case ISD::Constant: {
6316     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6317     assert(CV && "Const value should be ConstSDNode.");
6318     const APInt &CVal = CV->getAPIntValue();
6319     APInt NewVal = CVal & Mask;
6320     if (NewVal != CVal)
6321       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6322     break;
6323   }
6324   case ISD::OR:
6325   case ISD::XOR:
6326     // If the LHS or RHS don't contribute bits to the or, drop them.
6327     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6328       return V.getOperand(1);
6329     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6330       return V.getOperand(0);
6331     break;
6332   case ISD::SRL:
6333     // Only look at single-use SRLs.
6334     if (!V.getNode()->hasOneUse())
6335       break;
6336     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6337       // See if we can recursively simplify the LHS.
6338       unsigned Amt = RHSC->getZExtValue();
6339
6340       // Watch out for shift count overflow though.
6341       if (Amt >= Mask.getBitWidth()) break;
6342       APInt NewMask = Mask << Amt;
6343       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6344       if (SimplifyLHS.getNode())
6345         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6346                            SimplifyLHS, V.getOperand(1));
6347     }
6348   }
6349   return SDValue();
6350 }
6351
6352 /// If the result of a wider load is shifted to right of N  bits and then
6353 /// truncated to a narrower type and where N is a multiple of number of bits of
6354 /// the narrower type, transform it to a narrower load from address + N / num of
6355 /// bits of new type. If the result is to be extended, also fold the extension
6356 /// to form a extending load.
6357 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6358   unsigned Opc = N->getOpcode();
6359
6360   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6361   SDValue N0 = N->getOperand(0);
6362   EVT VT = N->getValueType(0);
6363   EVT ExtVT = VT;
6364
6365   // This transformation isn't valid for vector loads.
6366   if (VT.isVector())
6367     return SDValue();
6368
6369   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6370   // extended to VT.
6371   if (Opc == ISD::SIGN_EXTEND_INREG) {
6372     ExtType = ISD::SEXTLOAD;
6373     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6374   } else if (Opc == ISD::SRL) {
6375     // Another special-case: SRL is basically zero-extending a narrower value.
6376     ExtType = ISD::ZEXTLOAD;
6377     N0 = SDValue(N, 0);
6378     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6379     if (!N01) return SDValue();
6380     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6381                               VT.getSizeInBits() - N01->getZExtValue());
6382   }
6383   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6384     return SDValue();
6385
6386   unsigned EVTBits = ExtVT.getSizeInBits();
6387
6388   // Do not generate loads of non-round integer types since these can
6389   // be expensive (and would be wrong if the type is not byte sized).
6390   if (!ExtVT.isRound())
6391     return SDValue();
6392
6393   unsigned ShAmt = 0;
6394   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6395     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6396       ShAmt = N01->getZExtValue();
6397       // Is the shift amount a multiple of size of VT?
6398       if ((ShAmt & (EVTBits-1)) == 0) {
6399         N0 = N0.getOperand(0);
6400         // Is the load width a multiple of size of VT?
6401         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6402           return SDValue();
6403       }
6404
6405       // At this point, we must have a load or else we can't do the transform.
6406       if (!isa<LoadSDNode>(N0)) return SDValue();
6407
6408       // Because a SRL must be assumed to *need* to zero-extend the high bits
6409       // (as opposed to anyext the high bits), we can't combine the zextload
6410       // lowering of SRL and an sextload.
6411       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6412         return SDValue();
6413
6414       // If the shift amount is larger than the input type then we're not
6415       // accessing any of the loaded bytes.  If the load was a zextload/extload
6416       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6417       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6418         return SDValue();
6419     }
6420   }
6421
6422   // If the load is shifted left (and the result isn't shifted back right),
6423   // we can fold the truncate through the shift.
6424   unsigned ShLeftAmt = 0;
6425   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6426       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6427     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6428       ShLeftAmt = N01->getZExtValue();
6429       N0 = N0.getOperand(0);
6430     }
6431   }
6432
6433   // If we haven't found a load, we can't narrow it.  Don't transform one with
6434   // multiple uses, this would require adding a new load.
6435   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6436     return SDValue();
6437
6438   // Don't change the width of a volatile load.
6439   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6440   if (LN0->isVolatile())
6441     return SDValue();
6442
6443   // Verify that we are actually reducing a load width here.
6444   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6445     return SDValue();
6446
6447   // For the transform to be legal, the load must produce only two values
6448   // (the value loaded and the chain).  Don't transform a pre-increment
6449   // load, for example, which produces an extra value.  Otherwise the
6450   // transformation is not equivalent, and the downstream logic to replace
6451   // uses gets things wrong.
6452   if (LN0->getNumValues() > 2)
6453     return SDValue();
6454
6455   // If the load that we're shrinking is an extload and we're not just
6456   // discarding the extension we can't simply shrink the load. Bail.
6457   // TODO: It would be possible to merge the extensions in some cases.
6458   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6459       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6460     return SDValue();
6461
6462   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6463     return SDValue();
6464
6465   EVT PtrType = N0.getOperand(1).getValueType();
6466
6467   if (PtrType == MVT::Untyped || PtrType.isExtended())
6468     // It's not possible to generate a constant of extended or untyped type.
6469     return SDValue();
6470
6471   // For big endian targets, we need to adjust the offset to the pointer to
6472   // load the correct bytes.
6473   if (TLI.isBigEndian()) {
6474     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6475     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6476     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6477   }
6478
6479   uint64_t PtrOff = ShAmt / 8;
6480   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6481   SDLoc DL(LN0);
6482   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6483                                PtrType, LN0->getBasePtr(),
6484                                DAG.getConstant(PtrOff, DL, PtrType));
6485   AddToWorklist(NewPtr.getNode());
6486
6487   SDValue Load;
6488   if (ExtType == ISD::NON_EXTLOAD)
6489     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6490                         LN0->getPointerInfo().getWithOffset(PtrOff),
6491                         LN0->isVolatile(), LN0->isNonTemporal(),
6492                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6493   else
6494     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6495                           LN0->getPointerInfo().getWithOffset(PtrOff),
6496                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6497                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6498
6499   // Replace the old load's chain with the new load's chain.
6500   WorklistRemover DeadNodes(*this);
6501   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6502
6503   // Shift the result left, if we've swallowed a left shift.
6504   SDValue Result = Load;
6505   if (ShLeftAmt != 0) {
6506     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6507     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6508       ShImmTy = VT;
6509     // If the shift amount is as large as the result size (but, presumably,
6510     // no larger than the source) then the useful bits of the result are
6511     // zero; we can't simply return the shortened shift, because the result
6512     // of that operation is undefined.
6513     SDLoc DL(N0);
6514     if (ShLeftAmt >= VT.getSizeInBits())
6515       Result = DAG.getConstant(0, DL, VT);
6516     else
6517       Result = DAG.getNode(ISD::SHL, DL, VT,
6518                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6519   }
6520
6521   // Return the new loaded value.
6522   return Result;
6523 }
6524
6525 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6526   SDValue N0 = N->getOperand(0);
6527   SDValue N1 = N->getOperand(1);
6528   EVT VT = N->getValueType(0);
6529   EVT EVT = cast<VTSDNode>(N1)->getVT();
6530   unsigned VTBits = VT.getScalarType().getSizeInBits();
6531   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6532
6533   // fold (sext_in_reg c1) -> c1
6534   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6535     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6536
6537   // If the input is already sign extended, just drop the extension.
6538   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6539     return N0;
6540
6541   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6542   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6543       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6544     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6545                        N0.getOperand(0), N1);
6546
6547   // fold (sext_in_reg (sext x)) -> (sext x)
6548   // fold (sext_in_reg (aext x)) -> (sext x)
6549   // if x is small enough.
6550   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6551     SDValue N00 = N0.getOperand(0);
6552     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6553         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6554       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6555   }
6556
6557   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6558   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6559     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6560
6561   // fold operands of sext_in_reg based on knowledge that the top bits are not
6562   // demanded.
6563   if (SimplifyDemandedBits(SDValue(N, 0)))
6564     return SDValue(N, 0);
6565
6566   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6567   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6568   SDValue NarrowLoad = ReduceLoadWidth(N);
6569   if (NarrowLoad.getNode())
6570     return NarrowLoad;
6571
6572   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6573   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6574   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6575   if (N0.getOpcode() == ISD::SRL) {
6576     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6577       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6578         // We can turn this into an SRA iff the input to the SRL is already sign
6579         // extended enough.
6580         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6581         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6582           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6583                              N0.getOperand(0), N0.getOperand(1));
6584       }
6585   }
6586
6587   // fold (sext_inreg (extload x)) -> (sextload x)
6588   if (ISD::isEXTLoad(N0.getNode()) &&
6589       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6590       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6591       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6592        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6593     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6594     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6595                                      LN0->getChain(),
6596                                      LN0->getBasePtr(), EVT,
6597                                      LN0->getMemOperand());
6598     CombineTo(N, ExtLoad);
6599     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6600     AddToWorklist(ExtLoad.getNode());
6601     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6602   }
6603   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6604   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6605       N0.hasOneUse() &&
6606       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6607       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6608        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6609     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6610     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6611                                      LN0->getChain(),
6612                                      LN0->getBasePtr(), EVT,
6613                                      LN0->getMemOperand());
6614     CombineTo(N, ExtLoad);
6615     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6616     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6617   }
6618
6619   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6620   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6621     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6622                                        N0.getOperand(1), false);
6623     if (BSwap.getNode())
6624       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6625                          BSwap, N1);
6626   }
6627
6628   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6629   // into a build_vector.
6630   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6631     SmallVector<SDValue, 8> Elts;
6632     unsigned NumElts = N0->getNumOperands();
6633     unsigned ShAmt = VTBits - EVTBits;
6634
6635     for (unsigned i = 0; i != NumElts; ++i) {
6636       SDValue Op = N0->getOperand(i);
6637       if (Op->getOpcode() == ISD::UNDEF) {
6638         Elts.push_back(Op);
6639         continue;
6640       }
6641
6642       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6643       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6644       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6645                                      SDLoc(Op), Op.getValueType()));
6646     }
6647
6648     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6649   }
6650
6651   return SDValue();
6652 }
6653
6654 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6655   SDValue N0 = N->getOperand(0);
6656   EVT VT = N->getValueType(0);
6657   bool isLE = TLI.isLittleEndian();
6658
6659   // noop truncate
6660   if (N0.getValueType() == N->getValueType(0))
6661     return N0;
6662   // fold (truncate c1) -> c1
6663   if (isConstantIntBuildVectorOrConstantInt(N0))
6664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6665   // fold (truncate (truncate x)) -> (truncate x)
6666   if (N0.getOpcode() == ISD::TRUNCATE)
6667     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6668   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6669   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6670       N0.getOpcode() == ISD::SIGN_EXTEND ||
6671       N0.getOpcode() == ISD::ANY_EXTEND) {
6672     if (N0.getOperand(0).getValueType().bitsLT(VT))
6673       // if the source is smaller than the dest, we still need an extend
6674       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6675                          N0.getOperand(0));
6676     if (N0.getOperand(0).getValueType().bitsGT(VT))
6677       // if the source is larger than the dest, than we just need the truncate
6678       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6679     // if the source and dest are the same type, we can drop both the extend
6680     // and the truncate.
6681     return N0.getOperand(0);
6682   }
6683
6684   // Fold extract-and-trunc into a narrow extract. For example:
6685   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6686   //   i32 y = TRUNCATE(i64 x)
6687   //        -- becomes --
6688   //   v16i8 b = BITCAST (v2i64 val)
6689   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6690   //
6691   // Note: We only run this optimization after type legalization (which often
6692   // creates this pattern) and before operation legalization after which
6693   // we need to be more careful about the vector instructions that we generate.
6694   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6695       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6696
6697     EVT VecTy = N0.getOperand(0).getValueType();
6698     EVT ExTy = N0.getValueType();
6699     EVT TrTy = N->getValueType(0);
6700
6701     unsigned NumElem = VecTy.getVectorNumElements();
6702     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6703
6704     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6705     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6706
6707     SDValue EltNo = N0->getOperand(1);
6708     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6709       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6710       EVT IndexTy = TLI.getVectorIdxTy();
6711       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6712
6713       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6714                               NVT, N0.getOperand(0));
6715
6716       SDLoc DL(N);
6717       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6718                          DL, TrTy, V,
6719                          DAG.getConstant(Index, DL, IndexTy));
6720     }
6721   }
6722
6723   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6724   if (N0.getOpcode() == ISD::SELECT) {
6725     EVT SrcVT = N0.getValueType();
6726     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6727         TLI.isTruncateFree(SrcVT, VT)) {
6728       SDLoc SL(N0);
6729       SDValue Cond = N0.getOperand(0);
6730       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6731       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6732       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6733     }
6734   }
6735
6736   // Fold a series of buildvector, bitcast, and truncate if possible.
6737   // For example fold
6738   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6739   //   (2xi32 (buildvector x, y)).
6740   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6741       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6742       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6743       N0.getOperand(0).hasOneUse()) {
6744
6745     SDValue BuildVect = N0.getOperand(0);
6746     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6747     EVT TruncVecEltTy = VT.getVectorElementType();
6748
6749     // Check that the element types match.
6750     if (BuildVectEltTy == TruncVecEltTy) {
6751       // Now we only need to compute the offset of the truncated elements.
6752       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6753       unsigned TruncVecNumElts = VT.getVectorNumElements();
6754       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6755
6756       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6757              "Invalid number of elements");
6758
6759       SmallVector<SDValue, 8> Opnds;
6760       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6761         Opnds.push_back(BuildVect.getOperand(i));
6762
6763       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6764     }
6765   }
6766
6767   // See if we can simplify the input to this truncate through knowledge that
6768   // only the low bits are being used.
6769   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6770   // Currently we only perform this optimization on scalars because vectors
6771   // may have different active low bits.
6772   if (!VT.isVector()) {
6773     SDValue Shorter =
6774       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6775                                                VT.getSizeInBits()));
6776     if (Shorter.getNode())
6777       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6778   }
6779   // fold (truncate (load x)) -> (smaller load x)
6780   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6781   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6782     SDValue Reduced = ReduceLoadWidth(N);
6783     if (Reduced.getNode())
6784       return Reduced;
6785     // Handle the case where the load remains an extending load even
6786     // after truncation.
6787     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6788       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6789       if (!LN0->isVolatile() &&
6790           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6791         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6792                                          VT, LN0->getChain(), LN0->getBasePtr(),
6793                                          LN0->getMemoryVT(),
6794                                          LN0->getMemOperand());
6795         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6796         return NewLoad;
6797       }
6798     }
6799   }
6800   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6801   // where ... are all 'undef'.
6802   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6803     SmallVector<EVT, 8> VTs;
6804     SDValue V;
6805     unsigned Idx = 0;
6806     unsigned NumDefs = 0;
6807
6808     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6809       SDValue X = N0.getOperand(i);
6810       if (X.getOpcode() != ISD::UNDEF) {
6811         V = X;
6812         Idx = i;
6813         NumDefs++;
6814       }
6815       // Stop if more than one members are non-undef.
6816       if (NumDefs > 1)
6817         break;
6818       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6819                                      VT.getVectorElementType(),
6820                                      X.getValueType().getVectorNumElements()));
6821     }
6822
6823     if (NumDefs == 0)
6824       return DAG.getUNDEF(VT);
6825
6826     if (NumDefs == 1) {
6827       assert(V.getNode() && "The single defined operand is empty!");
6828       SmallVector<SDValue, 8> Opnds;
6829       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6830         if (i != Idx) {
6831           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6832           continue;
6833         }
6834         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6835         AddToWorklist(NV.getNode());
6836         Opnds.push_back(NV);
6837       }
6838       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6839     }
6840   }
6841
6842   // Simplify the operands using demanded-bits information.
6843   if (!VT.isVector() &&
6844       SimplifyDemandedBits(SDValue(N, 0)))
6845     return SDValue(N, 0);
6846
6847   return SDValue();
6848 }
6849
6850 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6851   SDValue Elt = N->getOperand(i);
6852   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6853     return Elt.getNode();
6854   return Elt.getOperand(Elt.getResNo()).getNode();
6855 }
6856
6857 /// build_pair (load, load) -> load
6858 /// if load locations are consecutive.
6859 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6860   assert(N->getOpcode() == ISD::BUILD_PAIR);
6861
6862   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6863   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6864   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6865       LD1->getAddressSpace() != LD2->getAddressSpace())
6866     return SDValue();
6867   EVT LD1VT = LD1->getValueType(0);
6868
6869   if (ISD::isNON_EXTLoad(LD2) &&
6870       LD2->hasOneUse() &&
6871       // If both are volatile this would reduce the number of volatile loads.
6872       // If one is volatile it might be ok, but play conservative and bail out.
6873       !LD1->isVolatile() &&
6874       !LD2->isVolatile() &&
6875       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6876     unsigned Align = LD1->getAlignment();
6877     unsigned NewAlign = TLI.getDataLayout()->
6878       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6879
6880     if (NewAlign <= Align &&
6881         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6882       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6883                          LD1->getBasePtr(), LD1->getPointerInfo(),
6884                          false, false, false, Align);
6885   }
6886
6887   return SDValue();
6888 }
6889
6890 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6891   SDValue N0 = N->getOperand(0);
6892   EVT VT = N->getValueType(0);
6893
6894   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6895   // Only do this before legalize, since afterward the target may be depending
6896   // on the bitconvert.
6897   // First check to see if this is all constant.
6898   if (!LegalTypes &&
6899       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6900       VT.isVector()) {
6901     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6902
6903     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6904     assert(!DestEltVT.isVector() &&
6905            "Element type of vector ValueType must not be vector!");
6906     if (isSimple)
6907       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6908   }
6909
6910   // If the input is a constant, let getNode fold it.
6911   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6912     // If we can't allow illegal operations, we need to check that this is just
6913     // a fp -> int or int -> conversion and that the resulting operation will
6914     // be legal.
6915     if (!LegalOperations ||
6916         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6917          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6918         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6919          TLI.isOperationLegal(ISD::Constant, VT)))
6920       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6921   }
6922
6923   // (conv (conv x, t1), t2) -> (conv x, t2)
6924   if (N0.getOpcode() == ISD::BITCAST)
6925     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6926                        N0.getOperand(0));
6927
6928   // fold (conv (load x)) -> (load (conv*)x)
6929   // If the resultant load doesn't need a higher alignment than the original!
6930   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6931       // Do not change the width of a volatile load.
6932       !cast<LoadSDNode>(N0)->isVolatile() &&
6933       // Do not remove the cast if the types differ in endian layout.
6934       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6935       TLI.hasBigEndianPartOrdering(VT) &&
6936       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6937       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6938     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6939     unsigned Align = TLI.getDataLayout()->
6940       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6941     unsigned OrigAlign = LN0->getAlignment();
6942
6943     if (Align <= OrigAlign) {
6944       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6945                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6946                                  LN0->isVolatile(), LN0->isNonTemporal(),
6947                                  LN0->isInvariant(), OrigAlign,
6948                                  LN0->getAAInfo());
6949       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6950       return Load;
6951     }
6952   }
6953
6954   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6955   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6956   // This often reduces constant pool loads.
6957   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6958        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6959       N0.getNode()->hasOneUse() && VT.isInteger() &&
6960       !VT.isVector() && !N0.getValueType().isVector()) {
6961     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6962                                   N0.getOperand(0));
6963     AddToWorklist(NewConv.getNode());
6964
6965     SDLoc DL(N);
6966     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6967     if (N0.getOpcode() == ISD::FNEG)
6968       return DAG.getNode(ISD::XOR, DL, VT,
6969                          NewConv, DAG.getConstant(SignBit, DL, VT));
6970     assert(N0.getOpcode() == ISD::FABS);
6971     return DAG.getNode(ISD::AND, DL, VT,
6972                        NewConv, DAG.getConstant(~SignBit, DL, VT));
6973   }
6974
6975   // fold (bitconvert (fcopysign cst, x)) ->
6976   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6977   // Note that we don't handle (copysign x, cst) because this can always be
6978   // folded to an fneg or fabs.
6979   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6980       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6981       VT.isInteger() && !VT.isVector()) {
6982     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6983     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6984     if (isTypeLegal(IntXVT)) {
6985       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6986                               IntXVT, N0.getOperand(1));
6987       AddToWorklist(X.getNode());
6988
6989       // If X has a different width than the result/lhs, sext it or truncate it.
6990       unsigned VTWidth = VT.getSizeInBits();
6991       if (OrigXWidth < VTWidth) {
6992         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6993         AddToWorklist(X.getNode());
6994       } else if (OrigXWidth > VTWidth) {
6995         // To get the sign bit in the right place, we have to shift it right
6996         // before truncating.
6997         SDLoc DL(X);
6998         X = DAG.getNode(ISD::SRL, DL,
6999                         X.getValueType(), X,
7000                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7001                                         X.getValueType()));
7002         AddToWorklist(X.getNode());
7003         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7004         AddToWorklist(X.getNode());
7005       }
7006
7007       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7008       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7009                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7010       AddToWorklist(X.getNode());
7011
7012       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7013                                 VT, N0.getOperand(0));
7014       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7015                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7016       AddToWorklist(Cst.getNode());
7017
7018       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7019     }
7020   }
7021
7022   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7023   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7024     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7025     if (CombineLD.getNode())
7026       return CombineLD;
7027   }
7028
7029   // Remove double bitcasts from shuffles - this is often a legacy of
7030   // XformToShuffleWithZero being used to combine bitmaskings (of
7031   // float vectors bitcast to integer vectors) into shuffles.
7032   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7033   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7034       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7035       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7036       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7037     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7038
7039     // If operands are a bitcast, peek through if it casts the original VT.
7040     // If operands are a UNDEF or constant, just bitcast back to original VT.
7041     auto PeekThroughBitcast = [&](SDValue Op) {
7042       if (Op.getOpcode() == ISD::BITCAST &&
7043           Op.getOperand(0)->getValueType(0) == VT)
7044         return SDValue(Op.getOperand(0));
7045       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7046           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7047         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7048       return SDValue();
7049     };
7050
7051     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7052     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7053     if (!(SV0 && SV1))
7054       return SDValue();
7055
7056     int MaskScale =
7057         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7058     SmallVector<int, 8> NewMask;
7059     for (int M : SVN->getMask())
7060       for (int i = 0; i != MaskScale; ++i)
7061         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7062
7063     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7064     if (!LegalMask) {
7065       std::swap(SV0, SV1);
7066       ShuffleVectorSDNode::commuteMask(NewMask);
7067       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7068     }
7069
7070     if (LegalMask)
7071       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7072   }
7073
7074   return SDValue();
7075 }
7076
7077 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7078   EVT VT = N->getValueType(0);
7079   return CombineConsecutiveLoads(N, VT);
7080 }
7081
7082 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7083 /// operands. DstEltVT indicates the destination element value type.
7084 SDValue DAGCombiner::
7085 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7086   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7087
7088   // If this is already the right type, we're done.
7089   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7090
7091   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7092   unsigned DstBitSize = DstEltVT.getSizeInBits();
7093
7094   // If this is a conversion of N elements of one type to N elements of another
7095   // type, convert each element.  This handles FP<->INT cases.
7096   if (SrcBitSize == DstBitSize) {
7097     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7098                               BV->getValueType(0).getVectorNumElements());
7099
7100     // Due to the FP element handling below calling this routine recursively,
7101     // we can end up with a scalar-to-vector node here.
7102     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7103       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7104                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7105                                      DstEltVT, BV->getOperand(0)));
7106
7107     SmallVector<SDValue, 8> Ops;
7108     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7109       SDValue Op = BV->getOperand(i);
7110       // If the vector element type is not legal, the BUILD_VECTOR operands
7111       // are promoted and implicitly truncated.  Make that explicit here.
7112       if (Op.getValueType() != SrcEltVT)
7113         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7114       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7115                                 DstEltVT, Op));
7116       AddToWorklist(Ops.back().getNode());
7117     }
7118     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7119   }
7120
7121   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7122   // handle annoying details of growing/shrinking FP values, we convert them to
7123   // int first.
7124   if (SrcEltVT.isFloatingPoint()) {
7125     // Convert the input float vector to a int vector where the elements are the
7126     // same sizes.
7127     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7128     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7129     SrcEltVT = IntVT;
7130   }
7131
7132   // Now we know the input is an integer vector.  If the output is a FP type,
7133   // convert to integer first, then to FP of the right size.
7134   if (DstEltVT.isFloatingPoint()) {
7135     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7136     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7137
7138     // Next, convert to FP elements of the same size.
7139     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7140   }
7141
7142   SDLoc DL(BV);
7143
7144   // Okay, we know the src/dst types are both integers of differing types.
7145   // Handling growing first.
7146   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7147   if (SrcBitSize < DstBitSize) {
7148     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7149
7150     SmallVector<SDValue, 8> Ops;
7151     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7152          i += NumInputsPerOutput) {
7153       bool isLE = TLI.isLittleEndian();
7154       APInt NewBits = APInt(DstBitSize, 0);
7155       bool EltIsUndef = true;
7156       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7157         // Shift the previously computed bits over.
7158         NewBits <<= SrcBitSize;
7159         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7160         if (Op.getOpcode() == ISD::UNDEF) continue;
7161         EltIsUndef = false;
7162
7163         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7164                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7165       }
7166
7167       if (EltIsUndef)
7168         Ops.push_back(DAG.getUNDEF(DstEltVT));
7169       else
7170         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7171     }
7172
7173     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7174     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7175   }
7176
7177   // Finally, this must be the case where we are shrinking elements: each input
7178   // turns into multiple outputs.
7179   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7180   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7181                             NumOutputsPerInput*BV->getNumOperands());
7182   SmallVector<SDValue, 8> Ops;
7183
7184   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7185     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7186       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7187       continue;
7188     }
7189
7190     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7191                   getAPIntValue().zextOrTrunc(SrcBitSize);
7192
7193     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7194       APInt ThisVal = OpVal.trunc(DstBitSize);
7195       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7196       OpVal = OpVal.lshr(DstBitSize);
7197     }
7198
7199     // For big endian targets, swap the order of the pieces of each element.
7200     if (TLI.isBigEndian())
7201       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7202   }
7203
7204   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7205 }
7206
7207 /// Try to perform FMA combining on a given FADD node.
7208 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7209   SDValue N0 = N->getOperand(0);
7210   SDValue N1 = N->getOperand(1);
7211   EVT VT = N->getValueType(0);
7212   SDLoc SL(N);
7213
7214   const TargetOptions &Options = DAG.getTarget().Options;
7215   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7216                        Options.UnsafeFPMath);
7217
7218   // Floating-point multiply-add with intermediate rounding.
7219   bool HasFMAD = (LegalOperations &&
7220                   TLI.isOperationLegal(ISD::FMAD, VT));
7221
7222   // Floating-point multiply-add without intermediate rounding.
7223   bool HasFMA = ((!LegalOperations ||
7224                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7225                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7226                  UnsafeFPMath);
7227
7228   // No valid opcode, do not combine.
7229   if (!HasFMAD && !HasFMA)
7230     return SDValue();
7231
7232   // Always prefer FMAD to FMA for precision.
7233   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7234   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7235   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7236
7237   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7238   if (N0.getOpcode() == ISD::FMUL &&
7239       (Aggressive || N0->hasOneUse())) {
7240     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7241                        N0.getOperand(0), N0.getOperand(1), N1);
7242   }
7243
7244   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7245   // Note: Commutes FADD operands.
7246   if (N1.getOpcode() == ISD::FMUL &&
7247       (Aggressive || N1->hasOneUse())) {
7248     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7249                        N1.getOperand(0), N1.getOperand(1), N0);
7250   }
7251
7252   // Look through FP_EXTEND nodes to do more combining.
7253   if (UnsafeFPMath && LookThroughFPExt) {
7254     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7255     if (N0.getOpcode() == ISD::FP_EXTEND) {
7256       SDValue N00 = N0.getOperand(0);
7257       if (N00.getOpcode() == ISD::FMUL)
7258         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7259                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7260                                        N00.getOperand(0)),
7261                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7262                                        N00.getOperand(1)), N1);
7263     }
7264
7265     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7266     // Note: Commutes FADD operands.
7267     if (N1.getOpcode() == ISD::FP_EXTEND) {
7268       SDValue N10 = N1.getOperand(0);
7269       if (N10.getOpcode() == ISD::FMUL)
7270         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7271                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7272                                        N10.getOperand(0)),
7273                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7274                                        N10.getOperand(1)), N0);
7275     }
7276   }
7277
7278   // More folding opportunities when target permits.
7279   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7280     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7281     if (N0.getOpcode() == PreferredFusedOpcode &&
7282         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7283       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7284                          N0.getOperand(0), N0.getOperand(1),
7285                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7286                                      N0.getOperand(2).getOperand(0),
7287                                      N0.getOperand(2).getOperand(1),
7288                                      N1));
7289     }
7290
7291     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7292     if (N1->getOpcode() == PreferredFusedOpcode &&
7293         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7294       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7295                          N1.getOperand(0), N1.getOperand(1),
7296                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7297                                      N1.getOperand(2).getOperand(0),
7298                                      N1.getOperand(2).getOperand(1),
7299                                      N0));
7300     }
7301
7302     if (UnsafeFPMath && LookThroughFPExt) {
7303       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7304       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7305       auto FoldFAddFMAFPExtFMul = [&] (
7306           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7307         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7308                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7309                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7310                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7311                                        Z));
7312       };
7313       if (N0.getOpcode() == PreferredFusedOpcode) {
7314         SDValue N02 = N0.getOperand(2);
7315         if (N02.getOpcode() == ISD::FP_EXTEND) {
7316           SDValue N020 = N02.getOperand(0);
7317           if (N020.getOpcode() == ISD::FMUL)
7318             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7319                                         N020.getOperand(0), N020.getOperand(1),
7320                                         N1);
7321         }
7322       }
7323
7324       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7325       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7326       // FIXME: This turns two single-precision and one double-precision
7327       // operation into two double-precision operations, which might not be
7328       // interesting for all targets, especially GPUs.
7329       auto FoldFAddFPExtFMAFMul = [&] (
7330           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7331         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7332                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7333                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7334                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7335                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7336                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7337                                        Z));
7338       };
7339       if (N0.getOpcode() == ISD::FP_EXTEND) {
7340         SDValue N00 = N0.getOperand(0);
7341         if (N00.getOpcode() == PreferredFusedOpcode) {
7342           SDValue N002 = N00.getOperand(2);
7343           if (N002.getOpcode() == ISD::FMUL)
7344             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7345                                         N002.getOperand(0), N002.getOperand(1),
7346                                         N1);
7347         }
7348       }
7349
7350       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7351       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7352       if (N1.getOpcode() == PreferredFusedOpcode) {
7353         SDValue N12 = N1.getOperand(2);
7354         if (N12.getOpcode() == ISD::FP_EXTEND) {
7355           SDValue N120 = N12.getOperand(0);
7356           if (N120.getOpcode() == ISD::FMUL)
7357             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7358                                         N120.getOperand(0), N120.getOperand(1),
7359                                         N0);
7360         }
7361       }
7362
7363       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7364       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7365       // FIXME: This turns two single-precision and one double-precision
7366       // operation into two double-precision operations, which might not be
7367       // interesting for all targets, especially GPUs.
7368       if (N1.getOpcode() == ISD::FP_EXTEND) {
7369         SDValue N10 = N1.getOperand(0);
7370         if (N10.getOpcode() == PreferredFusedOpcode) {
7371           SDValue N102 = N10.getOperand(2);
7372           if (N102.getOpcode() == ISD::FMUL)
7373             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7374                                         N102.getOperand(0), N102.getOperand(1),
7375                                         N0);
7376         }
7377       }
7378     }
7379   }
7380
7381   return SDValue();
7382 }
7383
7384 /// Try to perform FMA combining on a given FSUB node.
7385 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7386
7387
7388
7389   SDValue N0 = N->getOperand(0);
7390   SDValue N1 = N->getOperand(1);
7391   EVT VT = N->getValueType(0);
7392
7393   SDLoc SL(N);
7394
7395   const TargetOptions &Options = DAG.getTarget().Options;
7396   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7397                        Options.UnsafeFPMath);
7398
7399   // Floating-point multiply-add with intermediate rounding.
7400   bool HasFMAD = (LegalOperations &&
7401                   TLI.isOperationLegal(ISD::FMAD, VT));
7402
7403   // Floating-point multiply-add without intermediate rounding.
7404   bool HasFMA = ((!LegalOperations ||
7405                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7406                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7407                  UnsafeFPMath);
7408
7409   // No valid opcode, do not combine.
7410   if (!HasFMAD && !HasFMA)
7411     return SDValue();
7412
7413   // Always prefer FMAD to FMA for precision.
7414   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7415   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7416   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7417
7418   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7419   if (N0.getOpcode() == ISD::FMUL &&
7420       (Aggressive || N0->hasOneUse())) {
7421     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7422                        N0.getOperand(0), N0.getOperand(1),
7423                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7424   }
7425
7426   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7427   // Note: Commutes FSUB operands.
7428   if (N1.getOpcode() == ISD::FMUL &&
7429       (Aggressive || N1->hasOneUse()))
7430     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7431                        DAG.getNode(ISD::FNEG, SL, VT,
7432                                    N1.getOperand(0)),
7433                        N1.getOperand(1), N0);
7434
7435   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7436   if (N0.getOpcode() == ISD::FNEG &&
7437       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7438       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7439     SDValue N00 = N0.getOperand(0).getOperand(0);
7440     SDValue N01 = N0.getOperand(0).getOperand(1);
7441     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7442                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7443                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7444   }
7445
7446   // Look through FP_EXTEND nodes to do more combining.
7447   if (UnsafeFPMath && LookThroughFPExt) {
7448     // fold (fsub (fpext (fmul x, y)), z)
7449     //   -> (fma (fpext x), (fpext y), (fneg z))
7450     if (N0.getOpcode() == ISD::FP_EXTEND) {
7451       SDValue N00 = N0.getOperand(0);
7452       if (N00.getOpcode() == ISD::FMUL)
7453         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7454                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7455                                        N00.getOperand(0)),
7456                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7457                                        N00.getOperand(1)),
7458                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7459     }
7460
7461     // fold (fsub x, (fpext (fmul y, z)))
7462     //   -> (fma (fneg (fpext y)), (fpext z), x)
7463     // Note: Commutes FSUB operands.
7464     if (N1.getOpcode() == ISD::FP_EXTEND) {
7465       SDValue N10 = N1.getOperand(0);
7466       if (N10.getOpcode() == ISD::FMUL)
7467         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7468                            DAG.getNode(ISD::FNEG, SL, VT,
7469                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7470                                                    N10.getOperand(0))),
7471                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7472                                        N10.getOperand(1)),
7473                            N0);
7474     }
7475
7476     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7477     //   -> (fneg (fma (fpext x), (fpext y), z))
7478     // Note: This could be removed with appropriate canonicalization of the
7479     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7480     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7481     // from implementing the canonicalization in visitFSUB.
7482     if (N0.getOpcode() == ISD::FP_EXTEND) {
7483       SDValue N00 = N0.getOperand(0);
7484       if (N00.getOpcode() == ISD::FNEG) {
7485         SDValue N000 = N00.getOperand(0);
7486         if (N000.getOpcode() == ISD::FMUL) {
7487           return DAG.getNode(ISD::FNEG, SL, VT,
7488                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7489                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7490                                                      N000.getOperand(0)),
7491                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7492                                                      N000.getOperand(1)),
7493                                          N1));
7494         }
7495       }
7496     }
7497
7498     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7499     //   -> (fneg (fma (fpext x)), (fpext y), z)
7500     // Note: This could be removed with appropriate canonicalization of the
7501     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7502     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7503     // from implementing the canonicalization in visitFSUB.
7504     if (N0.getOpcode() == ISD::FNEG) {
7505       SDValue N00 = N0.getOperand(0);
7506       if (N00.getOpcode() == ISD::FP_EXTEND) {
7507         SDValue N000 = N00.getOperand(0);
7508         if (N000.getOpcode() == ISD::FMUL) {
7509           return DAG.getNode(ISD::FNEG, SL, VT,
7510                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7511                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7512                                                      N000.getOperand(0)),
7513                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7514                                                      N000.getOperand(1)),
7515                                          N1));
7516         }
7517       }
7518     }
7519
7520   }
7521
7522   // More folding opportunities when target permits.
7523   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7524     // fold (fsub (fma x, y, (fmul u, v)), z)
7525     //   -> (fma x, y (fma u, v, (fneg z)))
7526     if (N0.getOpcode() == PreferredFusedOpcode &&
7527         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7528       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7529                          N0.getOperand(0), N0.getOperand(1),
7530                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7531                                      N0.getOperand(2).getOperand(0),
7532                                      N0.getOperand(2).getOperand(1),
7533                                      DAG.getNode(ISD::FNEG, SL, VT,
7534                                                  N1)));
7535     }
7536
7537     // fold (fsub x, (fma y, z, (fmul u, v)))
7538     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7539     if (N1.getOpcode() == PreferredFusedOpcode &&
7540         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7541       SDValue N20 = N1.getOperand(2).getOperand(0);
7542       SDValue N21 = N1.getOperand(2).getOperand(1);
7543       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7544                          DAG.getNode(ISD::FNEG, SL, VT,
7545                                      N1.getOperand(0)),
7546                          N1.getOperand(1),
7547                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7549
7550                                      N21, N0));
7551     }
7552
7553     if (UnsafeFPMath && LookThroughFPExt) {
7554       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7555       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7556       if (N0.getOpcode() == PreferredFusedOpcode) {
7557         SDValue N02 = N0.getOperand(2);
7558         if (N02.getOpcode() == ISD::FP_EXTEND) {
7559           SDValue N020 = N02.getOperand(0);
7560           if (N020.getOpcode() == ISD::FMUL)
7561             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7562                                N0.getOperand(0), N0.getOperand(1),
7563                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7564                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7565                                                        N020.getOperand(0)),
7566                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7567                                                        N020.getOperand(1)),
7568                                            DAG.getNode(ISD::FNEG, SL, VT,
7569                                                        N1)));
7570         }
7571       }
7572
7573       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7574       //   -> (fma (fpext x), (fpext y),
7575       //           (fma (fpext u), (fpext v), (fneg z)))
7576       // FIXME: This turns two single-precision and one double-precision
7577       // operation into two double-precision operations, which might not be
7578       // interesting for all targets, especially GPUs.
7579       if (N0.getOpcode() == ISD::FP_EXTEND) {
7580         SDValue N00 = N0.getOperand(0);
7581         if (N00.getOpcode() == PreferredFusedOpcode) {
7582           SDValue N002 = N00.getOperand(2);
7583           if (N002.getOpcode() == ISD::FMUL)
7584             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7585                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7586                                            N00.getOperand(0)),
7587                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7588                                            N00.getOperand(1)),
7589                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7590                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7591                                                        N002.getOperand(0)),
7592                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7593                                                        N002.getOperand(1)),
7594                                            DAG.getNode(ISD::FNEG, SL, VT,
7595                                                        N1)));
7596         }
7597       }
7598
7599       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7600       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7601       if (N1.getOpcode() == PreferredFusedOpcode &&
7602         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7603         SDValue N120 = N1.getOperand(2).getOperand(0);
7604         if (N120.getOpcode() == ISD::FMUL) {
7605           SDValue N1200 = N120.getOperand(0);
7606           SDValue N1201 = N120.getOperand(1);
7607           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7608                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7609                              N1.getOperand(1),
7610                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7611                                          DAG.getNode(ISD::FNEG, SL, VT,
7612                                              DAG.getNode(ISD::FP_EXTEND, SL,
7613                                                          VT, N1200)),
7614                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7615                                                      N1201),
7616                                          N0));
7617         }
7618       }
7619
7620       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7621       //   -> (fma (fneg (fpext y)), (fpext z),
7622       //           (fma (fneg (fpext u)), (fpext v), x))
7623       // FIXME: This turns two single-precision and one double-precision
7624       // operation into two double-precision operations, which might not be
7625       // interesting for all targets, especially GPUs.
7626       if (N1.getOpcode() == ISD::FP_EXTEND &&
7627         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7628         SDValue N100 = N1.getOperand(0).getOperand(0);
7629         SDValue N101 = N1.getOperand(0).getOperand(1);
7630         SDValue N102 = N1.getOperand(0).getOperand(2);
7631         if (N102.getOpcode() == ISD::FMUL) {
7632           SDValue N1020 = N102.getOperand(0);
7633           SDValue N1021 = N102.getOperand(1);
7634           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7635                              DAG.getNode(ISD::FNEG, SL, VT,
7636                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7637                                                      N100)),
7638                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7639                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7640                                          DAG.getNode(ISD::FNEG, SL, VT,
7641                                              DAG.getNode(ISD::FP_EXTEND, SL,
7642                                                          VT, N1020)),
7643                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7644                                                      N1021),
7645                                          N0));
7646         }
7647       }
7648     }
7649   }
7650
7651   return SDValue();
7652 }
7653
7654 SDValue DAGCombiner::visitFADD(SDNode *N) {
7655   SDValue N0 = N->getOperand(0);
7656   SDValue N1 = N->getOperand(1);
7657   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7658   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7659   EVT VT = N->getValueType(0);
7660   const TargetOptions &Options = DAG.getTarget().Options;
7661
7662   // fold vector ops
7663   if (VT.isVector())
7664     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7665       return FoldedVOp;
7666
7667   // fold (fadd c1, c2) -> c1 + c2
7668   if (N0CFP && N1CFP)
7669     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7670
7671   // canonicalize constant to RHS
7672   if (N0CFP && !N1CFP)
7673     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7674
7675   // fold (fadd A, (fneg B)) -> (fsub A, B)
7676   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7677       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7678     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7679                        GetNegatedExpression(N1, DAG, LegalOperations));
7680
7681   // fold (fadd (fneg A), B) -> (fsub B, A)
7682   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7683       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7684     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7685                        GetNegatedExpression(N0, DAG, LegalOperations));
7686
7687   // If 'unsafe math' is enabled, fold lots of things.
7688   if (Options.UnsafeFPMath) {
7689     // No FP constant should be created after legalization as Instruction
7690     // Selection pass has a hard time dealing with FP constants.
7691     bool AllowNewConst = (Level < AfterLegalizeDAG);
7692
7693     // fold (fadd A, 0) -> A
7694     if (N1CFP && N1CFP->getValueAPF().isZero())
7695       return N0;
7696
7697     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7698     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7699         isa<ConstantFPSDNode>(N0.getOperand(1)))
7700       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7701                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7702                                      N0.getOperand(1), N1));
7703
7704     // If allowed, fold (fadd (fneg x), x) -> 0.0
7705     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7706       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7707
7708     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7709     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7710       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7711
7712     // We can fold chains of FADD's of the same value into multiplications.
7713     // This transform is not safe in general because we are reducing the number
7714     // of rounding steps.
7715     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7716       if (N0.getOpcode() == ISD::FMUL) {
7717         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7718         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7719
7720         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7721         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7722           SDLoc DL(N);
7723           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7724                                        SDValue(CFP01, 0),
7725                                        DAG.getConstantFP(1.0, DL, VT));
7726           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7727         }
7728
7729         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7730         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7731             N1.getOperand(0) == N1.getOperand(1) &&
7732             N0.getOperand(0) == N1.getOperand(0)) {
7733           SDLoc DL(N);
7734           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7735                                        SDValue(CFP01, 0),
7736                                        DAG.getConstantFP(2.0, DL, VT));
7737           return DAG.getNode(ISD::FMUL, DL, VT,
7738                              N0.getOperand(0), NewCFP);
7739         }
7740       }
7741
7742       if (N1.getOpcode() == ISD::FMUL) {
7743         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7744         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7745
7746         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7747         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7748           SDLoc DL(N);
7749           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7750                                        SDValue(CFP11, 0),
7751                                        DAG.getConstantFP(1.0, DL, VT));
7752           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7753         }
7754
7755         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7756         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7757             N0.getOperand(0) == N0.getOperand(1) &&
7758             N1.getOperand(0) == N0.getOperand(0)) {
7759           SDLoc DL(N);
7760           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7761                                        SDValue(CFP11, 0),
7762                                        DAG.getConstantFP(2.0, DL, VT));
7763           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7764         }
7765       }
7766
7767       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7768         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7769         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7770         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7771             (N0.getOperand(0) == N1)) {
7772           SDLoc DL(N);
7773           return DAG.getNode(ISD::FMUL, DL, VT,
7774                              N1, DAG.getConstantFP(3.0, DL, VT));
7775         }
7776       }
7777
7778       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7779         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7780         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7781         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7782             N1.getOperand(0) == N0) {
7783           SDLoc DL(N);
7784           return DAG.getNode(ISD::FMUL, DL, VT,
7785                              N0, DAG.getConstantFP(3.0, DL, VT));
7786         }
7787       }
7788
7789       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7790       if (AllowNewConst &&
7791           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7792           N0.getOperand(0) == N0.getOperand(1) &&
7793           N1.getOperand(0) == N1.getOperand(1) &&
7794           N0.getOperand(0) == N1.getOperand(0)) {
7795         SDLoc DL(N);
7796         return DAG.getNode(ISD::FMUL, DL, VT,
7797                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7798       }
7799     }
7800
7801     // Canonicalize chains of adds to LHS to simplify the following transform.
7802     if (N0.getOpcode() != ISD::FADD && N1.getOpcode() == ISD::FADD)
7803       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7804     
7805     // Convert a chain of 3 dependent operations into 2 independent operations
7806     // and 1 dependent operation:
7807     //  (fadd N0: (fadd N00: (fadd z, w), N01: y), N1: x) ->
7808     //  (fadd N00: (fadd z, w), (fadd N1: x, N01: y))
7809     if (N0.getOpcode() == ISD::FADD &&  N0.hasOneUse() &&
7810         N1.getOpcode() != ISD::FADD) {
7811       SDValue N00 = N0.getOperand(0);
7812       if (N00.getOpcode() == ISD::FADD) {
7813         SDValue N01 = N0.getOperand(1);
7814         SDValue NewAdd = DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N01);
7815         return DAG.getNode(ISD::FADD, SDLoc(N), VT, N00, NewAdd);
7816       }
7817     }
7818   } // enable-unsafe-fp-math
7819
7820   // FADD -> FMA combines:
7821   SDValue Fused = visitFADDForFMACombine(N);
7822   if (Fused) {
7823     AddToWorklist(Fused.getNode());
7824     return Fused;
7825   }
7826
7827   return SDValue();
7828 }
7829
7830 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7831   SDValue N0 = N->getOperand(0);
7832   SDValue N1 = N->getOperand(1);
7833   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7834   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7835   EVT VT = N->getValueType(0);
7836   SDLoc dl(N);
7837   const TargetOptions &Options = DAG.getTarget().Options;
7838
7839   // fold vector ops
7840   if (VT.isVector())
7841     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7842       return FoldedVOp;
7843
7844   // fold (fsub c1, c2) -> c1-c2
7845   if (N0CFP && N1CFP)
7846     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7847
7848   // fold (fsub A, (fneg B)) -> (fadd A, B)
7849   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7850     return DAG.getNode(ISD::FADD, dl, VT, N0,
7851                        GetNegatedExpression(N1, DAG, LegalOperations));
7852
7853   // If 'unsafe math' is enabled, fold lots of things.
7854   if (Options.UnsafeFPMath) {
7855     // (fsub A, 0) -> A
7856     if (N1CFP && N1CFP->getValueAPF().isZero())
7857       return N0;
7858
7859     // (fsub 0, B) -> -B
7860     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7861       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7862         return GetNegatedExpression(N1, DAG, LegalOperations);
7863       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7864         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7865     }
7866
7867     // (fsub x, x) -> 0.0
7868     if (N0 == N1)
7869       return DAG.getConstantFP(0.0f, dl, VT);
7870
7871     // (fsub x, (fadd x, y)) -> (fneg y)
7872     // (fsub x, (fadd y, x)) -> (fneg y)
7873     if (N1.getOpcode() == ISD::FADD) {
7874       SDValue N10 = N1->getOperand(0);
7875       SDValue N11 = N1->getOperand(1);
7876
7877       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7878         return GetNegatedExpression(N11, DAG, LegalOperations);
7879
7880       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7881         return GetNegatedExpression(N10, DAG, LegalOperations);
7882     }
7883   }
7884
7885   // FSUB -> FMA combines:
7886   SDValue Fused = visitFSUBForFMACombine(N);
7887   if (Fused) {
7888     AddToWorklist(Fused.getNode());
7889     return Fused;
7890   }
7891
7892   return SDValue();
7893 }
7894
7895 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7896   SDValue N0 = N->getOperand(0);
7897   SDValue N1 = N->getOperand(1);
7898   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7899   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7900   EVT VT = N->getValueType(0);
7901   const TargetOptions &Options = DAG.getTarget().Options;
7902
7903   // fold vector ops
7904   if (VT.isVector()) {
7905     // This just handles C1 * C2 for vectors. Other vector folds are below.
7906     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7907       return FoldedVOp;
7908   }
7909
7910   // fold (fmul c1, c2) -> c1*c2
7911   if (N0CFP && N1CFP)
7912     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7913
7914   // canonicalize constant to RHS
7915   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7916      !isConstantFPBuildVectorOrConstantFP(N1))
7917     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7918
7919   // fold (fmul A, 1.0) -> A
7920   if (N1CFP && N1CFP->isExactlyValue(1.0))
7921     return N0;
7922
7923   if (Options.UnsafeFPMath) {
7924     // fold (fmul A, 0) -> 0
7925     if (N1CFP && N1CFP->getValueAPF().isZero())
7926       return N1;
7927
7928     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7929     if (N0.getOpcode() == ISD::FMUL) {
7930       // Fold scalars or any vector constants (not just splats).
7931       // This fold is done in general by InstCombine, but extra fmul insts
7932       // may have been generated during lowering.
7933       SDValue N00 = N0.getOperand(0);
7934       SDValue N01 = N0.getOperand(1);
7935       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7936       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7937       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7938       
7939       // Check 1: Make sure that the first operand of the inner multiply is NOT
7940       // a constant. Otherwise, we may induce infinite looping.
7941       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7942         // Check 2: Make sure that the second operand of the inner multiply and
7943         // the second operand of the outer multiply are constants.
7944         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7945             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7946           SDLoc SL(N);
7947           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7948           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7949         }
7950       }
7951     }
7952
7953     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7954     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7955     // during an early run of DAGCombiner can prevent folding with fmuls
7956     // inserted during lowering.
7957     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7958       SDLoc SL(N);
7959       const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7960       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7961       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7962     }
7963   }
7964
7965   // fold (fmul X, 2.0) -> (fadd X, X)
7966   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7967     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7968
7969   // fold (fmul X, -1.0) -> (fneg X)
7970   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7971     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7972       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7973
7974   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7975   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7976     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7977       // Both can be negated for free, check to see if at least one is cheaper
7978       // negated.
7979       if (LHSNeg == 2 || RHSNeg == 2)
7980         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7981                            GetNegatedExpression(N0, DAG, LegalOperations),
7982                            GetNegatedExpression(N1, DAG, LegalOperations));
7983     }
7984   }
7985
7986   return SDValue();
7987 }
7988
7989 SDValue DAGCombiner::visitFMA(SDNode *N) {
7990   SDValue N0 = N->getOperand(0);
7991   SDValue N1 = N->getOperand(1);
7992   SDValue N2 = N->getOperand(2);
7993   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7994   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7995   EVT VT = N->getValueType(0);
7996   SDLoc dl(N);
7997   const TargetOptions &Options = DAG.getTarget().Options;
7998
7999   // Constant fold FMA.
8000   if (isa<ConstantFPSDNode>(N0) &&
8001       isa<ConstantFPSDNode>(N1) &&
8002       isa<ConstantFPSDNode>(N2)) {
8003     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8004   }
8005
8006   if (Options.UnsafeFPMath) {
8007     if (N0CFP && N0CFP->isZero())
8008       return N2;
8009     if (N1CFP && N1CFP->isZero())
8010       return N2;
8011   }
8012   if (N0CFP && N0CFP->isExactlyValue(1.0))
8013     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8014   if (N1CFP && N1CFP->isExactlyValue(1.0))
8015     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8016
8017   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8018   if (N0CFP && !N1CFP)
8019     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8020
8021   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8022   if (Options.UnsafeFPMath && N1CFP &&
8023       N2.getOpcode() == ISD::FMUL &&
8024       N0 == N2.getOperand(0) &&
8025       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8026     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8027                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8028   }
8029
8030
8031   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8032   if (Options.UnsafeFPMath &&
8033       N0.getOpcode() == ISD::FMUL && N1CFP &&
8034       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8035     return DAG.getNode(ISD::FMA, dl, VT,
8036                        N0.getOperand(0),
8037                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8038                        N2);
8039   }
8040
8041   // (fma x, 1, y) -> (fadd x, y)
8042   // (fma x, -1, y) -> (fadd (fneg x), y)
8043   if (N1CFP) {
8044     if (N1CFP->isExactlyValue(1.0))
8045       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8046
8047     if (N1CFP->isExactlyValue(-1.0) &&
8048         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8049       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8050       AddToWorklist(RHSNeg.getNode());
8051       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8052     }
8053   }
8054
8055   // (fma x, c, x) -> (fmul x, (c+1))
8056   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8057     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8058                        DAG.getNode(ISD::FADD, dl, VT,
8059                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8060
8061   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8062   if (Options.UnsafeFPMath && N1CFP &&
8063       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8064     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8065                        DAG.getNode(ISD::FADD, dl, VT,
8066                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8067
8068
8069   return SDValue();
8070 }
8071
8072 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8073   SDValue N0 = N->getOperand(0);
8074   SDValue N1 = N->getOperand(1);
8075   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8076   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8077   EVT VT = N->getValueType(0);
8078   SDLoc DL(N);
8079   const TargetOptions &Options = DAG.getTarget().Options;
8080
8081   // fold vector ops
8082   if (VT.isVector())
8083     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8084       return FoldedVOp;
8085
8086   // fold (fdiv c1, c2) -> c1/c2
8087   if (N0CFP && N1CFP)
8088     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8089
8090   if (Options.UnsafeFPMath) {
8091     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8092     if (N1CFP) {
8093       // Compute the reciprocal 1.0 / c2.
8094       APFloat N1APF = N1CFP->getValueAPF();
8095       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8096       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8097       // Only do the transform if the reciprocal is a legal fp immediate that
8098       // isn't too nasty (eg NaN, denormal, ...).
8099       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8100           (!LegalOperations ||
8101            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8102            // backend)... we should handle this gracefully after Legalize.
8103            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8104            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8105            TLI.isFPImmLegal(Recip, VT)))
8106         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8107                            DAG.getConstantFP(Recip, DL, VT));
8108     }
8109
8110     // If this FDIV is part of a reciprocal square root, it may be folded
8111     // into a target-specific square root estimate instruction.
8112     if (N1.getOpcode() == ISD::FSQRT) {
8113       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8114         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8115       }
8116     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8117                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8118       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8119         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8120         AddToWorklist(RV.getNode());
8121         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8122       }
8123     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8124                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8125       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8126         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8127         AddToWorklist(RV.getNode());
8128         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8129       }
8130     } else if (N1.getOpcode() == ISD::FMUL) {
8131       // Look through an FMUL. Even though this won't remove the FDIV directly,
8132       // it's still worthwhile to get rid of the FSQRT if possible.
8133       SDValue SqrtOp;
8134       SDValue OtherOp;
8135       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8136         SqrtOp = N1.getOperand(0);
8137         OtherOp = N1.getOperand(1);
8138       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8139         SqrtOp = N1.getOperand(1);
8140         OtherOp = N1.getOperand(0);
8141       }
8142       if (SqrtOp.getNode()) {
8143         // We found a FSQRT, so try to make this fold:
8144         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8145         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8146           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8147           AddToWorklist(RV.getNode());
8148           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8149         }
8150       }
8151     }
8152
8153     // Fold into a reciprocal estimate and multiply instead of a real divide.
8154     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8155       AddToWorklist(RV.getNode());
8156       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8157     }
8158   }
8159
8160   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8161   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8162     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8163       // Both can be negated for free, check to see if at least one is cheaper
8164       // negated.
8165       if (LHSNeg == 2 || RHSNeg == 2)
8166         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8167                            GetNegatedExpression(N0, DAG, LegalOperations),
8168                            GetNegatedExpression(N1, DAG, LegalOperations));
8169     }
8170   }
8171
8172   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8173   // reciprocal.
8174   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8175   // Notice that this is not always beneficial. One reason is different target
8176   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8177   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8178   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8179   if (Options.UnsafeFPMath) {
8180     // Skip if current node is a reciprocal.
8181     if (N0CFP && N0CFP->isExactlyValue(1.0))
8182       return SDValue();
8183
8184     SmallVector<SDNode *, 4> Users;
8185     // Find all FDIV users of the same divisor.
8186     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8187                               UE = N1.getNode()->use_end();
8188          UI != UE; ++UI) {
8189       SDNode *User = UI.getUse().getUser();
8190       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8191         Users.push_back(User);
8192     }
8193
8194     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8195       SDLoc DL(N);
8196       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8197       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8198
8199       // Dividend / Divisor -> Dividend * Reciprocal
8200       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8201         if ((*I)->getOperand(0) != FPOne) {
8202           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8203                                         (*I)->getOperand(0), Reciprocal);
8204           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8205         }
8206       }
8207       return SDValue();
8208     }
8209   }
8210
8211   return SDValue();
8212 }
8213
8214 SDValue DAGCombiner::visitFREM(SDNode *N) {
8215   SDValue N0 = N->getOperand(0);
8216   SDValue N1 = N->getOperand(1);
8217   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8218   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8219   EVT VT = N->getValueType(0);
8220
8221   // fold (frem c1, c2) -> fmod(c1,c2)
8222   if (N0CFP && N1CFP)
8223     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8224
8225   return SDValue();
8226 }
8227
8228 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8229   if (DAG.getTarget().Options.UnsafeFPMath &&
8230       !TLI.isFsqrtCheap()) {
8231     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8232     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8233       EVT VT = RV.getValueType();
8234       SDLoc DL(N);
8235       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8236       AddToWorklist(RV.getNode());
8237
8238       // Unfortunately, RV is now NaN if the input was exactly 0.
8239       // Select out this case and force the answer to 0.
8240       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8241       SDValue ZeroCmp =
8242         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8243                      N->getOperand(0), Zero, ISD::SETEQ);
8244       AddToWorklist(ZeroCmp.getNode());
8245       AddToWorklist(RV.getNode());
8246
8247       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8248                        DL, VT, ZeroCmp, Zero, RV);
8249       return RV;
8250     }
8251   }
8252   return SDValue();
8253 }
8254
8255 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8256   SDValue N0 = N->getOperand(0);
8257   SDValue N1 = N->getOperand(1);
8258   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8259   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8260   EVT VT = N->getValueType(0);
8261
8262   if (N0CFP && N1CFP)  // Constant fold
8263     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8264
8265   if (N1CFP) {
8266     const APFloat& V = N1CFP->getValueAPF();
8267     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8268     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8269     if (!V.isNegative()) {
8270       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8271         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8272     } else {
8273       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8274         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8275                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8276     }
8277   }
8278
8279   // copysign(fabs(x), y) -> copysign(x, y)
8280   // copysign(fneg(x), y) -> copysign(x, y)
8281   // copysign(copysign(x,z), y) -> copysign(x, y)
8282   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8283       N0.getOpcode() == ISD::FCOPYSIGN)
8284     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8285                        N0.getOperand(0), N1);
8286
8287   // copysign(x, abs(y)) -> abs(x)
8288   if (N1.getOpcode() == ISD::FABS)
8289     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8290
8291   // copysign(x, copysign(y,z)) -> copysign(x, z)
8292   if (N1.getOpcode() == ISD::FCOPYSIGN)
8293     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8294                        N0, N1.getOperand(1));
8295
8296   // copysign(x, fp_extend(y)) -> copysign(x, y)
8297   // copysign(x, fp_round(y)) -> copysign(x, y)
8298   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8299     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8300                        N0, N1.getOperand(0));
8301
8302   return SDValue();
8303 }
8304
8305 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8306   SDValue N0 = N->getOperand(0);
8307   EVT VT = N->getValueType(0);
8308   EVT OpVT = N0.getValueType();
8309
8310   // fold (sint_to_fp c1) -> c1fp
8311   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8312       // ...but only if the target supports immediate floating-point values
8313       (!LegalOperations ||
8314        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8315     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8316
8317   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8318   // but UINT_TO_FP is legal on this target, try to convert.
8319   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8320       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8321     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8322     if (DAG.SignBitIsZero(N0))
8323       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8324   }
8325
8326   // The next optimizations are desirable only if SELECT_CC can be lowered.
8327   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8328     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8329     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8330         !VT.isVector() &&
8331         (!LegalOperations ||
8332          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8333       SDLoc DL(N);
8334       SDValue Ops[] =
8335         { N0.getOperand(0), N0.getOperand(1),
8336           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8337           N0.getOperand(2) };
8338       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8339     }
8340
8341     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8342     //      (select_cc x, y, 1.0, 0.0,, cc)
8343     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8344         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8345         (!LegalOperations ||
8346          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8347       SDLoc DL(N);
8348       SDValue Ops[] =
8349         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8350           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8351           N0.getOperand(0).getOperand(2) };
8352       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8353     }
8354   }
8355
8356   return SDValue();
8357 }
8358
8359 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8360   SDValue N0 = N->getOperand(0);
8361   EVT VT = N->getValueType(0);
8362   EVT OpVT = N0.getValueType();
8363
8364   // fold (uint_to_fp c1) -> c1fp
8365   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8366       // ...but only if the target supports immediate floating-point values
8367       (!LegalOperations ||
8368        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8369     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8370
8371   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8372   // but SINT_TO_FP is legal on this target, try to convert.
8373   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8374       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8375     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8376     if (DAG.SignBitIsZero(N0))
8377       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8378   }
8379
8380   // The next optimizations are desirable only if SELECT_CC can be lowered.
8381   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8382     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8383
8384     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8385         (!LegalOperations ||
8386          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8387       SDLoc DL(N);
8388       SDValue Ops[] =
8389         { N0.getOperand(0), N0.getOperand(1),
8390           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8391           N0.getOperand(2) };
8392       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8393     }
8394   }
8395
8396   return SDValue();
8397 }
8398
8399 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8400 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8401   SDValue N0 = N->getOperand(0);
8402   EVT VT = N->getValueType(0);
8403
8404   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8405     return SDValue();
8406
8407   SDValue Src = N0.getOperand(0);
8408   EVT SrcVT = Src.getValueType();
8409   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8410   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8411
8412   // We can safely assume the conversion won't overflow the output range,
8413   // because (for example) (uint8_t)18293.f is undefined behavior.
8414
8415   // Since we can assume the conversion won't overflow, our decision as to
8416   // whether the input will fit in the float should depend on the minimum
8417   // of the input range and output range.
8418
8419   // This means this is also safe for a signed input and unsigned output, since
8420   // a negative input would lead to undefined behavior.
8421   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8422   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8423   unsigned ActualSize = std::min(InputSize, OutputSize);
8424   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8425
8426   // We can only fold away the float conversion if the input range can be
8427   // represented exactly in the float range.
8428   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8429     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8430       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8431                                                        : ISD::ZERO_EXTEND;
8432       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8433     }
8434     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8435       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8436     if (SrcVT == VT)
8437       return Src;
8438     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8439   }
8440   return SDValue();
8441 }
8442
8443 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8444   SDValue N0 = N->getOperand(0);
8445   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8446   EVT VT = N->getValueType(0);
8447
8448   // fold (fp_to_sint c1fp) -> c1
8449   if (N0CFP)
8450     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8451
8452   return FoldIntToFPToInt(N, DAG);
8453 }
8454
8455 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8456   SDValue N0 = N->getOperand(0);
8457   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8458   EVT VT = N->getValueType(0);
8459
8460   // fold (fp_to_uint c1fp) -> c1
8461   if (N0CFP)
8462     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8463
8464   return FoldIntToFPToInt(N, DAG);
8465 }
8466
8467 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8468   SDValue N0 = N->getOperand(0);
8469   SDValue N1 = N->getOperand(1);
8470   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8471   EVT VT = N->getValueType(0);
8472
8473   // fold (fp_round c1fp) -> c1fp
8474   if (N0CFP)
8475     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8476
8477   // fold (fp_round (fp_extend x)) -> x
8478   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8479     return N0.getOperand(0);
8480
8481   // fold (fp_round (fp_round x)) -> (fp_round x)
8482   if (N0.getOpcode() == ISD::FP_ROUND) {
8483     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8484     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8485     // If the first fp_round isn't a value preserving truncation, it might
8486     // introduce a tie in the second fp_round, that wouldn't occur in the
8487     // single-step fp_round we want to fold to.
8488     // In other words, double rounding isn't the same as rounding.
8489     // Also, this is a value preserving truncation iff both fp_round's are.
8490     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8491       SDLoc DL(N);
8492       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8493                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8494     }
8495   }
8496
8497   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8498   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8499     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8500                               N0.getOperand(0), N1);
8501     AddToWorklist(Tmp.getNode());
8502     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8503                        Tmp, N0.getOperand(1));
8504   }
8505
8506   return SDValue();
8507 }
8508
8509 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8510   SDValue N0 = N->getOperand(0);
8511   EVT VT = N->getValueType(0);
8512   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8513   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8514
8515   // fold (fp_round_inreg c1fp) -> c1fp
8516   if (N0CFP && isTypeLegal(EVT)) {
8517     SDLoc DL(N);
8518     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8519     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8520   }
8521
8522   return SDValue();
8523 }
8524
8525 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8526   SDValue N0 = N->getOperand(0);
8527   EVT VT = N->getValueType(0);
8528
8529   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8530   if (N->hasOneUse() &&
8531       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8532     return SDValue();
8533
8534   // fold (fp_extend c1fp) -> c1fp
8535   if (isConstantFPBuildVectorOrConstantFP(N0))
8536     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8537
8538   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8539   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8540       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8541     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8542
8543   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8544   // value of X.
8545   if (N0.getOpcode() == ISD::FP_ROUND
8546       && N0.getNode()->getConstantOperandVal(1) == 1) {
8547     SDValue In = N0.getOperand(0);
8548     if (In.getValueType() == VT) return In;
8549     if (VT.bitsLT(In.getValueType()))
8550       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8551                          In, N0.getOperand(1));
8552     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8553   }
8554
8555   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8556   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8557        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8558     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8559     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8560                                      LN0->getChain(),
8561                                      LN0->getBasePtr(), N0.getValueType(),
8562                                      LN0->getMemOperand());
8563     CombineTo(N, ExtLoad);
8564     CombineTo(N0.getNode(),
8565               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8566                           N0.getValueType(), ExtLoad,
8567                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8568               ExtLoad.getValue(1));
8569     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8570   }
8571
8572   return SDValue();
8573 }
8574
8575 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8576   SDValue N0 = N->getOperand(0);
8577   EVT VT = N->getValueType(0);
8578
8579   // fold (fceil c1) -> fceil(c1)
8580   if (isConstantFPBuildVectorOrConstantFP(N0))
8581     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8582
8583   return SDValue();
8584 }
8585
8586 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8587   SDValue N0 = N->getOperand(0);
8588   EVT VT = N->getValueType(0);
8589
8590   // fold (ftrunc c1) -> ftrunc(c1)
8591   if (isConstantFPBuildVectorOrConstantFP(N0))
8592     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8593
8594   return SDValue();
8595 }
8596
8597 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8598   SDValue N0 = N->getOperand(0);
8599   EVT VT = N->getValueType(0);
8600
8601   // fold (ffloor c1) -> ffloor(c1)
8602   if (isConstantFPBuildVectorOrConstantFP(N0))
8603     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8604
8605   return SDValue();
8606 }
8607
8608 // FIXME: FNEG and FABS have a lot in common; refactor.
8609 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8610   SDValue N0 = N->getOperand(0);
8611   EVT VT = N->getValueType(0);
8612
8613   // Constant fold FNEG.
8614   if (isConstantFPBuildVectorOrConstantFP(N0))
8615     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8616
8617   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8618                          &DAG.getTarget().Options))
8619     return GetNegatedExpression(N0, DAG, LegalOperations);
8620
8621   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8622   // constant pool values.
8623   if (!TLI.isFNegFree(VT) &&
8624       N0.getOpcode() == ISD::BITCAST &&
8625       N0.getNode()->hasOneUse()) {
8626     SDValue Int = N0.getOperand(0);
8627     EVT IntVT = Int.getValueType();
8628     if (IntVT.isInteger() && !IntVT.isVector()) {
8629       APInt SignMask;
8630       if (N0.getValueType().isVector()) {
8631         // For a vector, get a mask such as 0x80... per scalar element
8632         // and splat it.
8633         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8634         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8635       } else {
8636         // For a scalar, just generate 0x80...
8637         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8638       }
8639       SDLoc DL0(N0);
8640       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8641                         DAG.getConstant(SignMask, DL0, IntVT));
8642       AddToWorklist(Int.getNode());
8643       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8644     }
8645   }
8646
8647   // (fneg (fmul c, x)) -> (fmul -c, x)
8648   if (N0.getOpcode() == ISD::FMUL) {
8649     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8650     if (CFP1) {
8651       APFloat CVal = CFP1->getValueAPF();
8652       CVal.changeSign();
8653       if (Level >= AfterLegalizeDAG &&
8654           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8655            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8656         return DAG.getNode(
8657             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8658             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8659     }
8660   }
8661
8662   return SDValue();
8663 }
8664
8665 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8666   SDValue N0 = N->getOperand(0);
8667   SDValue N1 = N->getOperand(1);
8668   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8669   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8670
8671   if (N0CFP && N1CFP) {
8672     const APFloat &C0 = N0CFP->getValueAPF();
8673     const APFloat &C1 = N1CFP->getValueAPF();
8674     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8675   }
8676
8677   if (N0CFP) {
8678     EVT VT = N->getValueType(0);
8679     // Canonicalize to constant on RHS.
8680     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8681   }
8682
8683   return SDValue();
8684 }
8685
8686 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8687   SDValue N0 = N->getOperand(0);
8688   SDValue N1 = N->getOperand(1);
8689   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8690   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8691
8692   if (N0CFP && N1CFP) {
8693     const APFloat &C0 = N0CFP->getValueAPF();
8694     const APFloat &C1 = N1CFP->getValueAPF();
8695     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8696   }
8697
8698   if (N0CFP) {
8699     EVT VT = N->getValueType(0);
8700     // Canonicalize to constant on RHS.
8701     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8702   }
8703
8704   return SDValue();
8705 }
8706
8707 SDValue DAGCombiner::visitFABS(SDNode *N) {
8708   SDValue N0 = N->getOperand(0);
8709   EVT VT = N->getValueType(0);
8710
8711   // fold (fabs c1) -> fabs(c1)
8712   if (isConstantFPBuildVectorOrConstantFP(N0))
8713     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8714
8715   // fold (fabs (fabs x)) -> (fabs x)
8716   if (N0.getOpcode() == ISD::FABS)
8717     return N->getOperand(0);
8718
8719   // fold (fabs (fneg x)) -> (fabs x)
8720   // fold (fabs (fcopysign x, y)) -> (fabs x)
8721   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8722     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8723
8724   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8725   // constant pool values.
8726   if (!TLI.isFAbsFree(VT) &&
8727       N0.getOpcode() == ISD::BITCAST &&
8728       N0.getNode()->hasOneUse()) {
8729     SDValue Int = N0.getOperand(0);
8730     EVT IntVT = Int.getValueType();
8731     if (IntVT.isInteger() && !IntVT.isVector()) {
8732       APInt SignMask;
8733       if (N0.getValueType().isVector()) {
8734         // For a vector, get a mask such as 0x7f... per scalar element
8735         // and splat it.
8736         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8737         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8738       } else {
8739         // For a scalar, just generate 0x7f...
8740         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8741       }
8742       SDLoc DL(N0);
8743       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8744                         DAG.getConstant(SignMask, DL, IntVT));
8745       AddToWorklist(Int.getNode());
8746       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8747     }
8748   }
8749
8750   return SDValue();
8751 }
8752
8753 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8754   SDValue Chain = N->getOperand(0);
8755   SDValue N1 = N->getOperand(1);
8756   SDValue N2 = N->getOperand(2);
8757
8758   // If N is a constant we could fold this into a fallthrough or unconditional
8759   // branch. However that doesn't happen very often in normal code, because
8760   // Instcombine/SimplifyCFG should have handled the available opportunities.
8761   // If we did this folding here, it would be necessary to update the
8762   // MachineBasicBlock CFG, which is awkward.
8763
8764   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8765   // on the target.
8766   if (N1.getOpcode() == ISD::SETCC &&
8767       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8768                                    N1.getOperand(0).getValueType())) {
8769     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8770                        Chain, N1.getOperand(2),
8771                        N1.getOperand(0), N1.getOperand(1), N2);
8772   }
8773
8774   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8775       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8776        (N1.getOperand(0).hasOneUse() &&
8777         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8778     SDNode *Trunc = nullptr;
8779     if (N1.getOpcode() == ISD::TRUNCATE) {
8780       // Look pass the truncate.
8781       Trunc = N1.getNode();
8782       N1 = N1.getOperand(0);
8783     }
8784
8785     // Match this pattern so that we can generate simpler code:
8786     //
8787     //   %a = ...
8788     //   %b = and i32 %a, 2
8789     //   %c = srl i32 %b, 1
8790     //   brcond i32 %c ...
8791     //
8792     // into
8793     //
8794     //   %a = ...
8795     //   %b = and i32 %a, 2
8796     //   %c = setcc eq %b, 0
8797     //   brcond %c ...
8798     //
8799     // This applies only when the AND constant value has one bit set and the
8800     // SRL constant is equal to the log2 of the AND constant. The back-end is
8801     // smart enough to convert the result into a TEST/JMP sequence.
8802     SDValue Op0 = N1.getOperand(0);
8803     SDValue Op1 = N1.getOperand(1);
8804
8805     if (Op0.getOpcode() == ISD::AND &&
8806         Op1.getOpcode() == ISD::Constant) {
8807       SDValue AndOp1 = Op0.getOperand(1);
8808
8809       if (AndOp1.getOpcode() == ISD::Constant) {
8810         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8811
8812         if (AndConst.isPowerOf2() &&
8813             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8814           SDLoc DL(N);
8815           SDValue SetCC =
8816             DAG.getSetCC(DL,
8817                          getSetCCResultType(Op0.getValueType()),
8818                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8819                          ISD::SETNE);
8820
8821           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8822                                           MVT::Other, Chain, SetCC, N2);
8823           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8824           // will convert it back to (X & C1) >> C2.
8825           CombineTo(N, NewBRCond, false);
8826           // Truncate is dead.
8827           if (Trunc)
8828             deleteAndRecombine(Trunc);
8829           // Replace the uses of SRL with SETCC
8830           WorklistRemover DeadNodes(*this);
8831           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8832           deleteAndRecombine(N1.getNode());
8833           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8834         }
8835       }
8836     }
8837
8838     if (Trunc)
8839       // Restore N1 if the above transformation doesn't match.
8840       N1 = N->getOperand(1);
8841   }
8842
8843   // Transform br(xor(x, y)) -> br(x != y)
8844   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8845   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8846     SDNode *TheXor = N1.getNode();
8847     SDValue Op0 = TheXor->getOperand(0);
8848     SDValue Op1 = TheXor->getOperand(1);
8849     if (Op0.getOpcode() == Op1.getOpcode()) {
8850       // Avoid missing important xor optimizations.
8851       SDValue Tmp = visitXOR(TheXor);
8852       if (Tmp.getNode()) {
8853         if (Tmp.getNode() != TheXor) {
8854           DEBUG(dbgs() << "\nReplacing.8 ";
8855                 TheXor->dump(&DAG);
8856                 dbgs() << "\nWith: ";
8857                 Tmp.getNode()->dump(&DAG);
8858                 dbgs() << '\n');
8859           WorklistRemover DeadNodes(*this);
8860           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8861           deleteAndRecombine(TheXor);
8862           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8863                              MVT::Other, Chain, Tmp, N2);
8864         }
8865
8866         // visitXOR has changed XOR's operands or replaced the XOR completely,
8867         // bail out.
8868         return SDValue(N, 0);
8869       }
8870     }
8871
8872     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8873       bool Equal = false;
8874       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8875         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8876             Op0.getOpcode() == ISD::XOR) {
8877           TheXor = Op0.getNode();
8878           Equal = true;
8879         }
8880
8881       EVT SetCCVT = N1.getValueType();
8882       if (LegalTypes)
8883         SetCCVT = getSetCCResultType(SetCCVT);
8884       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8885                                    SetCCVT,
8886                                    Op0, Op1,
8887                                    Equal ? ISD::SETEQ : ISD::SETNE);
8888       // Replace the uses of XOR with SETCC
8889       WorklistRemover DeadNodes(*this);
8890       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8891       deleteAndRecombine(N1.getNode());
8892       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8893                          MVT::Other, Chain, SetCC, N2);
8894     }
8895   }
8896
8897   return SDValue();
8898 }
8899
8900 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8901 //
8902 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8903   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8904   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8905
8906   // If N is a constant we could fold this into a fallthrough or unconditional
8907   // branch. However that doesn't happen very often in normal code, because
8908   // Instcombine/SimplifyCFG should have handled the available opportunities.
8909   // If we did this folding here, it would be necessary to update the
8910   // MachineBasicBlock CFG, which is awkward.
8911
8912   // Use SimplifySetCC to simplify SETCC's.
8913   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8914                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8915                                false);
8916   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8917
8918   // fold to a simpler setcc
8919   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8920     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8921                        N->getOperand(0), Simp.getOperand(2),
8922                        Simp.getOperand(0), Simp.getOperand(1),
8923                        N->getOperand(4));
8924
8925   return SDValue();
8926 }
8927
8928 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8929 /// and that N may be folded in the load / store addressing mode.
8930 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8931                                     SelectionDAG &DAG,
8932                                     const TargetLowering &TLI) {
8933   EVT VT;
8934   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8935     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8936       return false;
8937     VT = LD->getMemoryVT();
8938   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8939     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8940       return false;
8941     VT = ST->getMemoryVT();
8942   } else
8943     return false;
8944
8945   TargetLowering::AddrMode AM;
8946   if (N->getOpcode() == ISD::ADD) {
8947     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8948     if (Offset)
8949       // [reg +/- imm]
8950       AM.BaseOffs = Offset->getSExtValue();
8951     else
8952       // [reg +/- reg]
8953       AM.Scale = 1;
8954   } else if (N->getOpcode() == ISD::SUB) {
8955     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8956     if (Offset)
8957       // [reg +/- imm]
8958       AM.BaseOffs = -Offset->getSExtValue();
8959     else
8960       // [reg +/- reg]
8961       AM.Scale = 1;
8962   } else
8963     return false;
8964
8965   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8966 }
8967
8968 /// Try turning a load/store into a pre-indexed load/store when the base
8969 /// pointer is an add or subtract and it has other uses besides the load/store.
8970 /// After the transformation, the new indexed load/store has effectively folded
8971 /// the add/subtract in and all of its other uses are redirected to the
8972 /// new load/store.
8973 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8974   if (Level < AfterLegalizeDAG)
8975     return false;
8976
8977   bool isLoad = true;
8978   SDValue Ptr;
8979   EVT VT;
8980   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8981     if (LD->isIndexed())
8982       return false;
8983     VT = LD->getMemoryVT();
8984     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8985         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8986       return false;
8987     Ptr = LD->getBasePtr();
8988   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8989     if (ST->isIndexed())
8990       return false;
8991     VT = ST->getMemoryVT();
8992     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8993         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8994       return false;
8995     Ptr = ST->getBasePtr();
8996     isLoad = false;
8997   } else {
8998     return false;
8999   }
9000
9001   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9002   // out.  There is no reason to make this a preinc/predec.
9003   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9004       Ptr.getNode()->hasOneUse())
9005     return false;
9006
9007   // Ask the target to do addressing mode selection.
9008   SDValue BasePtr;
9009   SDValue Offset;
9010   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9011   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9012     return false;
9013
9014   // Backends without true r+i pre-indexed forms may need to pass a
9015   // constant base with a variable offset so that constant coercion
9016   // will work with the patterns in canonical form.
9017   bool Swapped = false;
9018   if (isa<ConstantSDNode>(BasePtr)) {
9019     std::swap(BasePtr, Offset);
9020     Swapped = true;
9021   }
9022
9023   // Don't create a indexed load / store with zero offset.
9024   if (isa<ConstantSDNode>(Offset) &&
9025       cast<ConstantSDNode>(Offset)->isNullValue())
9026     return false;
9027
9028   // Try turning it into a pre-indexed load / store except when:
9029   // 1) The new base ptr is a frame index.
9030   // 2) If N is a store and the new base ptr is either the same as or is a
9031   //    predecessor of the value being stored.
9032   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9033   //    that would create a cycle.
9034   // 4) All uses are load / store ops that use it as old base ptr.
9035
9036   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9037   // (plus the implicit offset) to a register to preinc anyway.
9038   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9039     return false;
9040
9041   // Check #2.
9042   if (!isLoad) {
9043     SDValue Val = cast<StoreSDNode>(N)->getValue();
9044     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9045       return false;
9046   }
9047
9048   // If the offset is a constant, there may be other adds of constants that
9049   // can be folded with this one. We should do this to avoid having to keep
9050   // a copy of the original base pointer.
9051   SmallVector<SDNode *, 16> OtherUses;
9052   if (isa<ConstantSDNode>(Offset))
9053     for (SDNode *Use : BasePtr.getNode()->uses()) {
9054       if (Use == Ptr.getNode())
9055         continue;
9056
9057       if (Use->isPredecessorOf(N))
9058         continue;
9059
9060       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9061         OtherUses.clear();
9062         break;
9063       }
9064
9065       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9066       if (Op1.getNode() == BasePtr.getNode())
9067         std::swap(Op0, Op1);
9068       assert(Op0.getNode() == BasePtr.getNode() &&
9069              "Use of ADD/SUB but not an operand");
9070
9071       if (!isa<ConstantSDNode>(Op1)) {
9072         OtherUses.clear();
9073         break;
9074       }
9075
9076       // FIXME: In some cases, we can be smarter about this.
9077       if (Op1.getValueType() != Offset.getValueType()) {
9078         OtherUses.clear();
9079         break;
9080       }
9081
9082       OtherUses.push_back(Use);
9083     }
9084
9085   if (Swapped)
9086     std::swap(BasePtr, Offset);
9087
9088   // Now check for #3 and #4.
9089   bool RealUse = false;
9090
9091   // Caches for hasPredecessorHelper
9092   SmallPtrSet<const SDNode *, 32> Visited;
9093   SmallVector<const SDNode *, 16> Worklist;
9094
9095   for (SDNode *Use : Ptr.getNode()->uses()) {
9096     if (Use == N)
9097       continue;
9098     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9099       return false;
9100
9101     // If Ptr may be folded in addressing mode of other use, then it's
9102     // not profitable to do this transformation.
9103     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9104       RealUse = true;
9105   }
9106
9107   if (!RealUse)
9108     return false;
9109
9110   SDValue Result;
9111   if (isLoad)
9112     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9113                                 BasePtr, Offset, AM);
9114   else
9115     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9116                                  BasePtr, Offset, AM);
9117   ++PreIndexedNodes;
9118   ++NodesCombined;
9119   DEBUG(dbgs() << "\nReplacing.4 ";
9120         N->dump(&DAG);
9121         dbgs() << "\nWith: ";
9122         Result.getNode()->dump(&DAG);
9123         dbgs() << '\n');
9124   WorklistRemover DeadNodes(*this);
9125   if (isLoad) {
9126     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9127     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9128   } else {
9129     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9130   }
9131
9132   // Finally, since the node is now dead, remove it from the graph.
9133   deleteAndRecombine(N);
9134
9135   if (Swapped)
9136     std::swap(BasePtr, Offset);
9137
9138   // Replace other uses of BasePtr that can be updated to use Ptr
9139   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9140     unsigned OffsetIdx = 1;
9141     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9142       OffsetIdx = 0;
9143     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9144            BasePtr.getNode() && "Expected BasePtr operand");
9145
9146     // We need to replace ptr0 in the following expression:
9147     //   x0 * offset0 + y0 * ptr0 = t0
9148     // knowing that
9149     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9150     //
9151     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9152     // indexed load/store and the expresion that needs to be re-written.
9153     //
9154     // Therefore, we have:
9155     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9156
9157     ConstantSDNode *CN =
9158       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9159     int X0, X1, Y0, Y1;
9160     APInt Offset0 = CN->getAPIntValue();
9161     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9162
9163     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9164     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9165     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9166     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9167
9168     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9169
9170     APInt CNV = Offset0;
9171     if (X0 < 0) CNV = -CNV;
9172     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9173     else CNV = CNV - Offset1;
9174
9175     SDLoc DL(OtherUses[i]);
9176
9177     // We can now generate the new expression.
9178     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9179     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9180
9181     SDValue NewUse = DAG.getNode(Opcode,
9182                                  DL,
9183                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9184     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9185     deleteAndRecombine(OtherUses[i]);
9186   }
9187
9188   // Replace the uses of Ptr with uses of the updated base value.
9189   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9190   deleteAndRecombine(Ptr.getNode());
9191
9192   return true;
9193 }
9194
9195 /// Try to combine a load/store with a add/sub of the base pointer node into a
9196 /// post-indexed load/store. The transformation folded the add/subtract into the
9197 /// new indexed load/store effectively and all of its uses are redirected to the
9198 /// new load/store.
9199 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9200   if (Level < AfterLegalizeDAG)
9201     return false;
9202
9203   bool isLoad = true;
9204   SDValue Ptr;
9205   EVT VT;
9206   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9207     if (LD->isIndexed())
9208       return false;
9209     VT = LD->getMemoryVT();
9210     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9211         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9212       return false;
9213     Ptr = LD->getBasePtr();
9214   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9215     if (ST->isIndexed())
9216       return false;
9217     VT = ST->getMemoryVT();
9218     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9219         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9220       return false;
9221     Ptr = ST->getBasePtr();
9222     isLoad = false;
9223   } else {
9224     return false;
9225   }
9226
9227   if (Ptr.getNode()->hasOneUse())
9228     return false;
9229
9230   for (SDNode *Op : Ptr.getNode()->uses()) {
9231     if (Op == N ||
9232         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9233       continue;
9234
9235     SDValue BasePtr;
9236     SDValue Offset;
9237     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9238     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9239       // Don't create a indexed load / store with zero offset.
9240       if (isa<ConstantSDNode>(Offset) &&
9241           cast<ConstantSDNode>(Offset)->isNullValue())
9242         continue;
9243
9244       // Try turning it into a post-indexed load / store except when
9245       // 1) All uses are load / store ops that use it as base ptr (and
9246       //    it may be folded as addressing mmode).
9247       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9248       //    nor a successor of N. Otherwise, if Op is folded that would
9249       //    create a cycle.
9250
9251       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9252         continue;
9253
9254       // Check for #1.
9255       bool TryNext = false;
9256       for (SDNode *Use : BasePtr.getNode()->uses()) {
9257         if (Use == Ptr.getNode())
9258           continue;
9259
9260         // If all the uses are load / store addresses, then don't do the
9261         // transformation.
9262         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9263           bool RealUse = false;
9264           for (SDNode *UseUse : Use->uses()) {
9265             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9266               RealUse = true;
9267           }
9268
9269           if (!RealUse) {
9270             TryNext = true;
9271             break;
9272           }
9273         }
9274       }
9275
9276       if (TryNext)
9277         continue;
9278
9279       // Check for #2
9280       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9281         SDValue Result = isLoad
9282           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9283                                BasePtr, Offset, AM)
9284           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9285                                 BasePtr, Offset, AM);
9286         ++PostIndexedNodes;
9287         ++NodesCombined;
9288         DEBUG(dbgs() << "\nReplacing.5 ";
9289               N->dump(&DAG);
9290               dbgs() << "\nWith: ";
9291               Result.getNode()->dump(&DAG);
9292               dbgs() << '\n');
9293         WorklistRemover DeadNodes(*this);
9294         if (isLoad) {
9295           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9296           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9297         } else {
9298           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9299         }
9300
9301         // Finally, since the node is now dead, remove it from the graph.
9302         deleteAndRecombine(N);
9303
9304         // Replace the uses of Use with uses of the updated base value.
9305         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9306                                       Result.getValue(isLoad ? 1 : 0));
9307         deleteAndRecombine(Op);
9308         return true;
9309       }
9310     }
9311   }
9312
9313   return false;
9314 }
9315
9316 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9317 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9318   ISD::MemIndexedMode AM = LD->getAddressingMode();
9319   assert(AM != ISD::UNINDEXED);
9320   SDValue BP = LD->getOperand(1);
9321   SDValue Inc = LD->getOperand(2);
9322
9323   // Some backends use TargetConstants for load offsets, but don't expect
9324   // TargetConstants in general ADD nodes. We can convert these constants into
9325   // regular Constants (if the constant is not opaque).
9326   assert((Inc.getOpcode() != ISD::TargetConstant ||
9327           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9328          "Cannot split out indexing using opaque target constants");
9329   if (Inc.getOpcode() == ISD::TargetConstant) {
9330     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9331     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9332                           ConstInc->getValueType(0));
9333   }
9334
9335   unsigned Opc =
9336       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9337   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9338 }
9339
9340 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9341   LoadSDNode *LD  = cast<LoadSDNode>(N);
9342   SDValue Chain = LD->getChain();
9343   SDValue Ptr   = LD->getBasePtr();
9344
9345   // If load is not volatile and there are no uses of the loaded value (and
9346   // the updated indexed value in case of indexed loads), change uses of the
9347   // chain value into uses of the chain input (i.e. delete the dead load).
9348   if (!LD->isVolatile()) {
9349     if (N->getValueType(1) == MVT::Other) {
9350       // Unindexed loads.
9351       if (!N->hasAnyUseOfValue(0)) {
9352         // It's not safe to use the two value CombineTo variant here. e.g.
9353         // v1, chain2 = load chain1, loc
9354         // v2, chain3 = load chain2, loc
9355         // v3         = add v2, c
9356         // Now we replace use of chain2 with chain1.  This makes the second load
9357         // isomorphic to the one we are deleting, and thus makes this load live.
9358         DEBUG(dbgs() << "\nReplacing.6 ";
9359               N->dump(&DAG);
9360               dbgs() << "\nWith chain: ";
9361               Chain.getNode()->dump(&DAG);
9362               dbgs() << "\n");
9363         WorklistRemover DeadNodes(*this);
9364         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9365
9366         if (N->use_empty())
9367           deleteAndRecombine(N);
9368
9369         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9370       }
9371     } else {
9372       // Indexed loads.
9373       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9374
9375       // If this load has an opaque TargetConstant offset, then we cannot split
9376       // the indexing into an add/sub directly (that TargetConstant may not be
9377       // valid for a different type of node, and we cannot convert an opaque
9378       // target constant into a regular constant).
9379       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9380                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9381
9382       if (!N->hasAnyUseOfValue(0) &&
9383           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9384         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9385         SDValue Index;
9386         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9387           Index = SplitIndexingFromLoad(LD);
9388           // Try to fold the base pointer arithmetic into subsequent loads and
9389           // stores.
9390           AddUsersToWorklist(N);
9391         } else
9392           Index = DAG.getUNDEF(N->getValueType(1));
9393         DEBUG(dbgs() << "\nReplacing.7 ";
9394               N->dump(&DAG);
9395               dbgs() << "\nWith: ";
9396               Undef.getNode()->dump(&DAG);
9397               dbgs() << " and 2 other values\n");
9398         WorklistRemover DeadNodes(*this);
9399         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9400         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9401         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9402         deleteAndRecombine(N);
9403         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9404       }
9405     }
9406   }
9407
9408   // If this load is directly stored, replace the load value with the stored
9409   // value.
9410   // TODO: Handle store large -> read small portion.
9411   // TODO: Handle TRUNCSTORE/LOADEXT
9412   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9413     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9414       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9415       if (PrevST->getBasePtr() == Ptr &&
9416           PrevST->getValue().getValueType() == N->getValueType(0))
9417       return CombineTo(N, Chain.getOperand(1), Chain);
9418     }
9419   }
9420
9421   // Try to infer better alignment information than the load already has.
9422   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9423     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9424       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9425         SDValue NewLoad =
9426                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9427                               LD->getValueType(0),
9428                               Chain, Ptr, LD->getPointerInfo(),
9429                               LD->getMemoryVT(),
9430                               LD->isVolatile(), LD->isNonTemporal(),
9431                               LD->isInvariant(), Align, LD->getAAInfo());
9432         if (NewLoad.getNode() != N)
9433           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9434       }
9435     }
9436   }
9437
9438   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9439                                                   : DAG.getSubtarget().useAA();
9440 #ifndef NDEBUG
9441   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9442       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9443     UseAA = false;
9444 #endif
9445   if (UseAA && LD->isUnindexed()) {
9446     // Walk up chain skipping non-aliasing memory nodes.
9447     SDValue BetterChain = FindBetterChain(N, Chain);
9448
9449     // If there is a better chain.
9450     if (Chain != BetterChain) {
9451       SDValue ReplLoad;
9452
9453       // Replace the chain to void dependency.
9454       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9455         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9456                                BetterChain, Ptr, LD->getMemOperand());
9457       } else {
9458         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9459                                   LD->getValueType(0),
9460                                   BetterChain, Ptr, LD->getMemoryVT(),
9461                                   LD->getMemOperand());
9462       }
9463
9464       // Create token factor to keep old chain connected.
9465       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9466                                   MVT::Other, Chain, ReplLoad.getValue(1));
9467
9468       // Make sure the new and old chains are cleaned up.
9469       AddToWorklist(Token.getNode());
9470
9471       // Replace uses with load result and token factor. Don't add users
9472       // to work list.
9473       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9474     }
9475   }
9476
9477   // Try transforming N to an indexed load.
9478   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9479     return SDValue(N, 0);
9480
9481   // Try to slice up N to more direct loads if the slices are mapped to
9482   // different register banks or pairing can take place.
9483   if (SliceUpLoad(N))
9484     return SDValue(N, 0);
9485
9486   return SDValue();
9487 }
9488
9489 namespace {
9490 /// \brief Helper structure used to slice a load in smaller loads.
9491 /// Basically a slice is obtained from the following sequence:
9492 /// Origin = load Ty1, Base
9493 /// Shift = srl Ty1 Origin, CstTy Amount
9494 /// Inst = trunc Shift to Ty2
9495 ///
9496 /// Then, it will be rewriten into:
9497 /// Slice = load SliceTy, Base + SliceOffset
9498 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9499 ///
9500 /// SliceTy is deduced from the number of bits that are actually used to
9501 /// build Inst.
9502 struct LoadedSlice {
9503   /// \brief Helper structure used to compute the cost of a slice.
9504   struct Cost {
9505     /// Are we optimizing for code size.
9506     bool ForCodeSize;
9507     /// Various cost.
9508     unsigned Loads;
9509     unsigned Truncates;
9510     unsigned CrossRegisterBanksCopies;
9511     unsigned ZExts;
9512     unsigned Shift;
9513
9514     Cost(bool ForCodeSize = false)
9515         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9516           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9517
9518     /// \brief Get the cost of one isolated slice.
9519     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9520         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9521           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9522       EVT TruncType = LS.Inst->getValueType(0);
9523       EVT LoadedType = LS.getLoadedType();
9524       if (TruncType != LoadedType &&
9525           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9526         ZExts = 1;
9527     }
9528
9529     /// \brief Account for slicing gain in the current cost.
9530     /// Slicing provide a few gains like removing a shift or a
9531     /// truncate. This method allows to grow the cost of the original
9532     /// load with the gain from this slice.
9533     void addSliceGain(const LoadedSlice &LS) {
9534       // Each slice saves a truncate.
9535       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9536       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9537                               LS.Inst->getOperand(0).getValueType()))
9538         ++Truncates;
9539       // If there is a shift amount, this slice gets rid of it.
9540       if (LS.Shift)
9541         ++Shift;
9542       // If this slice can merge a cross register bank copy, account for it.
9543       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9544         ++CrossRegisterBanksCopies;
9545     }
9546
9547     Cost &operator+=(const Cost &RHS) {
9548       Loads += RHS.Loads;
9549       Truncates += RHS.Truncates;
9550       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9551       ZExts += RHS.ZExts;
9552       Shift += RHS.Shift;
9553       return *this;
9554     }
9555
9556     bool operator==(const Cost &RHS) const {
9557       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9558              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9559              ZExts == RHS.ZExts && Shift == RHS.Shift;
9560     }
9561
9562     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9563
9564     bool operator<(const Cost &RHS) const {
9565       // Assume cross register banks copies are as expensive as loads.
9566       // FIXME: Do we want some more target hooks?
9567       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9568       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9569       // Unless we are optimizing for code size, consider the
9570       // expensive operation first.
9571       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9572         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9573       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9574              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9575     }
9576
9577     bool operator>(const Cost &RHS) const { return RHS < *this; }
9578
9579     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9580
9581     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9582   };
9583   // The last instruction that represent the slice. This should be a
9584   // truncate instruction.
9585   SDNode *Inst;
9586   // The original load instruction.
9587   LoadSDNode *Origin;
9588   // The right shift amount in bits from the original load.
9589   unsigned Shift;
9590   // The DAG from which Origin came from.
9591   // This is used to get some contextual information about legal types, etc.
9592   SelectionDAG *DAG;
9593
9594   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9595               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9596       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9597
9598   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9599   /// \return Result is \p BitWidth and has used bits set to 1 and
9600   ///         not used bits set to 0.
9601   APInt getUsedBits() const {
9602     // Reproduce the trunc(lshr) sequence:
9603     // - Start from the truncated value.
9604     // - Zero extend to the desired bit width.
9605     // - Shift left.
9606     assert(Origin && "No original load to compare against.");
9607     unsigned BitWidth = Origin->getValueSizeInBits(0);
9608     assert(Inst && "This slice is not bound to an instruction");
9609     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9610            "Extracted slice is bigger than the whole type!");
9611     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9612     UsedBits.setAllBits();
9613     UsedBits = UsedBits.zext(BitWidth);
9614     UsedBits <<= Shift;
9615     return UsedBits;
9616   }
9617
9618   /// \brief Get the size of the slice to be loaded in bytes.
9619   unsigned getLoadedSize() const {
9620     unsigned SliceSize = getUsedBits().countPopulation();
9621     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9622     return SliceSize / 8;
9623   }
9624
9625   /// \brief Get the type that will be loaded for this slice.
9626   /// Note: This may not be the final type for the slice.
9627   EVT getLoadedType() const {
9628     assert(DAG && "Missing context");
9629     LLVMContext &Ctxt = *DAG->getContext();
9630     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9631   }
9632
9633   /// \brief Get the alignment of the load used for this slice.
9634   unsigned getAlignment() const {
9635     unsigned Alignment = Origin->getAlignment();
9636     unsigned Offset = getOffsetFromBase();
9637     if (Offset != 0)
9638       Alignment = MinAlign(Alignment, Alignment + Offset);
9639     return Alignment;
9640   }
9641
9642   /// \brief Check if this slice can be rewritten with legal operations.
9643   bool isLegal() const {
9644     // An invalid slice is not legal.
9645     if (!Origin || !Inst || !DAG)
9646       return false;
9647
9648     // Offsets are for indexed load only, we do not handle that.
9649     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9650       return false;
9651
9652     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9653
9654     // Check that the type is legal.
9655     EVT SliceType = getLoadedType();
9656     if (!TLI.isTypeLegal(SliceType))
9657       return false;
9658
9659     // Check that the load is legal for this type.
9660     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9661       return false;
9662
9663     // Check that the offset can be computed.
9664     // 1. Check its type.
9665     EVT PtrType = Origin->getBasePtr().getValueType();
9666     if (PtrType == MVT::Untyped || PtrType.isExtended())
9667       return false;
9668
9669     // 2. Check that it fits in the immediate.
9670     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9671       return false;
9672
9673     // 3. Check that the computation is legal.
9674     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9675       return false;
9676
9677     // Check that the zext is legal if it needs one.
9678     EVT TruncateType = Inst->getValueType(0);
9679     if (TruncateType != SliceType &&
9680         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9681       return false;
9682
9683     return true;
9684   }
9685
9686   /// \brief Get the offset in bytes of this slice in the original chunk of
9687   /// bits.
9688   /// \pre DAG != nullptr.
9689   uint64_t getOffsetFromBase() const {
9690     assert(DAG && "Missing context.");
9691     bool IsBigEndian =
9692         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9693     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9694     uint64_t Offset = Shift / 8;
9695     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9696     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9697            "The size of the original loaded type is not a multiple of a"
9698            " byte.");
9699     // If Offset is bigger than TySizeInBytes, it means we are loading all
9700     // zeros. This should have been optimized before in the process.
9701     assert(TySizeInBytes > Offset &&
9702            "Invalid shift amount for given loaded size");
9703     if (IsBigEndian)
9704       Offset = TySizeInBytes - Offset - getLoadedSize();
9705     return Offset;
9706   }
9707
9708   /// \brief Generate the sequence of instructions to load the slice
9709   /// represented by this object and redirect the uses of this slice to
9710   /// this new sequence of instructions.
9711   /// \pre this->Inst && this->Origin are valid Instructions and this
9712   /// object passed the legal check: LoadedSlice::isLegal returned true.
9713   /// \return The last instruction of the sequence used to load the slice.
9714   SDValue loadSlice() const {
9715     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9716     const SDValue &OldBaseAddr = Origin->getBasePtr();
9717     SDValue BaseAddr = OldBaseAddr;
9718     // Get the offset in that chunk of bytes w.r.t. the endianess.
9719     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9720     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9721     if (Offset) {
9722       // BaseAddr = BaseAddr + Offset.
9723       EVT ArithType = BaseAddr.getValueType();
9724       SDLoc DL(Origin);
9725       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9726                               DAG->getConstant(Offset, DL, ArithType));
9727     }
9728
9729     // Create the type of the loaded slice according to its size.
9730     EVT SliceType = getLoadedType();
9731
9732     // Create the load for the slice.
9733     SDValue LastInst = DAG->getLoad(
9734         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9735         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9736         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9737     // If the final type is not the same as the loaded type, this means that
9738     // we have to pad with zero. Create a zero extend for that.
9739     EVT FinalType = Inst->getValueType(0);
9740     if (SliceType != FinalType)
9741       LastInst =
9742           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9743     return LastInst;
9744   }
9745
9746   /// \brief Check if this slice can be merged with an expensive cross register
9747   /// bank copy. E.g.,
9748   /// i = load i32
9749   /// f = bitcast i32 i to float
9750   bool canMergeExpensiveCrossRegisterBankCopy() const {
9751     if (!Inst || !Inst->hasOneUse())
9752       return false;
9753     SDNode *Use = *Inst->use_begin();
9754     if (Use->getOpcode() != ISD::BITCAST)
9755       return false;
9756     assert(DAG && "Missing context");
9757     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9758     EVT ResVT = Use->getValueType(0);
9759     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9760     const TargetRegisterClass *ArgRC =
9761         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9762     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9763       return false;
9764
9765     // At this point, we know that we perform a cross-register-bank copy.
9766     // Check if it is expensive.
9767     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9768     // Assume bitcasts are cheap, unless both register classes do not
9769     // explicitly share a common sub class.
9770     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9771       return false;
9772
9773     // Check if it will be merged with the load.
9774     // 1. Check the alignment constraint.
9775     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9776         ResVT.getTypeForEVT(*DAG->getContext()));
9777
9778     if (RequiredAlignment > getAlignment())
9779       return false;
9780
9781     // 2. Check that the load is a legal operation for that type.
9782     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9783       return false;
9784
9785     // 3. Check that we do not have a zext in the way.
9786     if (Inst->getValueType(0) != getLoadedType())
9787       return false;
9788
9789     return true;
9790   }
9791 };
9792 }
9793
9794 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9795 /// \p UsedBits looks like 0..0 1..1 0..0.
9796 static bool areUsedBitsDense(const APInt &UsedBits) {
9797   // If all the bits are one, this is dense!
9798   if (UsedBits.isAllOnesValue())
9799     return true;
9800
9801   // Get rid of the unused bits on the right.
9802   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9803   // Get rid of the unused bits on the left.
9804   if (NarrowedUsedBits.countLeadingZeros())
9805     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9806   // Check that the chunk of bits is completely used.
9807   return NarrowedUsedBits.isAllOnesValue();
9808 }
9809
9810 /// \brief Check whether or not \p First and \p Second are next to each other
9811 /// in memory. This means that there is no hole between the bits loaded
9812 /// by \p First and the bits loaded by \p Second.
9813 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9814                                      const LoadedSlice &Second) {
9815   assert(First.Origin == Second.Origin && First.Origin &&
9816          "Unable to match different memory origins.");
9817   APInt UsedBits = First.getUsedBits();
9818   assert((UsedBits & Second.getUsedBits()) == 0 &&
9819          "Slices are not supposed to overlap.");
9820   UsedBits |= Second.getUsedBits();
9821   return areUsedBitsDense(UsedBits);
9822 }
9823
9824 /// \brief Adjust the \p GlobalLSCost according to the target
9825 /// paring capabilities and the layout of the slices.
9826 /// \pre \p GlobalLSCost should account for at least as many loads as
9827 /// there is in the slices in \p LoadedSlices.
9828 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9829                                  LoadedSlice::Cost &GlobalLSCost) {
9830   unsigned NumberOfSlices = LoadedSlices.size();
9831   // If there is less than 2 elements, no pairing is possible.
9832   if (NumberOfSlices < 2)
9833     return;
9834
9835   // Sort the slices so that elements that are likely to be next to each
9836   // other in memory are next to each other in the list.
9837   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9838             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9839     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9840     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9841   });
9842   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9843   // First (resp. Second) is the first (resp. Second) potentially candidate
9844   // to be placed in a paired load.
9845   const LoadedSlice *First = nullptr;
9846   const LoadedSlice *Second = nullptr;
9847   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9848                 // Set the beginning of the pair.
9849                                                            First = Second) {
9850
9851     Second = &LoadedSlices[CurrSlice];
9852
9853     // If First is NULL, it means we start a new pair.
9854     // Get to the next slice.
9855     if (!First)
9856       continue;
9857
9858     EVT LoadedType = First->getLoadedType();
9859
9860     // If the types of the slices are different, we cannot pair them.
9861     if (LoadedType != Second->getLoadedType())
9862       continue;
9863
9864     // Check if the target supplies paired loads for this type.
9865     unsigned RequiredAlignment = 0;
9866     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9867       // move to the next pair, this type is hopeless.
9868       Second = nullptr;
9869       continue;
9870     }
9871     // Check if we meet the alignment requirement.
9872     if (RequiredAlignment > First->getAlignment())
9873       continue;
9874
9875     // Check that both loads are next to each other in memory.
9876     if (!areSlicesNextToEachOther(*First, *Second))
9877       continue;
9878
9879     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9880     --GlobalLSCost.Loads;
9881     // Move to the next pair.
9882     Second = nullptr;
9883   }
9884 }
9885
9886 /// \brief Check the profitability of all involved LoadedSlice.
9887 /// Currently, it is considered profitable if there is exactly two
9888 /// involved slices (1) which are (2) next to each other in memory, and
9889 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9890 ///
9891 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9892 /// the elements themselves.
9893 ///
9894 /// FIXME: When the cost model will be mature enough, we can relax
9895 /// constraints (1) and (2).
9896 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9897                                 const APInt &UsedBits, bool ForCodeSize) {
9898   unsigned NumberOfSlices = LoadedSlices.size();
9899   if (StressLoadSlicing)
9900     return NumberOfSlices > 1;
9901
9902   // Check (1).
9903   if (NumberOfSlices != 2)
9904     return false;
9905
9906   // Check (2).
9907   if (!areUsedBitsDense(UsedBits))
9908     return false;
9909
9910   // Check (3).
9911   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9912   // The original code has one big load.
9913   OrigCost.Loads = 1;
9914   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9915     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9916     // Accumulate the cost of all the slices.
9917     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9918     GlobalSlicingCost += SliceCost;
9919
9920     // Account as cost in the original configuration the gain obtained
9921     // with the current slices.
9922     OrigCost.addSliceGain(LS);
9923   }
9924
9925   // If the target supports paired load, adjust the cost accordingly.
9926   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9927   return OrigCost > GlobalSlicingCost;
9928 }
9929
9930 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9931 /// operations, split it in the various pieces being extracted.
9932 ///
9933 /// This sort of thing is introduced by SROA.
9934 /// This slicing takes care not to insert overlapping loads.
9935 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9936 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9937   if (Level < AfterLegalizeDAG)
9938     return false;
9939
9940   LoadSDNode *LD = cast<LoadSDNode>(N);
9941   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9942       !LD->getValueType(0).isInteger())
9943     return false;
9944
9945   // Keep track of already used bits to detect overlapping values.
9946   // In that case, we will just abort the transformation.
9947   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9948
9949   SmallVector<LoadedSlice, 4> LoadedSlices;
9950
9951   // Check if this load is used as several smaller chunks of bits.
9952   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9953   // of computation for each trunc.
9954   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9955        UI != UIEnd; ++UI) {
9956     // Skip the uses of the chain.
9957     if (UI.getUse().getResNo() != 0)
9958       continue;
9959
9960     SDNode *User = *UI;
9961     unsigned Shift = 0;
9962
9963     // Check if this is a trunc(lshr).
9964     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9965         isa<ConstantSDNode>(User->getOperand(1))) {
9966       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9967       User = *User->use_begin();
9968     }
9969
9970     // At this point, User is a Truncate, iff we encountered, trunc or
9971     // trunc(lshr).
9972     if (User->getOpcode() != ISD::TRUNCATE)
9973       return false;
9974
9975     // The width of the type must be a power of 2 and greater than 8-bits.
9976     // Otherwise the load cannot be represented in LLVM IR.
9977     // Moreover, if we shifted with a non-8-bits multiple, the slice
9978     // will be across several bytes. We do not support that.
9979     unsigned Width = User->getValueSizeInBits(0);
9980     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9981       return 0;
9982
9983     // Build the slice for this chain of computations.
9984     LoadedSlice LS(User, LD, Shift, &DAG);
9985     APInt CurrentUsedBits = LS.getUsedBits();
9986
9987     // Check if this slice overlaps with another.
9988     if ((CurrentUsedBits & UsedBits) != 0)
9989       return false;
9990     // Update the bits used globally.
9991     UsedBits |= CurrentUsedBits;
9992
9993     // Check if the new slice would be legal.
9994     if (!LS.isLegal())
9995       return false;
9996
9997     // Record the slice.
9998     LoadedSlices.push_back(LS);
9999   }
10000
10001   // Abort slicing if it does not seem to be profitable.
10002   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10003     return false;
10004
10005   ++SlicedLoads;
10006
10007   // Rewrite each chain to use an independent load.
10008   // By construction, each chain can be represented by a unique load.
10009
10010   // Prepare the argument for the new token factor for all the slices.
10011   SmallVector<SDValue, 8> ArgChains;
10012   for (SmallVectorImpl<LoadedSlice>::const_iterator
10013            LSIt = LoadedSlices.begin(),
10014            LSItEnd = LoadedSlices.end();
10015        LSIt != LSItEnd; ++LSIt) {
10016     SDValue SliceInst = LSIt->loadSlice();
10017     CombineTo(LSIt->Inst, SliceInst, true);
10018     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10019       SliceInst = SliceInst.getOperand(0);
10020     assert(SliceInst->getOpcode() == ISD::LOAD &&
10021            "It takes more than a zext to get to the loaded slice!!");
10022     ArgChains.push_back(SliceInst.getValue(1));
10023   }
10024
10025   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10026                               ArgChains);
10027   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10028   return true;
10029 }
10030
10031 /// Check to see if V is (and load (ptr), imm), where the load is having
10032 /// specific bytes cleared out.  If so, return the byte size being masked out
10033 /// and the shift amount.
10034 static std::pair<unsigned, unsigned>
10035 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10036   std::pair<unsigned, unsigned> Result(0, 0);
10037
10038   // Check for the structure we're looking for.
10039   if (V->getOpcode() != ISD::AND ||
10040       !isa<ConstantSDNode>(V->getOperand(1)) ||
10041       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10042     return Result;
10043
10044   // Check the chain and pointer.
10045   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10046   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10047
10048   // The store should be chained directly to the load or be an operand of a
10049   // tokenfactor.
10050   if (LD == Chain.getNode())
10051     ; // ok.
10052   else if (Chain->getOpcode() != ISD::TokenFactor)
10053     return Result; // Fail.
10054   else {
10055     bool isOk = false;
10056     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10057       if (Chain->getOperand(i).getNode() == LD) {
10058         isOk = true;
10059         break;
10060       }
10061     if (!isOk) return Result;
10062   }
10063
10064   // This only handles simple types.
10065   if (V.getValueType() != MVT::i16 &&
10066       V.getValueType() != MVT::i32 &&
10067       V.getValueType() != MVT::i64)
10068     return Result;
10069
10070   // Check the constant mask.  Invert it so that the bits being masked out are
10071   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10072   // follow the sign bit for uniformity.
10073   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10074   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10075   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10076   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10077   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10078   if (NotMaskLZ == 64) return Result;  // All zero mask.
10079
10080   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10081   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10082     return Result;
10083
10084   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10085   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10086     NotMaskLZ -= 64-V.getValueSizeInBits();
10087
10088   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10089   switch (MaskedBytes) {
10090   case 1:
10091   case 2:
10092   case 4: break;
10093   default: return Result; // All one mask, or 5-byte mask.
10094   }
10095
10096   // Verify that the first bit starts at a multiple of mask so that the access
10097   // is aligned the same as the access width.
10098   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10099
10100   Result.first = MaskedBytes;
10101   Result.second = NotMaskTZ/8;
10102   return Result;
10103 }
10104
10105
10106 /// Check to see if IVal is something that provides a value as specified by
10107 /// MaskInfo. If so, replace the specified store with a narrower store of
10108 /// truncated IVal.
10109 static SDNode *
10110 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10111                                 SDValue IVal, StoreSDNode *St,
10112                                 DAGCombiner *DC) {
10113   unsigned NumBytes = MaskInfo.first;
10114   unsigned ByteShift = MaskInfo.second;
10115   SelectionDAG &DAG = DC->getDAG();
10116
10117   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10118   // that uses this.  If not, this is not a replacement.
10119   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10120                                   ByteShift*8, (ByteShift+NumBytes)*8);
10121   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10122
10123   // Check that it is legal on the target to do this.  It is legal if the new
10124   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10125   // legalization.
10126   MVT VT = MVT::getIntegerVT(NumBytes*8);
10127   if (!DC->isTypeLegal(VT))
10128     return nullptr;
10129
10130   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10131   // shifted by ByteShift and truncated down to NumBytes.
10132   if (ByteShift) {
10133     SDLoc DL(IVal);
10134     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10135                        DAG.getConstant(ByteShift*8, DL,
10136                                     DC->getShiftAmountTy(IVal.getValueType())));
10137   }
10138
10139   // Figure out the offset for the store and the alignment of the access.
10140   unsigned StOffset;
10141   unsigned NewAlign = St->getAlignment();
10142
10143   if (DAG.getTargetLoweringInfo().isLittleEndian())
10144     StOffset = ByteShift;
10145   else
10146     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10147
10148   SDValue Ptr = St->getBasePtr();
10149   if (StOffset) {
10150     SDLoc DL(IVal);
10151     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10152                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10153     NewAlign = MinAlign(NewAlign, StOffset);
10154   }
10155
10156   // Truncate down to the new size.
10157   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10158
10159   ++OpsNarrowed;
10160   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10161                       St->getPointerInfo().getWithOffset(StOffset),
10162                       false, false, NewAlign).getNode();
10163 }
10164
10165
10166 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10167 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10168 /// narrowing the load and store if it would end up being a win for performance
10169 /// or code size.
10170 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10171   StoreSDNode *ST  = cast<StoreSDNode>(N);
10172   if (ST->isVolatile())
10173     return SDValue();
10174
10175   SDValue Chain = ST->getChain();
10176   SDValue Value = ST->getValue();
10177   SDValue Ptr   = ST->getBasePtr();
10178   EVT VT = Value.getValueType();
10179
10180   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10181     return SDValue();
10182
10183   unsigned Opc = Value.getOpcode();
10184
10185   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10186   // is a byte mask indicating a consecutive number of bytes, check to see if
10187   // Y is known to provide just those bytes.  If so, we try to replace the
10188   // load + replace + store sequence with a single (narrower) store, which makes
10189   // the load dead.
10190   if (Opc == ISD::OR) {
10191     std::pair<unsigned, unsigned> MaskedLoad;
10192     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10193     if (MaskedLoad.first)
10194       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10195                                                   Value.getOperand(1), ST,this))
10196         return SDValue(NewST, 0);
10197
10198     // Or is commutative, so try swapping X and Y.
10199     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10200     if (MaskedLoad.first)
10201       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10202                                                   Value.getOperand(0), ST,this))
10203         return SDValue(NewST, 0);
10204   }
10205
10206   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10207       Value.getOperand(1).getOpcode() != ISD::Constant)
10208     return SDValue();
10209
10210   SDValue N0 = Value.getOperand(0);
10211   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10212       Chain == SDValue(N0.getNode(), 1)) {
10213     LoadSDNode *LD = cast<LoadSDNode>(N0);
10214     if (LD->getBasePtr() != Ptr ||
10215         LD->getPointerInfo().getAddrSpace() !=
10216         ST->getPointerInfo().getAddrSpace())
10217       return SDValue();
10218
10219     // Find the type to narrow it the load / op / store to.
10220     SDValue N1 = Value.getOperand(1);
10221     unsigned BitWidth = N1.getValueSizeInBits();
10222     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10223     if (Opc == ISD::AND)
10224       Imm ^= APInt::getAllOnesValue(BitWidth);
10225     if (Imm == 0 || Imm.isAllOnesValue())
10226       return SDValue();
10227     unsigned ShAmt = Imm.countTrailingZeros();
10228     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10229     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10230     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10231     // The narrowing should be profitable, the load/store operation should be
10232     // legal (or custom) and the store size should be equal to the NewVT width.
10233     while (NewBW < BitWidth &&
10234            (NewVT.getStoreSizeInBits() != NewBW ||
10235             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10236             !TLI.isNarrowingProfitable(VT, NewVT))) {
10237       NewBW = NextPowerOf2(NewBW);
10238       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10239     }
10240     if (NewBW >= BitWidth)
10241       return SDValue();
10242
10243     // If the lsb changed does not start at the type bitwidth boundary,
10244     // start at the previous one.
10245     if (ShAmt % NewBW)
10246       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10247     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10248                                    std::min(BitWidth, ShAmt + NewBW));
10249     if ((Imm & Mask) == Imm) {
10250       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10251       if (Opc == ISD::AND)
10252         NewImm ^= APInt::getAllOnesValue(NewBW);
10253       uint64_t PtrOff = ShAmt / 8;
10254       // For big endian targets, we need to adjust the offset to the pointer to
10255       // load the correct bytes.
10256       if (TLI.isBigEndian())
10257         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10258
10259       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10260       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10261       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10262         return SDValue();
10263
10264       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10265                                    Ptr.getValueType(), Ptr,
10266                                    DAG.getConstant(PtrOff, SDLoc(LD),
10267                                                    Ptr.getValueType()));
10268       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10269                                   LD->getChain(), NewPtr,
10270                                   LD->getPointerInfo().getWithOffset(PtrOff),
10271                                   LD->isVolatile(), LD->isNonTemporal(),
10272                                   LD->isInvariant(), NewAlign,
10273                                   LD->getAAInfo());
10274       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10275                                    DAG.getConstant(NewImm, SDLoc(Value),
10276                                                    NewVT));
10277       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10278                                    NewVal, NewPtr,
10279                                    ST->getPointerInfo().getWithOffset(PtrOff),
10280                                    false, false, NewAlign);
10281
10282       AddToWorklist(NewPtr.getNode());
10283       AddToWorklist(NewLD.getNode());
10284       AddToWorklist(NewVal.getNode());
10285       WorklistRemover DeadNodes(*this);
10286       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10287       ++OpsNarrowed;
10288       return NewST;
10289     }
10290   }
10291
10292   return SDValue();
10293 }
10294
10295 /// For a given floating point load / store pair, if the load value isn't used
10296 /// by any other operations, then consider transforming the pair to integer
10297 /// load / store operations if the target deems the transformation profitable.
10298 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10299   StoreSDNode *ST  = cast<StoreSDNode>(N);
10300   SDValue Chain = ST->getChain();
10301   SDValue Value = ST->getValue();
10302   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10303       Value.hasOneUse() &&
10304       Chain == SDValue(Value.getNode(), 1)) {
10305     LoadSDNode *LD = cast<LoadSDNode>(Value);
10306     EVT VT = LD->getMemoryVT();
10307     if (!VT.isFloatingPoint() ||
10308         VT != ST->getMemoryVT() ||
10309         LD->isNonTemporal() ||
10310         ST->isNonTemporal() ||
10311         LD->getPointerInfo().getAddrSpace() != 0 ||
10312         ST->getPointerInfo().getAddrSpace() != 0)
10313       return SDValue();
10314
10315     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10316     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10317         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10318         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10319         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10320       return SDValue();
10321
10322     unsigned LDAlign = LD->getAlignment();
10323     unsigned STAlign = ST->getAlignment();
10324     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10325     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10326     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10327       return SDValue();
10328
10329     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10330                                 LD->getChain(), LD->getBasePtr(),
10331                                 LD->getPointerInfo(),
10332                                 false, false, false, LDAlign);
10333
10334     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10335                                  NewLD, ST->getBasePtr(),
10336                                  ST->getPointerInfo(),
10337                                  false, false, STAlign);
10338
10339     AddToWorklist(NewLD.getNode());
10340     AddToWorklist(NewST.getNode());
10341     WorklistRemover DeadNodes(*this);
10342     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10343     ++LdStFP2Int;
10344     return NewST;
10345   }
10346
10347   return SDValue();
10348 }
10349
10350 namespace {
10351 /// Helper struct to parse and store a memory address as base + index + offset.
10352 /// We ignore sign extensions when it is safe to do so.
10353 /// The following two expressions are not equivalent. To differentiate we need
10354 /// to store whether there was a sign extension involved in the index
10355 /// computation.
10356 ///  (load (i64 add (i64 copyfromreg %c)
10357 ///                 (i64 signextend (add (i8 load %index)
10358 ///                                      (i8 1))))
10359 /// vs
10360 ///
10361 /// (load (i64 add (i64 copyfromreg %c)
10362 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10363 ///                                         (i32 1)))))
10364 struct BaseIndexOffset {
10365   SDValue Base;
10366   SDValue Index;
10367   int64_t Offset;
10368   bool IsIndexSignExt;
10369
10370   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10371
10372   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10373                   bool IsIndexSignExt) :
10374     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10375
10376   bool equalBaseIndex(const BaseIndexOffset &Other) {
10377     return Other.Base == Base && Other.Index == Index &&
10378       Other.IsIndexSignExt == IsIndexSignExt;
10379   }
10380
10381   /// Parses tree in Ptr for base, index, offset addresses.
10382   static BaseIndexOffset match(SDValue Ptr) {
10383     bool IsIndexSignExt = false;
10384
10385     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10386     // instruction, then it could be just the BASE or everything else we don't
10387     // know how to handle. Just use Ptr as BASE and give up.
10388     if (Ptr->getOpcode() != ISD::ADD)
10389       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10390
10391     // We know that we have at least an ADD instruction. Try to pattern match
10392     // the simple case of BASE + OFFSET.
10393     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10394       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10395       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10396                               IsIndexSignExt);
10397     }
10398
10399     // Inside a loop the current BASE pointer is calculated using an ADD and a
10400     // MUL instruction. In this case Ptr is the actual BASE pointer.
10401     // (i64 add (i64 %array_ptr)
10402     //          (i64 mul (i64 %induction_var)
10403     //                   (i64 %element_size)))
10404     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10405       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10406
10407     // Look at Base + Index + Offset cases.
10408     SDValue Base = Ptr->getOperand(0);
10409     SDValue IndexOffset = Ptr->getOperand(1);
10410
10411     // Skip signextends.
10412     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10413       IndexOffset = IndexOffset->getOperand(0);
10414       IsIndexSignExt = true;
10415     }
10416
10417     // Either the case of Base + Index (no offset) or something else.
10418     if (IndexOffset->getOpcode() != ISD::ADD)
10419       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10420
10421     // Now we have the case of Base + Index + offset.
10422     SDValue Index = IndexOffset->getOperand(0);
10423     SDValue Offset = IndexOffset->getOperand(1);
10424
10425     if (!isa<ConstantSDNode>(Offset))
10426       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10427
10428     // Ignore signextends.
10429     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10430       Index = Index->getOperand(0);
10431       IsIndexSignExt = true;
10432     } else IsIndexSignExt = false;
10433
10434     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10435     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10436   }
10437 };
10438 } // namespace
10439
10440 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10441                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10442                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10443   // Make sure we have something to merge.
10444   if (NumElem < 2)
10445     return false;
10446
10447   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10448   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10449   unsigned LatestNodeUsed = 0;
10450
10451   for (unsigned i=0; i < NumElem; ++i) {
10452     // Find a chain for the new wide-store operand. Notice that some
10453     // of the store nodes that we found may not be selected for inclusion
10454     // in the wide store. The chain we use needs to be the chain of the
10455     // latest store node which is *used* and replaced by the wide store.
10456     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10457       LatestNodeUsed = i;
10458   }
10459
10460   // The latest Node in the DAG.
10461   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10462   SDLoc DL(StoreNodes[0].MemNode);
10463
10464   SDValue StoredVal;
10465   if (UseVector) {
10466     // Find a legal type for the vector store.
10467     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10468     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10469     if (IsConstantSrc) {
10470       // A vector store with a constant source implies that the constant is
10471       // zero; we only handle merging stores of constant zeros because the zero
10472       // can be materialized without a load.
10473       // It may be beneficial to loosen this restriction to allow non-zero
10474       // store merging.
10475       StoredVal = DAG.getConstant(0, DL, Ty);
10476     } else {
10477       SmallVector<SDValue, 8> Ops;
10478       for (unsigned i = 0; i < NumElem ; ++i) {
10479         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10480         SDValue Val = St->getValue();
10481         // All of the operands of a BUILD_VECTOR must have the same type.
10482         if (Val.getValueType() != MemVT)
10483           return false;
10484         Ops.push_back(Val);
10485       }
10486
10487       // Build the extracted vector elements back into a vector.
10488       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10489     }
10490   } else {
10491     // We should always use a vector store when merging extracted vector
10492     // elements, so this path implies a store of constants.
10493     assert(IsConstantSrc && "Merged vector elements should use vector store");
10494
10495     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10496     APInt StoreInt(StoreBW, 0);
10497
10498     // Construct a single integer constant which is made of the smaller
10499     // constant inputs.
10500     bool IsLE = TLI.isLittleEndian();
10501     for (unsigned i = 0; i < NumElem ; ++i) {
10502       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10503       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10504       SDValue Val = St->getValue();
10505       StoreInt <<= ElementSizeBytes*8;
10506       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10507         StoreInt |= C->getAPIntValue().zext(StoreBW);
10508       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10509         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10510       } else {
10511         llvm_unreachable("Invalid constant element type");
10512       }
10513     }
10514
10515     // Create the new Load and Store operations.
10516     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10517     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10518   }
10519
10520   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10521                                   FirstInChain->getBasePtr(),
10522                                   FirstInChain->getPointerInfo(),
10523                                   false, false,
10524                                   FirstInChain->getAlignment());
10525
10526   // Replace the last store with the new store
10527   CombineTo(LatestOp, NewStore);
10528   // Erase all other stores.
10529   for (unsigned i = 0; i < NumElem ; ++i) {
10530     if (StoreNodes[i].MemNode == LatestOp)
10531       continue;
10532     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10533     // ReplaceAllUsesWith will replace all uses that existed when it was
10534     // called, but graph optimizations may cause new ones to appear. For
10535     // example, the case in pr14333 looks like
10536     //
10537     //  St's chain -> St -> another store -> X
10538     //
10539     // And the only difference from St to the other store is the chain.
10540     // When we change it's chain to be St's chain they become identical,
10541     // get CSEed and the net result is that X is now a use of St.
10542     // Since we know that St is redundant, just iterate.
10543     while (!St->use_empty())
10544       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10545     deleteAndRecombine(St);
10546   }
10547
10548   return true;
10549 }
10550
10551 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10552   if (OptLevel == CodeGenOpt::None)
10553     return false;
10554
10555   EVT MemVT = St->getMemoryVT();
10556   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10557   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10558       Attribute::NoImplicitFloat);
10559
10560   // Don't merge vectors into wider inputs.
10561   if (MemVT.isVector() || !MemVT.isSimple())
10562     return false;
10563
10564   // Perform an early exit check. Do not bother looking at stored values that
10565   // are not constants, loads, or extracted vector elements.
10566   SDValue StoredVal = St->getValue();
10567   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10568   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10569                        isa<ConstantFPSDNode>(StoredVal);
10570   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10571
10572   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10573     return false;
10574
10575   // Only look at ends of store sequences.
10576   SDValue Chain = SDValue(St, 0);
10577   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10578     return false;
10579
10580   // This holds the base pointer, index, and the offset in bytes from the base
10581   // pointer.
10582   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10583
10584   // We must have a base and an offset.
10585   if (!BasePtr.Base.getNode())
10586     return false;
10587
10588   // Do not handle stores to undef base pointers.
10589   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10590     return false;
10591
10592   // Save the LoadSDNodes that we find in the chain.
10593   // We need to make sure that these nodes do not interfere with
10594   // any of the store nodes.
10595   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10596
10597   // Save the StoreSDNodes that we find in the chain.
10598   SmallVector<MemOpLink, 8> StoreNodes;
10599
10600   // Walk up the chain and look for nodes with offsets from the same
10601   // base pointer. Stop when reaching an instruction with a different kind
10602   // or instruction which has a different base pointer.
10603   unsigned Seq = 0;
10604   StoreSDNode *Index = St;
10605   while (Index) {
10606     // If the chain has more than one use, then we can't reorder the mem ops.
10607     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10608       break;
10609
10610     // Find the base pointer and offset for this memory node.
10611     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10612
10613     // Check that the base pointer is the same as the original one.
10614     if (!Ptr.equalBaseIndex(BasePtr))
10615       break;
10616
10617     // Check that the alignment is the same.
10618     if (Index->getAlignment() != St->getAlignment())
10619       break;
10620
10621     // The memory operands must not be volatile.
10622     if (Index->isVolatile() || Index->isIndexed())
10623       break;
10624
10625     // No truncation.
10626     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10627       if (St->isTruncatingStore())
10628         break;
10629
10630     // The stored memory type must be the same.
10631     if (Index->getMemoryVT() != MemVT)
10632       break;
10633
10634     // We do not allow unaligned stores because we want to prevent overriding
10635     // stores.
10636     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10637       break;
10638
10639     // We found a potential memory operand to merge.
10640     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10641
10642     // Find the next memory operand in the chain. If the next operand in the
10643     // chain is a store then move up and continue the scan with the next
10644     // memory operand. If the next operand is a load save it and use alias
10645     // information to check if it interferes with anything.
10646     SDNode *NextInChain = Index->getChain().getNode();
10647     while (1) {
10648       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10649         // We found a store node. Use it for the next iteration.
10650         Index = STn;
10651         break;
10652       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10653         if (Ldn->isVolatile()) {
10654           Index = nullptr;
10655           break;
10656         }
10657
10658         // Save the load node for later. Continue the scan.
10659         AliasLoadNodes.push_back(Ldn);
10660         NextInChain = Ldn->getChain().getNode();
10661         continue;
10662       } else {
10663         Index = nullptr;
10664         break;
10665       }
10666     }
10667   }
10668
10669   // Check if there is anything to merge.
10670   if (StoreNodes.size() < 2)
10671     return false;
10672
10673   // Sort the memory operands according to their distance from the base pointer.
10674   std::sort(StoreNodes.begin(), StoreNodes.end(),
10675             [](MemOpLink LHS, MemOpLink RHS) {
10676     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10677            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10678             LHS.SequenceNum > RHS.SequenceNum);
10679   });
10680
10681   // Scan the memory operations on the chain and find the first non-consecutive
10682   // store memory address.
10683   unsigned LastConsecutiveStore = 0;
10684   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10685   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10686
10687     // Check that the addresses are consecutive starting from the second
10688     // element in the list of stores.
10689     if (i > 0) {
10690       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10691       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10692         break;
10693     }
10694
10695     bool Alias = false;
10696     // Check if this store interferes with any of the loads that we found.
10697     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10698       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10699         Alias = true;
10700         break;
10701       }
10702     // We found a load that alias with this store. Stop the sequence.
10703     if (Alias)
10704       break;
10705
10706     // Mark this node as useful.
10707     LastConsecutiveStore = i;
10708   }
10709
10710   // The node with the lowest store address.
10711   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10712
10713   // Store the constants into memory as one consecutive store.
10714   if (IsConstantSrc) {
10715     unsigned LastLegalType = 0;
10716     unsigned LastLegalVectorType = 0;
10717     bool NonZero = false;
10718     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10719       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10720       SDValue StoredVal = St->getValue();
10721
10722       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10723         NonZero |= !C->isNullValue();
10724       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10725         NonZero |= !C->getConstantFPValue()->isNullValue();
10726       } else {
10727         // Non-constant.
10728         break;
10729       }
10730
10731       // Find a legal type for the constant store.
10732       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10733       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10734       if (TLI.isTypeLegal(StoreTy))
10735         LastLegalType = i+1;
10736       // Or check whether a truncstore is legal.
10737       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10738                TargetLowering::TypePromoteInteger) {
10739         EVT LegalizedStoredValueTy =
10740           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10741         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10742           LastLegalType = i+1;
10743       }
10744
10745       // Find a legal type for the vector store.
10746       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10747       if (TLI.isTypeLegal(Ty))
10748         LastLegalVectorType = i + 1;
10749     }
10750
10751     // We only use vectors if the constant is known to be zero and the
10752     // function is not marked with the noimplicitfloat attribute.
10753     if (NonZero || NoVectors)
10754       LastLegalVectorType = 0;
10755
10756     // Check if we found a legal integer type to store.
10757     if (LastLegalType == 0 && LastLegalVectorType == 0)
10758       return false;
10759
10760     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10761     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10762
10763     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10764                                            true, UseVector);
10765   }
10766
10767   // When extracting multiple vector elements, try to store them
10768   // in one vector store rather than a sequence of scalar stores.
10769   if (IsExtractVecEltSrc) {
10770     unsigned NumElem = 0;
10771     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10772       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10773       SDValue StoredVal = St->getValue();
10774       // This restriction could be loosened.
10775       // Bail out if any stored values are not elements extracted from a vector.
10776       // It should be possible to handle mixed sources, but load sources need
10777       // more careful handling (see the block of code below that handles
10778       // consecutive loads).
10779       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10780         return false;
10781
10782       // Find a legal type for the vector store.
10783       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10784       if (TLI.isTypeLegal(Ty))
10785         NumElem = i + 1;
10786     }
10787
10788     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10789                                            false, true);
10790   }
10791
10792   // Below we handle the case of multiple consecutive stores that
10793   // come from multiple consecutive loads. We merge them into a single
10794   // wide load and a single wide store.
10795
10796   // Look for load nodes which are used by the stored values.
10797   SmallVector<MemOpLink, 8> LoadNodes;
10798
10799   // Find acceptable loads. Loads need to have the same chain (token factor),
10800   // must not be zext, volatile, indexed, and they must be consecutive.
10801   BaseIndexOffset LdBasePtr;
10802   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10803     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10804     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10805     if (!Ld) break;
10806
10807     // Loads must only have one use.
10808     if (!Ld->hasNUsesOfValue(1, 0))
10809       break;
10810
10811     // Check that the alignment is the same as the stores.
10812     if (Ld->getAlignment() != St->getAlignment())
10813       break;
10814
10815     // The memory operands must not be volatile.
10816     if (Ld->isVolatile() || Ld->isIndexed())
10817       break;
10818
10819     // We do not accept ext loads.
10820     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10821       break;
10822
10823     // The stored memory type must be the same.
10824     if (Ld->getMemoryVT() != MemVT)
10825       break;
10826
10827     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10828     // If this is not the first ptr that we check.
10829     if (LdBasePtr.Base.getNode()) {
10830       // The base ptr must be the same.
10831       if (!LdPtr.equalBaseIndex(LdBasePtr))
10832         break;
10833     } else {
10834       // Check that all other base pointers are the same as this one.
10835       LdBasePtr = LdPtr;
10836     }
10837
10838     // We found a potential memory operand to merge.
10839     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10840   }
10841
10842   if (LoadNodes.size() < 2)
10843     return false;
10844
10845   // If we have load/store pair instructions and we only have two values,
10846   // don't bother.
10847   unsigned RequiredAlignment;
10848   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10849       St->getAlignment() >= RequiredAlignment)
10850     return false;
10851
10852   // Scan the memory operations on the chain and find the first non-consecutive
10853   // load memory address. These variables hold the index in the store node
10854   // array.
10855   unsigned LastConsecutiveLoad = 0;
10856   // This variable refers to the size and not index in the array.
10857   unsigned LastLegalVectorType = 0;
10858   unsigned LastLegalIntegerType = 0;
10859   StartAddress = LoadNodes[0].OffsetFromBase;
10860   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10861   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10862     // All loads much share the same chain.
10863     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10864       break;
10865
10866     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10867     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10868       break;
10869     LastConsecutiveLoad = i;
10870
10871     // Find a legal type for the vector store.
10872     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10873     if (TLI.isTypeLegal(StoreTy))
10874       LastLegalVectorType = i + 1;
10875
10876     // Find a legal type for the integer store.
10877     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10878     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10879     if (TLI.isTypeLegal(StoreTy))
10880       LastLegalIntegerType = i + 1;
10881     // Or check whether a truncstore and extload is legal.
10882     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10883              TargetLowering::TypePromoteInteger) {
10884       EVT LegalizedStoredValueTy =
10885         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10886       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10887           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10888           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10889           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10890         LastLegalIntegerType = i+1;
10891     }
10892   }
10893
10894   // Only use vector types if the vector type is larger than the integer type.
10895   // If they are the same, use integers.
10896   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10897   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10898
10899   // We add +1 here because the LastXXX variables refer to location while
10900   // the NumElem refers to array/index size.
10901   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10902   NumElem = std::min(LastLegalType, NumElem);
10903
10904   if (NumElem < 2)
10905     return false;
10906
10907   // The latest Node in the DAG.
10908   unsigned LatestNodeUsed = 0;
10909   for (unsigned i=1; i<NumElem; ++i) {
10910     // Find a chain for the new wide-store operand. Notice that some
10911     // of the store nodes that we found may not be selected for inclusion
10912     // in the wide store. The chain we use needs to be the chain of the
10913     // latest store node which is *used* and replaced by the wide store.
10914     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10915       LatestNodeUsed = i;
10916   }
10917
10918   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10919
10920   // Find if it is better to use vectors or integers to load and store
10921   // to memory.
10922   EVT JointMemOpVT;
10923   if (UseVectorTy) {
10924     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10925   } else {
10926     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10927     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10928   }
10929
10930   SDLoc LoadDL(LoadNodes[0].MemNode);
10931   SDLoc StoreDL(StoreNodes[0].MemNode);
10932
10933   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10934   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10935                                 FirstLoad->getChain(),
10936                                 FirstLoad->getBasePtr(),
10937                                 FirstLoad->getPointerInfo(),
10938                                 false, false, false,
10939                                 FirstLoad->getAlignment());
10940
10941   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10942                                   FirstInChain->getBasePtr(),
10943                                   FirstInChain->getPointerInfo(), false, false,
10944                                   FirstInChain->getAlignment());
10945
10946   // Replace one of the loads with the new load.
10947   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10948   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10949                                 SDValue(NewLoad.getNode(), 1));
10950
10951   // Remove the rest of the load chains.
10952   for (unsigned i = 1; i < NumElem ; ++i) {
10953     // Replace all chain users of the old load nodes with the chain of the new
10954     // load node.
10955     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10956     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10957   }
10958
10959   // Replace the last store with the new store.
10960   CombineTo(LatestOp, NewStore);
10961   // Erase all other stores.
10962   for (unsigned i = 0; i < NumElem ; ++i) {
10963     // Remove all Store nodes.
10964     if (StoreNodes[i].MemNode == LatestOp)
10965       continue;
10966     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10967     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10968     deleteAndRecombine(St);
10969   }
10970
10971   return true;
10972 }
10973
10974 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10975   StoreSDNode *ST  = cast<StoreSDNode>(N);
10976   SDValue Chain = ST->getChain();
10977   SDValue Value = ST->getValue();
10978   SDValue Ptr   = ST->getBasePtr();
10979
10980   // If this is a store of a bit convert, store the input value if the
10981   // resultant store does not need a higher alignment than the original.
10982   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10983       ST->isUnindexed()) {
10984     unsigned OrigAlign = ST->getAlignment();
10985     EVT SVT = Value.getOperand(0).getValueType();
10986     unsigned Align = TLI.getDataLayout()->
10987       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10988     if (Align <= OrigAlign &&
10989         ((!LegalOperations && !ST->isVolatile()) ||
10990          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10991       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10992                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10993                           ST->isNonTemporal(), OrigAlign,
10994                           ST->getAAInfo());
10995   }
10996
10997   // Turn 'store undef, Ptr' -> nothing.
10998   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10999     return Chain;
11000
11001   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11002   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11003     // NOTE: If the original store is volatile, this transform must not increase
11004     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11005     // processor operation but an i64 (which is not legal) requires two.  So the
11006     // transform should not be done in this case.
11007     if (Value.getOpcode() != ISD::TargetConstantFP) {
11008       SDValue Tmp;
11009       switch (CFP->getSimpleValueType(0).SimpleTy) {
11010       default: llvm_unreachable("Unknown FP type");
11011       case MVT::f16:    // We don't do this for these yet.
11012       case MVT::f80:
11013       case MVT::f128:
11014       case MVT::ppcf128:
11015         break;
11016       case MVT::f32:
11017         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11018             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11019           ;
11020           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11021                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11022                               MVT::i32);
11023           return DAG.getStore(Chain, SDLoc(N), Tmp,
11024                               Ptr, ST->getMemOperand());
11025         }
11026         break;
11027       case MVT::f64:
11028         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11029              !ST->isVolatile()) ||
11030             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11031           ;
11032           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11033                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11034           return DAG.getStore(Chain, SDLoc(N), Tmp,
11035                               Ptr, ST->getMemOperand());
11036         }
11037
11038         if (!ST->isVolatile() &&
11039             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11040           // Many FP stores are not made apparent until after legalize, e.g. for
11041           // argument passing.  Since this is so common, custom legalize the
11042           // 64-bit integer store into two 32-bit stores.
11043           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11044           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11045           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11046           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11047
11048           unsigned Alignment = ST->getAlignment();
11049           bool isVolatile = ST->isVolatile();
11050           bool isNonTemporal = ST->isNonTemporal();
11051           AAMDNodes AAInfo = ST->getAAInfo();
11052
11053           SDLoc DL(N);
11054
11055           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11056                                      Ptr, ST->getPointerInfo(),
11057                                      isVolatile, isNonTemporal,
11058                                      ST->getAlignment(), AAInfo);
11059           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11060                             DAG.getConstant(4, DL, Ptr.getValueType()));
11061           Alignment = MinAlign(Alignment, 4U);
11062           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11063                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11064                                      isVolatile, isNonTemporal,
11065                                      Alignment, AAInfo);
11066           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11067                              St0, St1);
11068         }
11069
11070         break;
11071       }
11072     }
11073   }
11074
11075   // Try to infer better alignment information than the store already has.
11076   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11077     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11078       if (Align > ST->getAlignment()) {
11079         SDValue NewStore =
11080                DAG.getTruncStore(Chain, SDLoc(N), Value,
11081                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11082                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11083                                  ST->getAAInfo());
11084         if (NewStore.getNode() != N)
11085           return CombineTo(ST, NewStore, true);
11086       }
11087     }
11088   }
11089
11090   // Try transforming a pair floating point load / store ops to integer
11091   // load / store ops.
11092   SDValue NewST = TransformFPLoadStorePair(N);
11093   if (NewST.getNode())
11094     return NewST;
11095
11096   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11097                                                   : DAG.getSubtarget().useAA();
11098 #ifndef NDEBUG
11099   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11100       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11101     UseAA = false;
11102 #endif
11103   if (UseAA && ST->isUnindexed()) {
11104     // Walk up chain skipping non-aliasing memory nodes.
11105     SDValue BetterChain = FindBetterChain(N, Chain);
11106
11107     // If there is a better chain.
11108     if (Chain != BetterChain) {
11109       SDValue ReplStore;
11110
11111       // Replace the chain to avoid dependency.
11112       if (ST->isTruncatingStore()) {
11113         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11114                                       ST->getMemoryVT(), ST->getMemOperand());
11115       } else {
11116         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11117                                  ST->getMemOperand());
11118       }
11119
11120       // Create token to keep both nodes around.
11121       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11122                                   MVT::Other, Chain, ReplStore);
11123
11124       // Make sure the new and old chains are cleaned up.
11125       AddToWorklist(Token.getNode());
11126
11127       // Don't add users to work list.
11128       return CombineTo(N, Token, false);
11129     }
11130   }
11131
11132   // Try transforming N to an indexed store.
11133   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11134     return SDValue(N, 0);
11135
11136   // FIXME: is there such a thing as a truncating indexed store?
11137   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11138       Value.getValueType().isInteger()) {
11139     // See if we can simplify the input to this truncstore with knowledge that
11140     // only the low bits are being used.  For example:
11141     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11142     SDValue Shorter =
11143       GetDemandedBits(Value,
11144                       APInt::getLowBitsSet(
11145                         Value.getValueType().getScalarType().getSizeInBits(),
11146                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11147     AddToWorklist(Value.getNode());
11148     if (Shorter.getNode())
11149       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11150                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11151
11152     // Otherwise, see if we can simplify the operation with
11153     // SimplifyDemandedBits, which only works if the value has a single use.
11154     if (SimplifyDemandedBits(Value,
11155                         APInt::getLowBitsSet(
11156                           Value.getValueType().getScalarType().getSizeInBits(),
11157                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11158       return SDValue(N, 0);
11159   }
11160
11161   // If this is a load followed by a store to the same location, then the store
11162   // is dead/noop.
11163   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11164     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11165         ST->isUnindexed() && !ST->isVolatile() &&
11166         // There can't be any side effects between the load and store, such as
11167         // a call or store.
11168         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11169       // The store is dead, remove it.
11170       return Chain;
11171     }
11172   }
11173
11174   // If this is a store followed by a store with the same value to the same
11175   // location, then the store is dead/noop.
11176   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11177     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11178         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11179         ST1->isUnindexed() && !ST1->isVolatile()) {
11180       // The store is dead, remove it.
11181       return Chain;
11182     }
11183   }
11184
11185   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11186   // truncating store.  We can do this even if this is already a truncstore.
11187   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11188       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11189       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11190                             ST->getMemoryVT())) {
11191     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11192                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11193   }
11194
11195   // Only perform this optimization before the types are legal, because we
11196   // don't want to perform this optimization on every DAGCombine invocation.
11197   if (!LegalTypes) {
11198     bool EverChanged = false;
11199
11200     do {
11201       // There can be multiple store sequences on the same chain.
11202       // Keep trying to merge store sequences until we are unable to do so
11203       // or until we merge the last store on the chain.
11204       bool Changed = MergeConsecutiveStores(ST);
11205       EverChanged |= Changed;
11206       if (!Changed) break;
11207     } while (ST->getOpcode() != ISD::DELETED_NODE);
11208
11209     if (EverChanged)
11210       return SDValue(N, 0);
11211   }
11212
11213   return ReduceLoadOpStoreWidth(N);
11214 }
11215
11216 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11217   SDValue InVec = N->getOperand(0);
11218   SDValue InVal = N->getOperand(1);
11219   SDValue EltNo = N->getOperand(2);
11220   SDLoc dl(N);
11221
11222   // If the inserted element is an UNDEF, just use the input vector.
11223   if (InVal.getOpcode() == ISD::UNDEF)
11224     return InVec;
11225
11226   EVT VT = InVec.getValueType();
11227
11228   // If we can't generate a legal BUILD_VECTOR, exit
11229   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11230     return SDValue();
11231
11232   // Check that we know which element is being inserted
11233   if (!isa<ConstantSDNode>(EltNo))
11234     return SDValue();
11235   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11236
11237   // Canonicalize insert_vector_elt dag nodes.
11238   // Example:
11239   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11240   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11241   //
11242   // Do this only if the child insert_vector node has one use; also
11243   // do this only if indices are both constants and Idx1 < Idx0.
11244   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11245       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11246     unsigned OtherElt =
11247       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11248     if (Elt < OtherElt) {
11249       // Swap nodes.
11250       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11251                                   InVec.getOperand(0), InVal, EltNo);
11252       AddToWorklist(NewOp.getNode());
11253       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11254                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11255     }
11256   }
11257
11258   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11259   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11260   // vector elements.
11261   SmallVector<SDValue, 8> Ops;
11262   // Do not combine these two vectors if the output vector will not replace
11263   // the input vector.
11264   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11265     Ops.append(InVec.getNode()->op_begin(),
11266                InVec.getNode()->op_end());
11267   } else if (InVec.getOpcode() == ISD::UNDEF) {
11268     unsigned NElts = VT.getVectorNumElements();
11269     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11270   } else {
11271     return SDValue();
11272   }
11273
11274   // Insert the element
11275   if (Elt < Ops.size()) {
11276     // All the operands of BUILD_VECTOR must have the same type;
11277     // we enforce that here.
11278     EVT OpVT = Ops[0].getValueType();
11279     if (InVal.getValueType() != OpVT)
11280       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11281                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11282                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11283     Ops[Elt] = InVal;
11284   }
11285
11286   // Return the new vector
11287   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11288 }
11289
11290 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11291     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11292   EVT ResultVT = EVE->getValueType(0);
11293   EVT VecEltVT = InVecVT.getVectorElementType();
11294   unsigned Align = OriginalLoad->getAlignment();
11295   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11296       VecEltVT.getTypeForEVT(*DAG.getContext()));
11297
11298   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11299     return SDValue();
11300
11301   Align = NewAlign;
11302
11303   SDValue NewPtr = OriginalLoad->getBasePtr();
11304   SDValue Offset;
11305   EVT PtrType = NewPtr.getValueType();
11306   MachinePointerInfo MPI;
11307   SDLoc DL(EVE);
11308   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11309     int Elt = ConstEltNo->getZExtValue();
11310     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11311     if (TLI.isBigEndian())
11312       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11313     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11314     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11315   } else {
11316     Offset = DAG.getNode(
11317         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11318         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11319     if (TLI.isBigEndian())
11320       Offset = DAG.getNode(
11321           ISD::SUB, DL, EltNo.getValueType(),
11322           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11323           Offset);
11324     MPI = OriginalLoad->getPointerInfo();
11325   }
11326   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11327
11328   // The replacement we need to do here is a little tricky: we need to
11329   // replace an extractelement of a load with a load.
11330   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11331   // Note that this replacement assumes that the extractvalue is the only
11332   // use of the load; that's okay because we don't want to perform this
11333   // transformation in other cases anyway.
11334   SDValue Load;
11335   SDValue Chain;
11336   if (ResultVT.bitsGT(VecEltVT)) {
11337     // If the result type of vextract is wider than the load, then issue an
11338     // extending load instead.
11339     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11340                                                   VecEltVT)
11341                                    ? ISD::ZEXTLOAD
11342                                    : ISD::EXTLOAD;
11343     Load = DAG.getExtLoad(
11344         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11345         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11346         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11347     Chain = Load.getValue(1);
11348   } else {
11349     Load = DAG.getLoad(
11350         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11351         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11352         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11353     Chain = Load.getValue(1);
11354     if (ResultVT.bitsLT(VecEltVT))
11355       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11356     else
11357       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11358   }
11359   WorklistRemover DeadNodes(*this);
11360   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11361   SDValue To[] = { Load, Chain };
11362   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11363   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11364   // worklist explicitly as well.
11365   AddToWorklist(Load.getNode());
11366   AddUsersToWorklist(Load.getNode()); // Add users too
11367   // Make sure to revisit this node to clean it up; it will usually be dead.
11368   AddToWorklist(EVE);
11369   ++OpsNarrowed;
11370   return SDValue(EVE, 0);
11371 }
11372
11373 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11374   // (vextract (scalar_to_vector val, 0) -> val
11375   SDValue InVec = N->getOperand(0);
11376   EVT VT = InVec.getValueType();
11377   EVT NVT = N->getValueType(0);
11378
11379   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11380     // Check if the result type doesn't match the inserted element type. A
11381     // SCALAR_TO_VECTOR may truncate the inserted element and the
11382     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11383     SDValue InOp = InVec.getOperand(0);
11384     if (InOp.getValueType() != NVT) {
11385       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11386       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11387     }
11388     return InOp;
11389   }
11390
11391   SDValue EltNo = N->getOperand(1);
11392   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11393
11394   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11395   // We only perform this optimization before the op legalization phase because
11396   // we may introduce new vector instructions which are not backed by TD
11397   // patterns. For example on AVX, extracting elements from a wide vector
11398   // without using extract_subvector. However, if we can find an underlying
11399   // scalar value, then we can always use that.
11400   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11401       && ConstEltNo) {
11402     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11403     int NumElem = VT.getVectorNumElements();
11404     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11405     // Find the new index to extract from.
11406     int OrigElt = SVOp->getMaskElt(Elt);
11407
11408     // Extracting an undef index is undef.
11409     if (OrigElt == -1)
11410       return DAG.getUNDEF(NVT);
11411
11412     // Select the right vector half to extract from.
11413     SDValue SVInVec;
11414     if (OrigElt < NumElem) {
11415       SVInVec = InVec->getOperand(0);
11416     } else {
11417       SVInVec = InVec->getOperand(1);
11418       OrigElt -= NumElem;
11419     }
11420
11421     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11422       SDValue InOp = SVInVec.getOperand(OrigElt);
11423       if (InOp.getValueType() != NVT) {
11424         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11425         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11426       }
11427
11428       return InOp;
11429     }
11430
11431     // FIXME: We should handle recursing on other vector shuffles and
11432     // scalar_to_vector here as well.
11433
11434     if (!LegalOperations) {
11435       EVT IndexTy = TLI.getVectorIdxTy();
11436       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11437                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11438     }
11439   }
11440
11441   bool BCNumEltsChanged = false;
11442   EVT ExtVT = VT.getVectorElementType();
11443   EVT LVT = ExtVT;
11444
11445   // If the result of load has to be truncated, then it's not necessarily
11446   // profitable.
11447   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11448     return SDValue();
11449
11450   if (InVec.getOpcode() == ISD::BITCAST) {
11451     // Don't duplicate a load with other uses.
11452     if (!InVec.hasOneUse())
11453       return SDValue();
11454
11455     EVT BCVT = InVec.getOperand(0).getValueType();
11456     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11457       return SDValue();
11458     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11459       BCNumEltsChanged = true;
11460     InVec = InVec.getOperand(0);
11461     ExtVT = BCVT.getVectorElementType();
11462   }
11463
11464   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11465   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11466       ISD::isNormalLoad(InVec.getNode()) &&
11467       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11468     SDValue Index = N->getOperand(1);
11469     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11470       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11471                                                            OrigLoad);
11472   }
11473
11474   // Perform only after legalization to ensure build_vector / vector_shuffle
11475   // optimizations have already been done.
11476   if (!LegalOperations) return SDValue();
11477
11478   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11479   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11480   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11481
11482   if (ConstEltNo) {
11483     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11484
11485     LoadSDNode *LN0 = nullptr;
11486     const ShuffleVectorSDNode *SVN = nullptr;
11487     if (ISD::isNormalLoad(InVec.getNode())) {
11488       LN0 = cast<LoadSDNode>(InVec);
11489     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11490                InVec.getOperand(0).getValueType() == ExtVT &&
11491                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11492       // Don't duplicate a load with other uses.
11493       if (!InVec.hasOneUse())
11494         return SDValue();
11495
11496       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11497     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11498       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11499       // =>
11500       // (load $addr+1*size)
11501
11502       // Don't duplicate a load with other uses.
11503       if (!InVec.hasOneUse())
11504         return SDValue();
11505
11506       // If the bit convert changed the number of elements, it is unsafe
11507       // to examine the mask.
11508       if (BCNumEltsChanged)
11509         return SDValue();
11510
11511       // Select the input vector, guarding against out of range extract vector.
11512       unsigned NumElems = VT.getVectorNumElements();
11513       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11514       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11515
11516       if (InVec.getOpcode() == ISD::BITCAST) {
11517         // Don't duplicate a load with other uses.
11518         if (!InVec.hasOneUse())
11519           return SDValue();
11520
11521         InVec = InVec.getOperand(0);
11522       }
11523       if (ISD::isNormalLoad(InVec.getNode())) {
11524         LN0 = cast<LoadSDNode>(InVec);
11525         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11526         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11527       }
11528     }
11529
11530     // Make sure we found a non-volatile load and the extractelement is
11531     // the only use.
11532     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11533       return SDValue();
11534
11535     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11536     if (Elt == -1)
11537       return DAG.getUNDEF(LVT);
11538
11539     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11540   }
11541
11542   return SDValue();
11543 }
11544
11545 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11546 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11547   // We perform this optimization post type-legalization because
11548   // the type-legalizer often scalarizes integer-promoted vectors.
11549   // Performing this optimization before may create bit-casts which
11550   // will be type-legalized to complex code sequences.
11551   // We perform this optimization only before the operation legalizer because we
11552   // may introduce illegal operations.
11553   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11554     return SDValue();
11555
11556   unsigned NumInScalars = N->getNumOperands();
11557   SDLoc dl(N);
11558   EVT VT = N->getValueType(0);
11559
11560   // Check to see if this is a BUILD_VECTOR of a bunch of values
11561   // which come from any_extend or zero_extend nodes. If so, we can create
11562   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11563   // optimizations. We do not handle sign-extend because we can't fill the sign
11564   // using shuffles.
11565   EVT SourceType = MVT::Other;
11566   bool AllAnyExt = true;
11567
11568   for (unsigned i = 0; i != NumInScalars; ++i) {
11569     SDValue In = N->getOperand(i);
11570     // Ignore undef inputs.
11571     if (In.getOpcode() == ISD::UNDEF) continue;
11572
11573     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11574     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11575
11576     // Abort if the element is not an extension.
11577     if (!ZeroExt && !AnyExt) {
11578       SourceType = MVT::Other;
11579       break;
11580     }
11581
11582     // The input is a ZeroExt or AnyExt. Check the original type.
11583     EVT InTy = In.getOperand(0).getValueType();
11584
11585     // Check that all of the widened source types are the same.
11586     if (SourceType == MVT::Other)
11587       // First time.
11588       SourceType = InTy;
11589     else if (InTy != SourceType) {
11590       // Multiple income types. Abort.
11591       SourceType = MVT::Other;
11592       break;
11593     }
11594
11595     // Check if all of the extends are ANY_EXTENDs.
11596     AllAnyExt &= AnyExt;
11597   }
11598
11599   // In order to have valid types, all of the inputs must be extended from the
11600   // same source type and all of the inputs must be any or zero extend.
11601   // Scalar sizes must be a power of two.
11602   EVT OutScalarTy = VT.getScalarType();
11603   bool ValidTypes = SourceType != MVT::Other &&
11604                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11605                  isPowerOf2_32(SourceType.getSizeInBits());
11606
11607   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11608   // turn into a single shuffle instruction.
11609   if (!ValidTypes)
11610     return SDValue();
11611
11612   bool isLE = TLI.isLittleEndian();
11613   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11614   assert(ElemRatio > 1 && "Invalid element size ratio");
11615   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11616                                DAG.getConstant(0, SDLoc(N), SourceType);
11617
11618   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11619   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11620
11621   // Populate the new build_vector
11622   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11623     SDValue Cast = N->getOperand(i);
11624     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11625             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11626             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11627     SDValue In;
11628     if (Cast.getOpcode() == ISD::UNDEF)
11629       In = DAG.getUNDEF(SourceType);
11630     else
11631       In = Cast->getOperand(0);
11632     unsigned Index = isLE ? (i * ElemRatio) :
11633                             (i * ElemRatio + (ElemRatio - 1));
11634
11635     assert(Index < Ops.size() && "Invalid index");
11636     Ops[Index] = In;
11637   }
11638
11639   // The type of the new BUILD_VECTOR node.
11640   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11641   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11642          "Invalid vector size");
11643   // Check if the new vector type is legal.
11644   if (!isTypeLegal(VecVT)) return SDValue();
11645
11646   // Make the new BUILD_VECTOR.
11647   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11648
11649   // The new BUILD_VECTOR node has the potential to be further optimized.
11650   AddToWorklist(BV.getNode());
11651   // Bitcast to the desired type.
11652   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11653 }
11654
11655 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11656   EVT VT = N->getValueType(0);
11657
11658   unsigned NumInScalars = N->getNumOperands();
11659   SDLoc dl(N);
11660
11661   EVT SrcVT = MVT::Other;
11662   unsigned Opcode = ISD::DELETED_NODE;
11663   unsigned NumDefs = 0;
11664
11665   for (unsigned i = 0; i != NumInScalars; ++i) {
11666     SDValue In = N->getOperand(i);
11667     unsigned Opc = In.getOpcode();
11668
11669     if (Opc == ISD::UNDEF)
11670       continue;
11671
11672     // If all scalar values are floats and converted from integers.
11673     if (Opcode == ISD::DELETED_NODE &&
11674         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11675       Opcode = Opc;
11676     }
11677
11678     if (Opc != Opcode)
11679       return SDValue();
11680
11681     EVT InVT = In.getOperand(0).getValueType();
11682
11683     // If all scalar values are typed differently, bail out. It's chosen to
11684     // simplify BUILD_VECTOR of integer types.
11685     if (SrcVT == MVT::Other)
11686       SrcVT = InVT;
11687     if (SrcVT != InVT)
11688       return SDValue();
11689     NumDefs++;
11690   }
11691
11692   // If the vector has just one element defined, it's not worth to fold it into
11693   // a vectorized one.
11694   if (NumDefs < 2)
11695     return SDValue();
11696
11697   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11698          && "Should only handle conversion from integer to float.");
11699   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11700
11701   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11702
11703   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11704     return SDValue();
11705
11706   // Just because the floating-point vector type is legal does not necessarily
11707   // mean that the corresponding integer vector type is.
11708   if (!isTypeLegal(NVT))
11709     return SDValue();
11710
11711   SmallVector<SDValue, 8> Opnds;
11712   for (unsigned i = 0; i != NumInScalars; ++i) {
11713     SDValue In = N->getOperand(i);
11714
11715     if (In.getOpcode() == ISD::UNDEF)
11716       Opnds.push_back(DAG.getUNDEF(SrcVT));
11717     else
11718       Opnds.push_back(In.getOperand(0));
11719   }
11720   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11721   AddToWorklist(BV.getNode());
11722
11723   return DAG.getNode(Opcode, dl, VT, BV);
11724 }
11725
11726 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11727   unsigned NumInScalars = N->getNumOperands();
11728   SDLoc dl(N);
11729   EVT VT = N->getValueType(0);
11730
11731   // A vector built entirely of undefs is undef.
11732   if (ISD::allOperandsUndef(N))
11733     return DAG.getUNDEF(VT);
11734
11735   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11736     return V;
11737
11738   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11739     return V;
11740
11741   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11742   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11743   // at most two distinct vectors, turn this into a shuffle node.
11744
11745   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11746   if (!isTypeLegal(VT))
11747     return SDValue();
11748
11749   // May only combine to shuffle after legalize if shuffle is legal.
11750   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11751     return SDValue();
11752
11753   SDValue VecIn1, VecIn2;
11754   bool UsesZeroVector = false;
11755   for (unsigned i = 0; i != NumInScalars; ++i) {
11756     SDValue Op = N->getOperand(i);
11757     // Ignore undef inputs.
11758     if (Op.getOpcode() == ISD::UNDEF) continue;
11759
11760     // See if we can combine this build_vector into a blend with a zero vector.
11761     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11762         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11763         (Op.getOpcode() == ISD::ConstantFP &&
11764         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11765       UsesZeroVector = true;
11766       continue;
11767     }
11768
11769     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11770     // constant index, bail out.
11771     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11772         !isa<ConstantSDNode>(Op.getOperand(1))) {
11773       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11774       break;
11775     }
11776
11777     // We allow up to two distinct input vectors.
11778     SDValue ExtractedFromVec = Op.getOperand(0);
11779     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11780       continue;
11781
11782     if (!VecIn1.getNode()) {
11783       VecIn1 = ExtractedFromVec;
11784     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11785       VecIn2 = ExtractedFromVec;
11786     } else {
11787       // Too many inputs.
11788       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11789       break;
11790     }
11791   }
11792
11793   // If everything is good, we can make a shuffle operation.
11794   if (VecIn1.getNode()) {
11795     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11796     SmallVector<int, 8> Mask;
11797     for (unsigned i = 0; i != NumInScalars; ++i) {
11798       unsigned Opcode = N->getOperand(i).getOpcode();
11799       if (Opcode == ISD::UNDEF) {
11800         Mask.push_back(-1);
11801         continue;
11802       }
11803
11804       // Operands can also be zero.
11805       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11806         assert(UsesZeroVector &&
11807                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11808                "Unexpected node found!");
11809         Mask.push_back(NumInScalars+i);
11810         continue;
11811       }
11812
11813       // If extracting from the first vector, just use the index directly.
11814       SDValue Extract = N->getOperand(i);
11815       SDValue ExtVal = Extract.getOperand(1);
11816       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11817       if (Extract.getOperand(0) == VecIn1) {
11818         Mask.push_back(ExtIndex);
11819         continue;
11820       }
11821
11822       // Otherwise, use InIdx + InputVecSize
11823       Mask.push_back(InNumElements + ExtIndex);
11824     }
11825
11826     // Avoid introducing illegal shuffles with zero.
11827     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11828       return SDValue();
11829
11830     // We can't generate a shuffle node with mismatched input and output types.
11831     // Attempt to transform a single input vector to the correct type.
11832     if ((VT != VecIn1.getValueType())) {
11833       // If the input vector type has a different base type to the output
11834       // vector type, bail out.
11835       EVT VTElemType = VT.getVectorElementType();
11836       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11837           (VecIn2.getNode() &&
11838            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11839         return SDValue();
11840
11841       // If the input vector is too small, widen it.
11842       // We only support widening of vectors which are half the size of the
11843       // output registers. For example XMM->YMM widening on X86 with AVX.
11844       EVT VecInT = VecIn1.getValueType();
11845       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11846         // If we only have one small input, widen it by adding undef values.
11847         if (!VecIn2.getNode())
11848           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11849                                DAG.getUNDEF(VecIn1.getValueType()));
11850         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11851           // If we have two small inputs of the same type, try to concat them.
11852           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11853           VecIn2 = SDValue(nullptr, 0);
11854         } else
11855           return SDValue();
11856       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11857         // If the input vector is too large, try to split it.
11858         // We don't support having two input vectors that are too large.
11859         // If the zero vector was used, we can not split the vector,
11860         // since we'd need 3 inputs.
11861         if (UsesZeroVector || VecIn2.getNode())
11862           return SDValue();
11863
11864         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11865           return SDValue();
11866
11867         // Try to replace VecIn1 with two extract_subvectors
11868         // No need to update the masks, they should still be correct.
11869         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11870           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11871         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11872           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11873       } else
11874         return SDValue();
11875     }
11876
11877     if (UsesZeroVector)
11878       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11879                                 DAG.getConstantFP(0.0, dl, VT);
11880     else
11881       // If VecIn2 is unused then change it to undef.
11882       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11883
11884     // Check that we were able to transform all incoming values to the same
11885     // type.
11886     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11887         VecIn1.getValueType() != VT)
11888           return SDValue();
11889
11890     // Return the new VECTOR_SHUFFLE node.
11891     SDValue Ops[2];
11892     Ops[0] = VecIn1;
11893     Ops[1] = VecIn2;
11894     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11895   }
11896
11897   return SDValue();
11898 }
11899
11900 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11901   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11902   EVT OpVT = N->getOperand(0).getValueType();
11903
11904   // If the operands are legal vectors, leave them alone.
11905   if (TLI.isTypeLegal(OpVT))
11906     return SDValue();
11907
11908   SDLoc DL(N);
11909   EVT VT = N->getValueType(0);
11910   SmallVector<SDValue, 8> Ops;
11911
11912   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11913   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11914
11915   // Keep track of what we encounter.
11916   bool AnyInteger = false;
11917   bool AnyFP = false;
11918   for (const SDValue &Op : N->ops()) {
11919     if (ISD::BITCAST == Op.getOpcode() &&
11920         !Op.getOperand(0).getValueType().isVector())
11921       Ops.push_back(Op.getOperand(0));
11922     else if (ISD::UNDEF == Op.getOpcode())
11923       Ops.push_back(ScalarUndef);
11924     else
11925       return SDValue();
11926
11927     // Note whether we encounter an integer or floating point scalar.
11928     // If it's neither, bail out, it could be something weird like x86mmx.
11929     EVT LastOpVT = Ops.back().getValueType();
11930     if (LastOpVT.isFloatingPoint())
11931       AnyFP = true;
11932     else if (LastOpVT.isInteger())
11933       AnyInteger = true;
11934     else
11935       return SDValue();
11936   }
11937
11938   // If any of the operands is a floating point scalar bitcast to a vector,
11939   // use floating point types throughout, and bitcast everything.  
11940   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11941   if (AnyFP) {
11942     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11943     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11944     if (AnyInteger) {
11945       for (SDValue &Op : Ops) {
11946         if (Op.getValueType() == SVT)
11947           continue;
11948         if (Op.getOpcode() == ISD::UNDEF)
11949           Op = ScalarUndef;
11950         else
11951           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11952       }
11953     }
11954   }
11955
11956   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11957                                VT.getSizeInBits() / SVT.getSizeInBits());
11958   return DAG.getNode(ISD::BITCAST, DL, VT,
11959                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11960 }
11961
11962 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11963   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11964   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11965   // inputs come from at most two distinct vectors, turn this into a shuffle
11966   // node.
11967
11968   // If we only have one input vector, we don't need to do any concatenation.
11969   if (N->getNumOperands() == 1)
11970     return N->getOperand(0);
11971
11972   // Check if all of the operands are undefs.
11973   EVT VT = N->getValueType(0);
11974   if (ISD::allOperandsUndef(N))
11975     return DAG.getUNDEF(VT);
11976
11977   // Optimize concat_vectors where all but the first of the vectors are undef.
11978   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11979         return Op.getOpcode() == ISD::UNDEF;
11980       })) {
11981     SDValue In = N->getOperand(0);
11982     assert(In.getValueType().isVector() && "Must concat vectors");
11983
11984     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11985     if (In->getOpcode() == ISD::BITCAST &&
11986         !In->getOperand(0)->getValueType(0).isVector()) {
11987       SDValue Scalar = In->getOperand(0);
11988
11989       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11990       // look through the trunc so we can still do the transform:
11991       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11992       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11993           !TLI.isTypeLegal(Scalar.getValueType()) &&
11994           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11995         Scalar = Scalar->getOperand(0);
11996
11997       EVT SclTy = Scalar->getValueType(0);
11998
11999       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12000         return SDValue();
12001
12002       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12003                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12004       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12005         return SDValue();
12006
12007       SDLoc dl = SDLoc(N);
12008       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12009       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12010     }
12011   }
12012
12013   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12014   // We have already tested above for an UNDEF only concatenation.
12015   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12016   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12017   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12018     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12019   };
12020   bool AllBuildVectorsOrUndefs =
12021       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12022   if (AllBuildVectorsOrUndefs) {
12023     SmallVector<SDValue, 8> Opnds;
12024     EVT SVT = VT.getScalarType();
12025
12026     EVT MinVT = SVT;
12027     if (!SVT.isFloatingPoint()) {
12028       // If BUILD_VECTOR are from built from integer, they may have different
12029       // operand types. Get the smallest type and truncate all operands to it.
12030       bool FoundMinVT = false;
12031       for (const SDValue &Op : N->ops())
12032         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12033           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12034           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12035           FoundMinVT = true;
12036         }
12037       assert(FoundMinVT && "Concat vector type mismatch");
12038     }
12039
12040     for (const SDValue &Op : N->ops()) {
12041       EVT OpVT = Op.getValueType();
12042       unsigned NumElts = OpVT.getVectorNumElements();
12043
12044       if (ISD::UNDEF == Op.getOpcode())
12045         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12046
12047       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12048         if (SVT.isFloatingPoint()) {
12049           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12050           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12051         } else {
12052           for (unsigned i = 0; i != NumElts; ++i)
12053             Opnds.push_back(
12054                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12055         }
12056       }
12057     }
12058
12059     assert(VT.getVectorNumElements() == Opnds.size() &&
12060            "Concat vector type mismatch");
12061     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12062   }
12063
12064   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12065   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12066     return V;
12067
12068   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12069   // nodes often generate nop CONCAT_VECTOR nodes.
12070   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12071   // place the incoming vectors at the exact same location.
12072   SDValue SingleSource = SDValue();
12073   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12074
12075   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12076     SDValue Op = N->getOperand(i);
12077
12078     if (Op.getOpcode() == ISD::UNDEF)
12079       continue;
12080
12081     // Check if this is the identity extract:
12082     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12083       return SDValue();
12084
12085     // Find the single incoming vector for the extract_subvector.
12086     if (SingleSource.getNode()) {
12087       if (Op.getOperand(0) != SingleSource)
12088         return SDValue();
12089     } else {
12090       SingleSource = Op.getOperand(0);
12091
12092       // Check the source type is the same as the type of the result.
12093       // If not, this concat may extend the vector, so we can not
12094       // optimize it away.
12095       if (SingleSource.getValueType() != N->getValueType(0))
12096         return SDValue();
12097     }
12098
12099     unsigned IdentityIndex = i * PartNumElem;
12100     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12101     // The extract index must be constant.
12102     if (!CS)
12103       return SDValue();
12104
12105     // Check that we are reading from the identity index.
12106     if (CS->getZExtValue() != IdentityIndex)
12107       return SDValue();
12108   }
12109
12110   if (SingleSource.getNode())
12111     return SingleSource;
12112
12113   return SDValue();
12114 }
12115
12116 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12117   EVT NVT = N->getValueType(0);
12118   SDValue V = N->getOperand(0);
12119
12120   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12121     // Combine:
12122     //    (extract_subvec (concat V1, V2, ...), i)
12123     // Into:
12124     //    Vi if possible
12125     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12126     // type.
12127     if (V->getOperand(0).getValueType() != NVT)
12128       return SDValue();
12129     unsigned Idx = N->getConstantOperandVal(1);
12130     unsigned NumElems = NVT.getVectorNumElements();
12131     assert((Idx % NumElems) == 0 &&
12132            "IDX in concat is not a multiple of the result vector length.");
12133     return V->getOperand(Idx / NumElems);
12134   }
12135
12136   // Skip bitcasting
12137   if (V->getOpcode() == ISD::BITCAST)
12138     V = V.getOperand(0);
12139
12140   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12141     SDLoc dl(N);
12142     // Handle only simple case where vector being inserted and vector
12143     // being extracted are of same type, and are half size of larger vectors.
12144     EVT BigVT = V->getOperand(0).getValueType();
12145     EVT SmallVT = V->getOperand(1).getValueType();
12146     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12147       return SDValue();
12148
12149     // Only handle cases where both indexes are constants with the same type.
12150     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12151     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12152
12153     if (InsIdx && ExtIdx &&
12154         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12155         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12156       // Combine:
12157       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12158       // Into:
12159       //    indices are equal or bit offsets are equal => V1
12160       //    otherwise => (extract_subvec V1, ExtIdx)
12161       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12162           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12163         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12164       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12165                          DAG.getNode(ISD::BITCAST, dl,
12166                                      N->getOperand(0).getValueType(),
12167                                      V->getOperand(0)), N->getOperand(1));
12168     }
12169   }
12170
12171   return SDValue();
12172 }
12173
12174 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12175                                                  SDValue V, SelectionDAG &DAG) {
12176   SDLoc DL(V);
12177   EVT VT = V.getValueType();
12178
12179   switch (V.getOpcode()) {
12180   default:
12181     return V;
12182
12183   case ISD::CONCAT_VECTORS: {
12184     EVT OpVT = V->getOperand(0).getValueType();
12185     int OpSize = OpVT.getVectorNumElements();
12186     SmallBitVector OpUsedElements(OpSize, false);
12187     bool FoundSimplification = false;
12188     SmallVector<SDValue, 4> NewOps;
12189     NewOps.reserve(V->getNumOperands());
12190     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12191       SDValue Op = V->getOperand(i);
12192       bool OpUsed = false;
12193       for (int j = 0; j < OpSize; ++j)
12194         if (UsedElements[i * OpSize + j]) {
12195           OpUsedElements[j] = true;
12196           OpUsed = true;
12197         }
12198       NewOps.push_back(
12199           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12200                  : DAG.getUNDEF(OpVT));
12201       FoundSimplification |= Op == NewOps.back();
12202       OpUsedElements.reset();
12203     }
12204     if (FoundSimplification)
12205       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12206     return V;
12207   }
12208
12209   case ISD::INSERT_SUBVECTOR: {
12210     SDValue BaseV = V->getOperand(0);
12211     SDValue SubV = V->getOperand(1);
12212     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12213     if (!IdxN)
12214       return V;
12215
12216     int SubSize = SubV.getValueType().getVectorNumElements();
12217     int Idx = IdxN->getZExtValue();
12218     bool SubVectorUsed = false;
12219     SmallBitVector SubUsedElements(SubSize, false);
12220     for (int i = 0; i < SubSize; ++i)
12221       if (UsedElements[i + Idx]) {
12222         SubVectorUsed = true;
12223         SubUsedElements[i] = true;
12224         UsedElements[i + Idx] = false;
12225       }
12226
12227     // Now recurse on both the base and sub vectors.
12228     SDValue SimplifiedSubV =
12229         SubVectorUsed
12230             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12231             : DAG.getUNDEF(SubV.getValueType());
12232     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12233     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12234       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12235                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12236     return V;
12237   }
12238   }
12239 }
12240
12241 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12242                                        SDValue N1, SelectionDAG &DAG) {
12243   EVT VT = SVN->getValueType(0);
12244   int NumElts = VT.getVectorNumElements();
12245   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12246   for (int M : SVN->getMask())
12247     if (M >= 0 && M < NumElts)
12248       N0UsedElements[M] = true;
12249     else if (M >= NumElts)
12250       N1UsedElements[M - NumElts] = true;
12251
12252   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12253   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12254   if (S0 == N0 && S1 == N1)
12255     return SDValue();
12256
12257   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12258 }
12259
12260 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12261 // or turn a shuffle of a single concat into simpler shuffle then concat.
12262 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12263   EVT VT = N->getValueType(0);
12264   unsigned NumElts = VT.getVectorNumElements();
12265
12266   SDValue N0 = N->getOperand(0);
12267   SDValue N1 = N->getOperand(1);
12268   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12269
12270   SmallVector<SDValue, 4> Ops;
12271   EVT ConcatVT = N0.getOperand(0).getValueType();
12272   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12273   unsigned NumConcats = NumElts / NumElemsPerConcat;
12274
12275   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12276   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12277   // half vector elements.
12278   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12279       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12280                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12281     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12282                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12283     N1 = DAG.getUNDEF(ConcatVT);
12284     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12285   }
12286
12287   // Look at every vector that's inserted. We're looking for exact
12288   // subvector-sized copies from a concatenated vector
12289   for (unsigned I = 0; I != NumConcats; ++I) {
12290     // Make sure we're dealing with a copy.
12291     unsigned Begin = I * NumElemsPerConcat;
12292     bool AllUndef = true, NoUndef = true;
12293     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12294       if (SVN->getMaskElt(J) >= 0)
12295         AllUndef = false;
12296       else
12297         NoUndef = false;
12298     }
12299
12300     if (NoUndef) {
12301       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12302         return SDValue();
12303
12304       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12305         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12306           return SDValue();
12307
12308       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12309       if (FirstElt < N0.getNumOperands())
12310         Ops.push_back(N0.getOperand(FirstElt));
12311       else
12312         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12313
12314     } else if (AllUndef) {
12315       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12316     } else { // Mixed with general masks and undefs, can't do optimization.
12317       return SDValue();
12318     }
12319   }
12320
12321   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12322 }
12323
12324 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12325   EVT VT = N->getValueType(0);
12326   unsigned NumElts = VT.getVectorNumElements();
12327
12328   SDValue N0 = N->getOperand(0);
12329   SDValue N1 = N->getOperand(1);
12330
12331   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12332
12333   // Canonicalize shuffle undef, undef -> undef
12334   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12335     return DAG.getUNDEF(VT);
12336
12337   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12338
12339   // Canonicalize shuffle v, v -> v, undef
12340   if (N0 == N1) {
12341     SmallVector<int, 8> NewMask;
12342     for (unsigned i = 0; i != NumElts; ++i) {
12343       int Idx = SVN->getMaskElt(i);
12344       if (Idx >= (int)NumElts) Idx -= NumElts;
12345       NewMask.push_back(Idx);
12346     }
12347     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12348                                 &NewMask[0]);
12349   }
12350
12351   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12352   if (N0.getOpcode() == ISD::UNDEF) {
12353     SmallVector<int, 8> NewMask;
12354     for (unsigned i = 0; i != NumElts; ++i) {
12355       int Idx = SVN->getMaskElt(i);
12356       if (Idx >= 0) {
12357         if (Idx >= (int)NumElts)
12358           Idx -= NumElts;
12359         else
12360           Idx = -1; // remove reference to lhs
12361       }
12362       NewMask.push_back(Idx);
12363     }
12364     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12365                                 &NewMask[0]);
12366   }
12367
12368   // Remove references to rhs if it is undef
12369   if (N1.getOpcode() == ISD::UNDEF) {
12370     bool Changed = false;
12371     SmallVector<int, 8> NewMask;
12372     for (unsigned i = 0; i != NumElts; ++i) {
12373       int Idx = SVN->getMaskElt(i);
12374       if (Idx >= (int)NumElts) {
12375         Idx = -1;
12376         Changed = true;
12377       }
12378       NewMask.push_back(Idx);
12379     }
12380     if (Changed)
12381       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12382   }
12383
12384   // If it is a splat, check if the argument vector is another splat or a
12385   // build_vector.
12386   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12387     SDNode *V = N0.getNode();
12388
12389     // If this is a bit convert that changes the element type of the vector but
12390     // not the number of vector elements, look through it.  Be careful not to
12391     // look though conversions that change things like v4f32 to v2f64.
12392     if (V->getOpcode() == ISD::BITCAST) {
12393       SDValue ConvInput = V->getOperand(0);
12394       if (ConvInput.getValueType().isVector() &&
12395           ConvInput.getValueType().getVectorNumElements() == NumElts)
12396         V = ConvInput.getNode();
12397     }
12398
12399     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12400       assert(V->getNumOperands() == NumElts &&
12401              "BUILD_VECTOR has wrong number of operands");
12402       SDValue Base;
12403       bool AllSame = true;
12404       for (unsigned i = 0; i != NumElts; ++i) {
12405         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12406           Base = V->getOperand(i);
12407           break;
12408         }
12409       }
12410       // Splat of <u, u, u, u>, return <u, u, u, u>
12411       if (!Base.getNode())
12412         return N0;
12413       for (unsigned i = 0; i != NumElts; ++i) {
12414         if (V->getOperand(i) != Base) {
12415           AllSame = false;
12416           break;
12417         }
12418       }
12419       // Splat of <x, x, x, x>, return <x, x, x, x>
12420       if (AllSame)
12421         return N0;
12422
12423       // Canonicalize any other splat as a build_vector.
12424       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12425       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12426       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12427                                   V->getValueType(0), Ops);
12428
12429       // We may have jumped through bitcasts, so the type of the
12430       // BUILD_VECTOR may not match the type of the shuffle.
12431       if (V->getValueType(0) != VT)
12432         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12433       return NewBV;
12434     }
12435   }
12436
12437   // There are various patterns used to build up a vector from smaller vectors,
12438   // subvectors, or elements. Scan chains of these and replace unused insertions
12439   // or components with undef.
12440   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12441     return S;
12442
12443   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12444       Level < AfterLegalizeVectorOps &&
12445       (N1.getOpcode() == ISD::UNDEF ||
12446       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12447        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12448     SDValue V = partitionShuffleOfConcats(N, DAG);
12449
12450     if (V.getNode())
12451       return V;
12452   }
12453
12454   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12455   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12456   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12457     SmallVector<SDValue, 8> Ops;
12458     for (int M : SVN->getMask()) {
12459       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12460       if (M >= 0) {
12461         int Idx = M % NumElts;
12462         SDValue &S = (M < (int)NumElts ? N0 : N1);
12463         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12464           Op = S.getOperand(Idx);
12465         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12466           if (Idx == 0)
12467             Op = S.getOperand(0);
12468         } else {
12469           // Operand can't be combined - bail out.
12470           break;
12471         }
12472       }
12473       Ops.push_back(Op);
12474     }
12475     if (Ops.size() == VT.getVectorNumElements()) {
12476       // BUILD_VECTOR requires all inputs to be of the same type, find the
12477       // maximum type and extend them all.
12478       EVT SVT = VT.getScalarType();
12479       if (SVT.isInteger())
12480         for (SDValue &Op : Ops)
12481           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12482       if (SVT != VT.getScalarType())
12483         for (SDValue &Op : Ops)
12484           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12485                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12486                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12487       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12488     }
12489   }
12490
12491   // If this shuffle only has a single input that is a bitcasted shuffle,
12492   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12493   // back to their original types.
12494   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12495       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12496       TLI.isTypeLegal(VT)) {
12497
12498     // Peek through the bitcast only if there is one user.
12499     SDValue BC0 = N0;
12500     while (BC0.getOpcode() == ISD::BITCAST) {
12501       if (!BC0.hasOneUse())
12502         break;
12503       BC0 = BC0.getOperand(0);
12504     }
12505
12506     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12507       if (Scale == 1)
12508         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12509
12510       SmallVector<int, 8> NewMask;
12511       for (int M : Mask)
12512         for (int s = 0; s != Scale; ++s)
12513           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12514       return NewMask;
12515     };
12516
12517     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12518       EVT SVT = VT.getScalarType();
12519       EVT InnerVT = BC0->getValueType(0);
12520       EVT InnerSVT = InnerVT.getScalarType();
12521
12522       // Determine which shuffle works with the smaller scalar type.
12523       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12524       EVT ScaleSVT = ScaleVT.getScalarType();
12525
12526       if (TLI.isTypeLegal(ScaleVT) &&
12527           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12528           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12529
12530         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12531         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12532
12533         // Scale the shuffle masks to the smaller scalar type.
12534         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12535         SmallVector<int, 8> InnerMask =
12536             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12537         SmallVector<int, 8> OuterMask =
12538             ScaleShuffleMask(SVN->getMask(), OuterScale);
12539
12540         // Merge the shuffle masks.
12541         SmallVector<int, 8> NewMask;
12542         for (int M : OuterMask)
12543           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12544
12545         // Test for shuffle mask legality over both commutations.
12546         SDValue SV0 = BC0->getOperand(0);
12547         SDValue SV1 = BC0->getOperand(1);
12548         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12549         if (!LegalMask) {
12550           std::swap(SV0, SV1);
12551           ShuffleVectorSDNode::commuteMask(NewMask);
12552           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12553         }
12554
12555         if (LegalMask) {
12556           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12557           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12558           return DAG.getNode(
12559               ISD::BITCAST, SDLoc(N), VT,
12560               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12561         }
12562       }
12563     }
12564   }
12565
12566   // Canonicalize shuffles according to rules:
12567   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12568   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12569   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12570   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12571       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12572       TLI.isTypeLegal(VT)) {
12573     // The incoming shuffle must be of the same type as the result of the
12574     // current shuffle.
12575     assert(N1->getOperand(0).getValueType() == VT &&
12576            "Shuffle types don't match");
12577
12578     SDValue SV0 = N1->getOperand(0);
12579     SDValue SV1 = N1->getOperand(1);
12580     bool HasSameOp0 = N0 == SV0;
12581     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12582     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12583       // Commute the operands of this shuffle so that next rule
12584       // will trigger.
12585       return DAG.getCommutedVectorShuffle(*SVN);
12586   }
12587
12588   // Try to fold according to rules:
12589   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12590   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12591   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12592   // Don't try to fold shuffles with illegal type.
12593   // Only fold if this shuffle is the only user of the other shuffle.
12594   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12595       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12596     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12597
12598     // The incoming shuffle must be of the same type as the result of the
12599     // current shuffle.
12600     assert(OtherSV->getOperand(0).getValueType() == VT &&
12601            "Shuffle types don't match");
12602
12603     SDValue SV0, SV1;
12604     SmallVector<int, 4> Mask;
12605     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12606     // operand, and SV1 as the second operand.
12607     for (unsigned i = 0; i != NumElts; ++i) {
12608       int Idx = SVN->getMaskElt(i);
12609       if (Idx < 0) {
12610         // Propagate Undef.
12611         Mask.push_back(Idx);
12612         continue;
12613       }
12614
12615       SDValue CurrentVec;
12616       if (Idx < (int)NumElts) {
12617         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12618         // shuffle mask to identify which vector is actually referenced.
12619         Idx = OtherSV->getMaskElt(Idx);
12620         if (Idx < 0) {
12621           // Propagate Undef.
12622           Mask.push_back(Idx);
12623           continue;
12624         }
12625
12626         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12627                                            : OtherSV->getOperand(1);
12628       } else {
12629         // This shuffle index references an element within N1.
12630         CurrentVec = N1;
12631       }
12632
12633       // Simple case where 'CurrentVec' is UNDEF.
12634       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12635         Mask.push_back(-1);
12636         continue;
12637       }
12638
12639       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12640       // will be the first or second operand of the combined shuffle.
12641       Idx = Idx % NumElts;
12642       if (!SV0.getNode() || SV0 == CurrentVec) {
12643         // Ok. CurrentVec is the left hand side.
12644         // Update the mask accordingly.
12645         SV0 = CurrentVec;
12646         Mask.push_back(Idx);
12647         continue;
12648       }
12649
12650       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12651       if (SV1.getNode() && SV1 != CurrentVec)
12652         return SDValue();
12653
12654       // Ok. CurrentVec is the right hand side.
12655       // Update the mask accordingly.
12656       SV1 = CurrentVec;
12657       Mask.push_back(Idx + NumElts);
12658     }
12659
12660     // Check if all indices in Mask are Undef. In case, propagate Undef.
12661     bool isUndefMask = true;
12662     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12663       isUndefMask &= Mask[i] < 0;
12664
12665     if (isUndefMask)
12666       return DAG.getUNDEF(VT);
12667
12668     if (!SV0.getNode())
12669       SV0 = DAG.getUNDEF(VT);
12670     if (!SV1.getNode())
12671       SV1 = DAG.getUNDEF(VT);
12672
12673     // Avoid introducing shuffles with illegal mask.
12674     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12675       ShuffleVectorSDNode::commuteMask(Mask);
12676
12677       if (!TLI.isShuffleMaskLegal(Mask, VT))
12678         return SDValue();
12679
12680       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12681       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12682       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12683       std::swap(SV0, SV1);
12684     }
12685
12686     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12687     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12688     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12689     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12690   }
12691
12692   return SDValue();
12693 }
12694
12695 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12696   SDValue InVal = N->getOperand(0);
12697   EVT VT = N->getValueType(0);
12698
12699   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12700   // with a VECTOR_SHUFFLE.
12701   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12702     SDValue InVec = InVal->getOperand(0);
12703     SDValue EltNo = InVal->getOperand(1);
12704
12705     // FIXME: We could support implicit truncation if the shuffle can be
12706     // scaled to a smaller vector scalar type.
12707     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12708     if (C0 && VT == InVec.getValueType() &&
12709         VT.getScalarType() == InVal.getValueType()) {
12710       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12711       int Elt = C0->getZExtValue();
12712       NewMask[0] = Elt;
12713
12714       if (TLI.isShuffleMaskLegal(NewMask, VT))
12715         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12716                                     NewMask);
12717     }
12718   }
12719
12720   return SDValue();
12721 }
12722
12723 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12724   SDValue N0 = N->getOperand(0);
12725   SDValue N2 = N->getOperand(2);
12726
12727   // If the input vector is a concatenation, and the insert replaces
12728   // one of the halves, we can optimize into a single concat_vectors.
12729   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12730       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12731     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12732     EVT VT = N->getValueType(0);
12733
12734     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12735     // (concat_vectors Z, Y)
12736     if (InsIdx == 0)
12737       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12738                          N->getOperand(1), N0.getOperand(1));
12739
12740     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12741     // (concat_vectors X, Z)
12742     if (InsIdx == VT.getVectorNumElements()/2)
12743       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12744                          N0.getOperand(0), N->getOperand(1));
12745   }
12746
12747   return SDValue();
12748 }
12749
12750 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12751   SDValue N0 = N->getOperand(0);
12752
12753   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12754   if (N0->getOpcode() == ISD::FP16_TO_FP)
12755     return N0->getOperand(0);
12756
12757   return SDValue();
12758 }
12759
12760 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12761 /// with the destination vector and a zero vector.
12762 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12763 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12764 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12765   EVT VT = N->getValueType(0);
12766   SDValue LHS = N->getOperand(0);
12767   SDValue RHS = N->getOperand(1);
12768   SDLoc dl(N);
12769
12770   // Make sure we're not running after operation legalization where it 
12771   // may have custom lowered the vector shuffles.
12772   if (LegalOperations)
12773     return SDValue();
12774
12775   if (N->getOpcode() != ISD::AND)
12776     return SDValue();
12777
12778   if (RHS.getOpcode() == ISD::BITCAST)
12779     RHS = RHS.getOperand(0);
12780
12781   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12782     SmallVector<int, 8> Indices;
12783     unsigned NumElts = RHS.getNumOperands();
12784
12785     for (unsigned i = 0; i != NumElts; ++i) {
12786       SDValue Elt = RHS.getOperand(i);
12787       if (!isa<ConstantSDNode>(Elt))
12788         return SDValue();
12789
12790       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12791         Indices.push_back(i);
12792       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12793         Indices.push_back(NumElts+i);
12794       else
12795         return SDValue();
12796     }
12797
12798     // Let's see if the target supports this vector_shuffle.
12799     EVT RVT = RHS.getValueType();
12800     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12801       return SDValue();
12802
12803     // Return the new VECTOR_SHUFFLE node.
12804     EVT EltVT = RVT.getVectorElementType();
12805     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12806                                    DAG.getConstant(0, dl, EltVT));
12807     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12808     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12809     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12810     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12811   }
12812
12813   return SDValue();
12814 }
12815
12816 /// Visit a binary vector operation, like ADD.
12817 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12818   assert(N->getValueType(0).isVector() &&
12819          "SimplifyVBinOp only works on vectors!");
12820
12821   SDValue LHS = N->getOperand(0);
12822   SDValue RHS = N->getOperand(1);
12823
12824   if (SDValue Shuffle = XformToShuffleWithZero(N))
12825     return Shuffle;
12826
12827   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12828   // this operation.
12829   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12830       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12831     // Check if both vectors are constants. If not bail out.
12832     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12833           cast<BuildVectorSDNode>(RHS)->isConstant()))
12834       return SDValue();
12835
12836     SmallVector<SDValue, 8> Ops;
12837     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12838       SDValue LHSOp = LHS.getOperand(i);
12839       SDValue RHSOp = RHS.getOperand(i);
12840
12841       // Can't fold divide by zero.
12842       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12843           N->getOpcode() == ISD::FDIV) {
12844         if ((RHSOp.getOpcode() == ISD::Constant &&
12845              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12846             (RHSOp.getOpcode() == ISD::ConstantFP &&
12847              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12848           break;
12849       }
12850
12851       EVT VT = LHSOp.getValueType();
12852       EVT RVT = RHSOp.getValueType();
12853       if (RVT != VT) {
12854         // Integer BUILD_VECTOR operands may have types larger than the element
12855         // size (e.g., when the element type is not legal).  Prior to type
12856         // legalization, the types may not match between the two BUILD_VECTORS.
12857         // Truncate one of the operands to make them match.
12858         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12859           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12860         } else {
12861           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12862           VT = RVT;
12863         }
12864       }
12865       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12866                                    LHSOp, RHSOp);
12867       if (FoldOp.getOpcode() != ISD::UNDEF &&
12868           FoldOp.getOpcode() != ISD::Constant &&
12869           FoldOp.getOpcode() != ISD::ConstantFP)
12870         break;
12871       Ops.push_back(FoldOp);
12872       AddToWorklist(FoldOp.getNode());
12873     }
12874
12875     if (Ops.size() == LHS.getNumOperands())
12876       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12877   }
12878
12879   // Type legalization might introduce new shuffles in the DAG.
12880   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12881   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12882   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12883       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12884       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12885       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12886     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12887     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12888
12889     if (SVN0->getMask().equals(SVN1->getMask())) {
12890       EVT VT = N->getValueType(0);
12891       SDValue UndefVector = LHS.getOperand(1);
12892       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12893                                      LHS.getOperand(0), RHS.getOperand(0));
12894       AddUsersToWorklist(N);
12895       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12896                                   &SVN0->getMask()[0]);
12897     }
12898   }
12899
12900   return SDValue();
12901 }
12902
12903 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12904                                     SDValue N1, SDValue N2){
12905   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12906
12907   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12908                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12909
12910   // If we got a simplified select_cc node back from SimplifySelectCC, then
12911   // break it down into a new SETCC node, and a new SELECT node, and then return
12912   // the SELECT node, since we were called with a SELECT node.
12913   if (SCC.getNode()) {
12914     // Check to see if we got a select_cc back (to turn into setcc/select).
12915     // Otherwise, just return whatever node we got back, like fabs.
12916     if (SCC.getOpcode() == ISD::SELECT_CC) {
12917       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12918                                   N0.getValueType(),
12919                                   SCC.getOperand(0), SCC.getOperand(1),
12920                                   SCC.getOperand(4));
12921       AddToWorklist(SETCC.getNode());
12922       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12923                            SCC.getOperand(2), SCC.getOperand(3));
12924     }
12925
12926     return SCC;
12927   }
12928   return SDValue();
12929 }
12930
12931 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12932 /// being selected between, see if we can simplify the select.  Callers of this
12933 /// should assume that TheSelect is deleted if this returns true.  As such, they
12934 /// should return the appropriate thing (e.g. the node) back to the top-level of
12935 /// the DAG combiner loop to avoid it being looked at.
12936 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12937                                     SDValue RHS) {
12938
12939   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12940   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12941   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12942     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12943       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12944       SDValue Sqrt = RHS;
12945       ISD::CondCode CC;
12946       SDValue CmpLHS;
12947       const ConstantFPSDNode *NegZero = nullptr;
12948
12949       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12950         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12951         CmpLHS = TheSelect->getOperand(0);
12952         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12953       } else {
12954         // SELECT or VSELECT
12955         SDValue Cmp = TheSelect->getOperand(0);
12956         if (Cmp.getOpcode() == ISD::SETCC) {
12957           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12958           CmpLHS = Cmp.getOperand(0);
12959           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12960         }
12961       }
12962       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12963           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12964           CC == ISD::SETULT || CC == ISD::SETLT)) {
12965         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12966         CombineTo(TheSelect, Sqrt);
12967         return true;
12968       }
12969     }
12970   }
12971   // Cannot simplify select with vector condition
12972   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12973
12974   // If this is a select from two identical things, try to pull the operation
12975   // through the select.
12976   if (LHS.getOpcode() != RHS.getOpcode() ||
12977       !LHS.hasOneUse() || !RHS.hasOneUse())
12978     return false;
12979
12980   // If this is a load and the token chain is identical, replace the select
12981   // of two loads with a load through a select of the address to load from.
12982   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12983   // constants have been dropped into the constant pool.
12984   if (LHS.getOpcode() == ISD::LOAD) {
12985     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12986     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12987
12988     // Token chains must be identical.
12989     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12990         // Do not let this transformation reduce the number of volatile loads.
12991         LLD->isVolatile() || RLD->isVolatile() ||
12992         // FIXME: If either is a pre/post inc/dec load,
12993         // we'd need to split out the address adjustment.
12994         LLD->isIndexed() || RLD->isIndexed() ||
12995         // If this is an EXTLOAD, the VT's must match.
12996         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12997         // If this is an EXTLOAD, the kind of extension must match.
12998         (LLD->getExtensionType() != RLD->getExtensionType() &&
12999          // The only exception is if one of the extensions is anyext.
13000          LLD->getExtensionType() != ISD::EXTLOAD &&
13001          RLD->getExtensionType() != ISD::EXTLOAD) ||
13002         // FIXME: this discards src value information.  This is
13003         // over-conservative. It would be beneficial to be able to remember
13004         // both potential memory locations.  Since we are discarding
13005         // src value info, don't do the transformation if the memory
13006         // locations are not in the default address space.
13007         LLD->getPointerInfo().getAddrSpace() != 0 ||
13008         RLD->getPointerInfo().getAddrSpace() != 0 ||
13009         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13010                                       LLD->getBasePtr().getValueType()))
13011       return false;
13012
13013     // Check that the select condition doesn't reach either load.  If so,
13014     // folding this will induce a cycle into the DAG.  If not, this is safe to
13015     // xform, so create a select of the addresses.
13016     SDValue Addr;
13017     if (TheSelect->getOpcode() == ISD::SELECT) {
13018       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13019       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13020           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13021         return false;
13022       // The loads must not depend on one another.
13023       if (LLD->isPredecessorOf(RLD) ||
13024           RLD->isPredecessorOf(LLD))
13025         return false;
13026       Addr = DAG.getSelect(SDLoc(TheSelect),
13027                            LLD->getBasePtr().getValueType(),
13028                            TheSelect->getOperand(0), LLD->getBasePtr(),
13029                            RLD->getBasePtr());
13030     } else {  // Otherwise SELECT_CC
13031       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13032       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13033
13034       if ((LLD->hasAnyUseOfValue(1) &&
13035            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13036           (RLD->hasAnyUseOfValue(1) &&
13037            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13038         return false;
13039
13040       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13041                          LLD->getBasePtr().getValueType(),
13042                          TheSelect->getOperand(0),
13043                          TheSelect->getOperand(1),
13044                          LLD->getBasePtr(), RLD->getBasePtr(),
13045                          TheSelect->getOperand(4));
13046     }
13047
13048     SDValue Load;
13049     // It is safe to replace the two loads if they have different alignments,
13050     // but the new load must be the minimum (most restrictive) alignment of the
13051     // inputs.
13052     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13053     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13054     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13055       Load = DAG.getLoad(TheSelect->getValueType(0),
13056                          SDLoc(TheSelect),
13057                          // FIXME: Discards pointer and AA info.
13058                          LLD->getChain(), Addr, MachinePointerInfo(),
13059                          LLD->isVolatile(), LLD->isNonTemporal(),
13060                          isInvariant, Alignment);
13061     } else {
13062       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13063                             RLD->getExtensionType() : LLD->getExtensionType(),
13064                             SDLoc(TheSelect),
13065                             TheSelect->getValueType(0),
13066                             // FIXME: Discards pointer and AA info.
13067                             LLD->getChain(), Addr, MachinePointerInfo(),
13068                             LLD->getMemoryVT(), LLD->isVolatile(),
13069                             LLD->isNonTemporal(), isInvariant, Alignment);
13070     }
13071
13072     // Users of the select now use the result of the load.
13073     CombineTo(TheSelect, Load);
13074
13075     // Users of the old loads now use the new load's chain.  We know the
13076     // old-load value is dead now.
13077     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13078     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13079     return true;
13080   }
13081
13082   return false;
13083 }
13084
13085 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13086 /// where 'cond' is the comparison specified by CC.
13087 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13088                                       SDValue N2, SDValue N3,
13089                                       ISD::CondCode CC, bool NotExtCompare) {
13090   // (x ? y : y) -> y.
13091   if (N2 == N3) return N2;
13092
13093   EVT VT = N2.getValueType();
13094   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13095   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13096   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13097
13098   // Determine if the condition we're dealing with is constant
13099   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13100                               N0, N1, CC, DL, false);
13101   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13102   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13103
13104   // fold select_cc true, x, y -> x
13105   if (SCCC && !SCCC->isNullValue())
13106     return N2;
13107   // fold select_cc false, x, y -> y
13108   if (SCCC && SCCC->isNullValue())
13109     return N3;
13110
13111   // Check to see if we can simplify the select into an fabs node
13112   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13113     // Allow either -0.0 or 0.0
13114     if (CFP->getValueAPF().isZero()) {
13115       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13116       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13117           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13118           N2 == N3.getOperand(0))
13119         return DAG.getNode(ISD::FABS, DL, VT, N0);
13120
13121       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13122       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13123           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13124           N2.getOperand(0) == N3)
13125         return DAG.getNode(ISD::FABS, DL, VT, N3);
13126     }
13127   }
13128
13129   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13130   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13131   // in it.  This is a win when the constant is not otherwise available because
13132   // it replaces two constant pool loads with one.  We only do this if the FP
13133   // type is known to be legal, because if it isn't, then we are before legalize
13134   // types an we want the other legalization to happen first (e.g. to avoid
13135   // messing with soft float) and if the ConstantFP is not legal, because if
13136   // it is legal, we may not need to store the FP constant in a constant pool.
13137   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13138     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13139       if (TLI.isTypeLegal(N2.getValueType()) &&
13140           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13141                TargetLowering::Legal &&
13142            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13143            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13144           // If both constants have multiple uses, then we won't need to do an
13145           // extra load, they are likely around in registers for other users.
13146           (TV->hasOneUse() || FV->hasOneUse())) {
13147         Constant *Elts[] = {
13148           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13149           const_cast<ConstantFP*>(TV->getConstantFPValue())
13150         };
13151         Type *FPTy = Elts[0]->getType();
13152         const DataLayout &TD = *TLI.getDataLayout();
13153
13154         // Create a ConstantArray of the two constants.
13155         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13156         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13157                                             TD.getPrefTypeAlignment(FPTy));
13158         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13159
13160         // Get the offsets to the 0 and 1 element of the array so that we can
13161         // select between them.
13162         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13163         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13164         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13165
13166         SDValue Cond = DAG.getSetCC(DL,
13167                                     getSetCCResultType(N0.getValueType()),
13168                                     N0, N1, CC);
13169         AddToWorklist(Cond.getNode());
13170         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13171                                           Cond, One, Zero);
13172         AddToWorklist(CstOffset.getNode());
13173         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13174                             CstOffset);
13175         AddToWorklist(CPIdx.getNode());
13176         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13177                            MachinePointerInfo::getConstantPool(), false,
13178                            false, false, Alignment);
13179       }
13180     }
13181
13182   // Check to see if we can perform the "gzip trick", transforming
13183   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13184   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13185       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13186        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13187     EVT XType = N0.getValueType();
13188     EVT AType = N2.getValueType();
13189     if (XType.bitsGE(AType)) {
13190       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13191       // single-bit constant.
13192       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13193         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13194         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13195         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13196                                        getShiftAmountTy(N0.getValueType()));
13197         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13198                                     XType, N0, ShCt);
13199         AddToWorklist(Shift.getNode());
13200
13201         if (XType.bitsGT(AType)) {
13202           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13203           AddToWorklist(Shift.getNode());
13204         }
13205
13206         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13207       }
13208
13209       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13210                                   XType, N0,
13211                                   DAG.getConstant(XType.getSizeInBits() - 1,
13212                                                   SDLoc(N0),
13213                                          getShiftAmountTy(N0.getValueType())));
13214       AddToWorklist(Shift.getNode());
13215
13216       if (XType.bitsGT(AType)) {
13217         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13218         AddToWorklist(Shift.getNode());
13219       }
13220
13221       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13222     }
13223   }
13224
13225   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13226   // where y is has a single bit set.
13227   // A plaintext description would be, we can turn the SELECT_CC into an AND
13228   // when the condition can be materialized as an all-ones register.  Any
13229   // single bit-test can be materialized as an all-ones register with
13230   // shift-left and shift-right-arith.
13231   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13232       N0->getValueType(0) == VT &&
13233       N1C && N1C->isNullValue() &&
13234       N2C && N2C->isNullValue()) {
13235     SDValue AndLHS = N0->getOperand(0);
13236     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13237     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13238       // Shift the tested bit over the sign bit.
13239       APInt AndMask = ConstAndRHS->getAPIntValue();
13240       SDValue ShlAmt =
13241         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13242                         getShiftAmountTy(AndLHS.getValueType()));
13243       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13244
13245       // Now arithmetic right shift it all the way over, so the result is either
13246       // all-ones, or zero.
13247       SDValue ShrAmt =
13248         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13249                         getShiftAmountTy(Shl.getValueType()));
13250       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13251
13252       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13253     }
13254   }
13255
13256   // fold select C, 16, 0 -> shl C, 4
13257   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13258       TLI.getBooleanContents(N0.getValueType()) ==
13259           TargetLowering::ZeroOrOneBooleanContent) {
13260
13261     // If the caller doesn't want us to simplify this into a zext of a compare,
13262     // don't do it.
13263     if (NotExtCompare && N2C->getAPIntValue() == 1)
13264       return SDValue();
13265
13266     // Get a SetCC of the condition
13267     // NOTE: Don't create a SETCC if it's not legal on this target.
13268     if (!LegalOperations ||
13269         TLI.isOperationLegal(ISD::SETCC,
13270           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13271       SDValue Temp, SCC;
13272       // cast from setcc result type to select result type
13273       if (LegalTypes) {
13274         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13275                             N0, N1, CC);
13276         if (N2.getValueType().bitsLT(SCC.getValueType()))
13277           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13278                                         N2.getValueType());
13279         else
13280           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13281                              N2.getValueType(), SCC);
13282       } else {
13283         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13284         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13285                            N2.getValueType(), SCC);
13286       }
13287
13288       AddToWorklist(SCC.getNode());
13289       AddToWorklist(Temp.getNode());
13290
13291       if (N2C->getAPIntValue() == 1)
13292         return Temp;
13293
13294       // shl setcc result by log2 n2c
13295       return DAG.getNode(
13296           ISD::SHL, DL, N2.getValueType(), Temp,
13297           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13298                           getShiftAmountTy(Temp.getValueType())));
13299     }
13300   }
13301
13302   // Check to see if this is the equivalent of setcc
13303   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13304   // otherwise, go ahead with the folds.
13305   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13306     EVT XType = N0.getValueType();
13307     if (!LegalOperations ||
13308         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13309       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13310       if (Res.getValueType() != VT)
13311         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13312       return Res;
13313     }
13314
13315     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13316     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13317         (!LegalOperations ||
13318          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13319       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13320       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13321                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13322                                          SDLoc(Ctlz),
13323                                        getShiftAmountTy(Ctlz.getValueType())));
13324     }
13325     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13326     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13327       SDLoc DL(N0);
13328       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13329                                   XType, DAG.getConstant(0, DL, XType), N0);
13330       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13331       return DAG.getNode(ISD::SRL, DL, XType,
13332                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13333                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13334                                          getShiftAmountTy(XType)));
13335     }
13336     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13337     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13338       SDLoc DL(N0);
13339       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13340                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13341                                          getShiftAmountTy(N0.getValueType())));
13342       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13343                                                                     XType));
13344     }
13345   }
13346
13347   // Check to see if this is an integer abs.
13348   // select_cc setg[te] X,  0,  X, -X ->
13349   // select_cc setgt    X, -1,  X, -X ->
13350   // select_cc setl[te] X,  0, -X,  X ->
13351   // select_cc setlt    X,  1, -X,  X ->
13352   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13353   if (N1C) {
13354     ConstantSDNode *SubC = nullptr;
13355     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13356          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13357         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13358       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13359     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13360               (N1C->isOne() && CC == ISD::SETLT)) &&
13361              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13362       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13363
13364     EVT XType = N0.getValueType();
13365     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13366       SDLoc DL(N0);
13367       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13368                                   N0,
13369                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13370                                          getShiftAmountTy(N0.getValueType())));
13371       SDValue Add = DAG.getNode(ISD::ADD, DL,
13372                                 XType, N0, Shift);
13373       AddToWorklist(Shift.getNode());
13374       AddToWorklist(Add.getNode());
13375       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13376     }
13377   }
13378
13379   return SDValue();
13380 }
13381
13382 /// This is a stub for TargetLowering::SimplifySetCC.
13383 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13384                                    SDValue N1, ISD::CondCode Cond,
13385                                    SDLoc DL, bool foldBooleans) {
13386   TargetLowering::DAGCombinerInfo
13387     DagCombineInfo(DAG, Level, false, this);
13388   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13389 }
13390
13391 /// Given an ISD::SDIV node expressing a divide by constant, return
13392 /// a DAG expression to select that will generate the same value by multiplying
13393 /// by a magic number.
13394 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13395 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13396   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13397   if (!C)
13398     return SDValue();
13399
13400   // Avoid division by zero.
13401   if (!C->getAPIntValue())
13402     return SDValue();
13403
13404   std::vector<SDNode*> Built;
13405   SDValue S =
13406       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13407
13408   for (SDNode *N : Built)
13409     AddToWorklist(N);
13410   return S;
13411 }
13412
13413 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13414 /// DAG expression that will generate the same value by right shifting.
13415 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13416   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13417   if (!C)
13418     return SDValue();
13419
13420   // Avoid division by zero.
13421   if (!C->getAPIntValue())
13422     return SDValue();
13423
13424   std::vector<SDNode *> Built;
13425   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13426
13427   for (SDNode *N : Built)
13428     AddToWorklist(N);
13429   return S;
13430 }
13431
13432 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13433 /// expression that will generate the same value by multiplying by a magic
13434 /// number.
13435 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13436 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13437   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13438   if (!C)
13439     return SDValue();
13440
13441   // Avoid division by zero.
13442   if (!C->getAPIntValue())
13443     return SDValue();
13444
13445   std::vector<SDNode*> Built;
13446   SDValue S =
13447       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13448
13449   for (SDNode *N : Built)
13450     AddToWorklist(N);
13451   return S;
13452 }
13453
13454 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13455   if (Level >= AfterLegalizeDAG)
13456     return SDValue();
13457
13458   // Expose the DAG combiner to the target combiner implementations.
13459   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13460
13461   unsigned Iterations = 0;
13462   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13463     if (Iterations) {
13464       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13465       // For the reciprocal, we need to find the zero of the function:
13466       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13467       //     =>
13468       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13469       //     does not require additional intermediate precision]
13470       EVT VT = Op.getValueType();
13471       SDLoc DL(Op);
13472       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13473
13474       AddToWorklist(Est.getNode());
13475
13476       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13477       for (unsigned i = 0; i < Iterations; ++i) {
13478         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13479         AddToWorklist(NewEst.getNode());
13480
13481         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13482         AddToWorklist(NewEst.getNode());
13483
13484         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13485         AddToWorklist(NewEst.getNode());
13486
13487         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13488         AddToWorklist(Est.getNode());
13489       }
13490     }
13491     return Est;
13492   }
13493
13494   return SDValue();
13495 }
13496
13497 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13498 /// For the reciprocal sqrt, we need to find the zero of the function:
13499 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13500 ///     =>
13501 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13502 /// As a result, we precompute A/2 prior to the iteration loop.
13503 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13504                                           unsigned Iterations) {
13505   EVT VT = Arg.getValueType();
13506   SDLoc DL(Arg);
13507   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13508
13509   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13510   // this entire sequence requires only one FP constant.
13511   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13512   AddToWorklist(HalfArg.getNode());
13513
13514   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13515   AddToWorklist(HalfArg.getNode());
13516
13517   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13518   for (unsigned i = 0; i < Iterations; ++i) {
13519     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13520     AddToWorklist(NewEst.getNode());
13521
13522     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13523     AddToWorklist(NewEst.getNode());
13524
13525     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13526     AddToWorklist(NewEst.getNode());
13527
13528     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13529     AddToWorklist(Est.getNode());
13530   }
13531   return Est;
13532 }
13533
13534 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13535 /// For the reciprocal sqrt, we need to find the zero of the function:
13536 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13537 ///     =>
13538 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13539 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13540                                           unsigned Iterations) {
13541   EVT VT = Arg.getValueType();
13542   SDLoc DL(Arg);
13543   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13544   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13545
13546   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13547   for (unsigned i = 0; i < Iterations; ++i) {
13548     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13549     AddToWorklist(HalfEst.getNode());
13550
13551     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13552     AddToWorklist(Est.getNode());
13553
13554     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13555     AddToWorklist(Est.getNode());
13556
13557     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13558     AddToWorklist(Est.getNode());
13559
13560     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13561     AddToWorklist(Est.getNode());
13562   }
13563   return Est;
13564 }
13565
13566 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13567   if (Level >= AfterLegalizeDAG)
13568     return SDValue();
13569
13570   // Expose the DAG combiner to the target combiner implementations.
13571   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13572   unsigned Iterations = 0;
13573   bool UseOneConstNR = false;
13574   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13575     AddToWorklist(Est.getNode());
13576     if (Iterations) {
13577       Est = UseOneConstNR ?
13578         BuildRsqrtNROneConst(Op, Est, Iterations) :
13579         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13580     }
13581     return Est;
13582   }
13583
13584   return SDValue();
13585 }
13586
13587 /// Return true if base is a frame index, which is known not to alias with
13588 /// anything but itself.  Provides base object and offset as results.
13589 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13590                            const GlobalValue *&GV, const void *&CV) {
13591   // Assume it is a primitive operation.
13592   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13593
13594   // If it's an adding a simple constant then integrate the offset.
13595   if (Base.getOpcode() == ISD::ADD) {
13596     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13597       Base = Base.getOperand(0);
13598       Offset += C->getZExtValue();
13599     }
13600   }
13601
13602   // Return the underlying GlobalValue, and update the Offset.  Return false
13603   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13604   // by multiple nodes with different offsets.
13605   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13606     GV = G->getGlobal();
13607     Offset += G->getOffset();
13608     return false;
13609   }
13610
13611   // Return the underlying Constant value, and update the Offset.  Return false
13612   // for ConstantSDNodes since the same constant pool entry may be represented
13613   // by multiple nodes with different offsets.
13614   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13615     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13616                                          : (const void *)C->getConstVal();
13617     Offset += C->getOffset();
13618     return false;
13619   }
13620   // If it's any of the following then it can't alias with anything but itself.
13621   return isa<FrameIndexSDNode>(Base);
13622 }
13623
13624 /// Return true if there is any possibility that the two addresses overlap.
13625 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13626   // If they are the same then they must be aliases.
13627   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13628
13629   // If they are both volatile then they cannot be reordered.
13630   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13631
13632   // Gather base node and offset information.
13633   SDValue Base1, Base2;
13634   int64_t Offset1, Offset2;
13635   const GlobalValue *GV1, *GV2;
13636   const void *CV1, *CV2;
13637   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13638                                       Base1, Offset1, GV1, CV1);
13639   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13640                                       Base2, Offset2, GV2, CV2);
13641
13642   // If they have a same base address then check to see if they overlap.
13643   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13644     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13645              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13646
13647   // It is possible for different frame indices to alias each other, mostly
13648   // when tail call optimization reuses return address slots for arguments.
13649   // To catch this case, look up the actual index of frame indices to compute
13650   // the real alias relationship.
13651   if (isFrameIndex1 && isFrameIndex2) {
13652     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13653     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13654     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13655     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13656              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13657   }
13658
13659   // Otherwise, if we know what the bases are, and they aren't identical, then
13660   // we know they cannot alias.
13661   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13662     return false;
13663
13664   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13665   // compared to the size and offset of the access, we may be able to prove they
13666   // do not alias.  This check is conservative for now to catch cases created by
13667   // splitting vector types.
13668   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13669       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13670       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13671        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13672       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13673     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13674     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13675
13676     // There is no overlap between these relatively aligned accesses of similar
13677     // size, return no alias.
13678     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13679         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13680       return false;
13681   }
13682
13683   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13684                    ? CombinerGlobalAA
13685                    : DAG.getSubtarget().useAA();
13686 #ifndef NDEBUG
13687   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13688       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13689     UseAA = false;
13690 #endif
13691   if (UseAA &&
13692       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13693     // Use alias analysis information.
13694     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13695                                  Op1->getSrcValueOffset());
13696     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13697         Op0->getSrcValueOffset() - MinOffset;
13698     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13699         Op1->getSrcValueOffset() - MinOffset;
13700     AliasAnalysis::AliasResult AAResult =
13701         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13702                                          Overlap1,
13703                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13704                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13705                                          Overlap2,
13706                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13707     if (AAResult == AliasAnalysis::NoAlias)
13708       return false;
13709   }
13710
13711   // Otherwise we have to assume they alias.
13712   return true;
13713 }
13714
13715 /// Walk up chain skipping non-aliasing memory nodes,
13716 /// looking for aliasing nodes and adding them to the Aliases vector.
13717 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13718                                    SmallVectorImpl<SDValue> &Aliases) {
13719   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13720   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13721
13722   // Get alias information for node.
13723   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13724
13725   // Starting off.
13726   Chains.push_back(OriginalChain);
13727   unsigned Depth = 0;
13728
13729   // Look at each chain and determine if it is an alias.  If so, add it to the
13730   // aliases list.  If not, then continue up the chain looking for the next
13731   // candidate.
13732   while (!Chains.empty()) {
13733     SDValue Chain = Chains.back();
13734     Chains.pop_back();
13735
13736     // For TokenFactor nodes, look at each operand and only continue up the
13737     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13738     // find more and revert to original chain since the xform is unlikely to be
13739     // profitable.
13740     //
13741     // FIXME: The depth check could be made to return the last non-aliasing
13742     // chain we found before we hit a tokenfactor rather than the original
13743     // chain.
13744     if (Depth > 6 || Aliases.size() == 2) {
13745       Aliases.clear();
13746       Aliases.push_back(OriginalChain);
13747       return;
13748     }
13749
13750     // Don't bother if we've been before.
13751     if (!Visited.insert(Chain.getNode()).second)
13752       continue;
13753
13754     switch (Chain.getOpcode()) {
13755     case ISD::EntryToken:
13756       // Entry token is ideal chain operand, but handled in FindBetterChain.
13757       break;
13758
13759     case ISD::LOAD:
13760     case ISD::STORE: {
13761       // Get alias information for Chain.
13762       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13763           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13764
13765       // If chain is alias then stop here.
13766       if (!(IsLoad && IsOpLoad) &&
13767           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13768         Aliases.push_back(Chain);
13769       } else {
13770         // Look further up the chain.
13771         Chains.push_back(Chain.getOperand(0));
13772         ++Depth;
13773       }
13774       break;
13775     }
13776
13777     case ISD::TokenFactor:
13778       // We have to check each of the operands of the token factor for "small"
13779       // token factors, so we queue them up.  Adding the operands to the queue
13780       // (stack) in reverse order maintains the original order and increases the
13781       // likelihood that getNode will find a matching token factor (CSE.)
13782       if (Chain.getNumOperands() > 16) {
13783         Aliases.push_back(Chain);
13784         break;
13785       }
13786       for (unsigned n = Chain.getNumOperands(); n;)
13787         Chains.push_back(Chain.getOperand(--n));
13788       ++Depth;
13789       break;
13790
13791     default:
13792       // For all other instructions we will just have to take what we can get.
13793       Aliases.push_back(Chain);
13794       break;
13795     }
13796   }
13797
13798   // We need to be careful here to also search for aliases through the
13799   // value operand of a store, etc. Consider the following situation:
13800   //   Token1 = ...
13801   //   L1 = load Token1, %52
13802   //   S1 = store Token1, L1, %51
13803   //   L2 = load Token1, %52+8
13804   //   S2 = store Token1, L2, %51+8
13805   //   Token2 = Token(S1, S2)
13806   //   L3 = load Token2, %53
13807   //   S3 = store Token2, L3, %52
13808   //   L4 = load Token2, %53+8
13809   //   S4 = store Token2, L4, %52+8
13810   // If we search for aliases of S3 (which loads address %52), and we look
13811   // only through the chain, then we'll miss the trivial dependence on L1
13812   // (which also loads from %52). We then might change all loads and
13813   // stores to use Token1 as their chain operand, which could result in
13814   // copying %53 into %52 before copying %52 into %51 (which should
13815   // happen first).
13816   //
13817   // The problem is, however, that searching for such data dependencies
13818   // can become expensive, and the cost is not directly related to the
13819   // chain depth. Instead, we'll rule out such configurations here by
13820   // insisting that we've visited all chain users (except for users
13821   // of the original chain, which is not necessary). When doing this,
13822   // we need to look through nodes we don't care about (otherwise, things
13823   // like register copies will interfere with trivial cases).
13824
13825   SmallVector<const SDNode *, 16> Worklist;
13826   for (const SDNode *N : Visited)
13827     if (N != OriginalChain.getNode())
13828       Worklist.push_back(N);
13829
13830   while (!Worklist.empty()) {
13831     const SDNode *M = Worklist.pop_back_val();
13832
13833     // We have already visited M, and want to make sure we've visited any uses
13834     // of M that we care about. For uses that we've not visisted, and don't
13835     // care about, queue them to the worklist.
13836
13837     for (SDNode::use_iterator UI = M->use_begin(),
13838          UIE = M->use_end(); UI != UIE; ++UI)
13839       if (UI.getUse().getValueType() == MVT::Other &&
13840           Visited.insert(*UI).second) {
13841         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13842           // We've not visited this use, and we care about it (it could have an
13843           // ordering dependency with the original node).
13844           Aliases.clear();
13845           Aliases.push_back(OriginalChain);
13846           return;
13847         }
13848
13849         // We've not visited this use, but we don't care about it. Mark it as
13850         // visited and enqueue it to the worklist.
13851         Worklist.push_back(*UI);
13852       }
13853   }
13854 }
13855
13856 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13857 /// (aliasing node.)
13858 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13859   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13860
13861   // Accumulate all the aliases to this node.
13862   GatherAllAliases(N, OldChain, Aliases);
13863
13864   // If no operands then chain to entry token.
13865   if (Aliases.size() == 0)
13866     return DAG.getEntryNode();
13867
13868   // If a single operand then chain to it.  We don't need to revisit it.
13869   if (Aliases.size() == 1)
13870     return Aliases[0];
13871
13872   // Construct a custom tailored token factor.
13873   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13874 }
13875
13876 /// This is the entry point for the file.
13877 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13878                            CodeGenOpt::Level OptLevel) {
13879   /// This is the main entry point to this class.
13880   DAGCombiner(*this, AA, OptLevel).Run(Level);
13881 }