Combining DIV+REM->DIVREM doesn't belong in LegalizeDAG; move it over into DAGCombiner.
[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     /// Replaces all uses of the results of one DAG node with new values.
160     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
161                       bool AddTo = true);
162
163     /// Replaces all uses of the results of one DAG node with new values.
164     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
165       return CombineTo(N, &Res, 1, AddTo);
166     }
167
168     /// Replaces all uses of the results of one DAG node with new values.
169     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
170                       bool AddTo = true) {
171       SDValue To[] = { Res0, Res1 };
172       return CombineTo(N, To, 2, AddTo);
173     }
174
175     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176
177   private:
178
179     /// Check the specified integer node value to see if it can be simplified or
180     /// if things it uses can be simplified by bit propagation.
181     /// If so, return true.
182     bool SimplifyDemandedBits(SDValue Op) {
183       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
184       APInt Demanded = APInt::getAllOnesValue(BitWidth);
185       return SimplifyDemandedBits(Op, Demanded);
186     }
187
188     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
189
190     bool CombineToPreIndexedLoadStore(SDNode *N);
191     bool CombineToPostIndexedLoadStore(SDNode *N);
192     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
193     bool SliceUpLoad(SDNode *N);
194
195     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
196     ///   load.
197     ///
198     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
199     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
200     /// \param EltNo index of the vector element to load.
201     /// \param OriginalLoad load that EVE came from to be replaced.
202     /// \returns EVE on success SDValue() on failure.
203     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
204         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
205     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
206     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
207     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
208     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
209     SDValue PromoteIntBinOp(SDValue Op);
210     SDValue PromoteIntShiftOp(SDValue Op);
211     SDValue PromoteExtend(SDValue Op);
212     bool PromoteLoad(SDValue Op);
213
214     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
215                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
216                          ISD::NodeType ExtType);
217
218     /// Call the node-specific routine that knows how to fold each
219     /// particular type of node. If that doesn't do anything, try the
220     /// target-specific DAG combines.
221     SDValue combine(SDNode *N);
222
223     // Visitation implementation - Implement dag node combining for different
224     // node types.  The semantics are as follows:
225     // Return Value:
226     //   SDValue.getNode() == 0 - No change was made
227     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
228     //   otherwise              - N should be replaced by the returned Operand.
229     //
230     SDValue visitTokenFactor(SDNode *N);
231     SDValue visitMERGE_VALUES(SDNode *N);
232     SDValue visitADD(SDNode *N);
233     SDValue visitSUB(SDNode *N);
234     SDValue visitADDC(SDNode *N);
235     SDValue visitSUBC(SDNode *N);
236     SDValue visitADDE(SDNode *N);
237     SDValue visitSUBE(SDNode *N);
238     SDValue visitMUL(SDNode *N);
239     SDValue useDivRem(SDNode *N);
240     SDValue visitSDIV(SDNode *N);
241     SDValue visitUDIV(SDNode *N);
242     SDValue visitREM(SDNode *N);
243     SDValue visitMULHU(SDNode *N);
244     SDValue visitMULHS(SDNode *N);
245     SDValue visitSMUL_LOHI(SDNode *N);
246     SDValue visitUMUL_LOHI(SDNode *N);
247     SDValue visitSMULO(SDNode *N);
248     SDValue visitUMULO(SDNode *N);
249     SDValue visitIMINMAX(SDNode *N);
250     SDValue visitAND(SDNode *N);
251     SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitOR(SDNode *N);
253     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
254     SDValue visitXOR(SDNode *N);
255     SDValue SimplifyVBinOp(SDNode *N);
256     SDValue visitSHL(SDNode *N);
257     SDValue visitSRA(SDNode *N);
258     SDValue visitSRL(SDNode *N);
259     SDValue visitRotate(SDNode *N);
260     SDValue visitBSWAP(SDNode *N);
261     SDValue visitCTLZ(SDNode *N);
262     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
263     SDValue visitCTTZ(SDNode *N);
264     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
265     SDValue visitCTPOP(SDNode *N);
266     SDValue visitSELECT(SDNode *N);
267     SDValue visitVSELECT(SDNode *N);
268     SDValue visitSELECT_CC(SDNode *N);
269     SDValue visitSETCC(SDNode *N);
270     SDValue visitSIGN_EXTEND(SDNode *N);
271     SDValue visitZERO_EXTEND(SDNode *N);
272     SDValue visitANY_EXTEND(SDNode *N);
273     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
274     SDValue visitSIGN_EXTEND_VECTOR_INREG(SDNode *N);
275     SDValue visitTRUNCATE(SDNode *N);
276     SDValue visitBITCAST(SDNode *N);
277     SDValue visitBUILD_PAIR(SDNode *N);
278     SDValue visitFADD(SDNode *N);
279     SDValue visitFSUB(SDNode *N);
280     SDValue visitFMUL(SDNode *N);
281     SDValue visitFMA(SDNode *N);
282     SDValue visitFDIV(SDNode *N);
283     SDValue visitFREM(SDNode *N);
284     SDValue visitFSQRT(SDNode *N);
285     SDValue visitFCOPYSIGN(SDNode *N);
286     SDValue visitSINT_TO_FP(SDNode *N);
287     SDValue visitUINT_TO_FP(SDNode *N);
288     SDValue visitFP_TO_SINT(SDNode *N);
289     SDValue visitFP_TO_UINT(SDNode *N);
290     SDValue visitFP_ROUND(SDNode *N);
291     SDValue visitFP_ROUND_INREG(SDNode *N);
292     SDValue visitFP_EXTEND(SDNode *N);
293     SDValue visitFNEG(SDNode *N);
294     SDValue visitFABS(SDNode *N);
295     SDValue visitFCEIL(SDNode *N);
296     SDValue visitFTRUNC(SDNode *N);
297     SDValue visitFFLOOR(SDNode *N);
298     SDValue visitFMINNUM(SDNode *N);
299     SDValue visitFMAXNUM(SDNode *N);
300     SDValue visitBRCOND(SDNode *N);
301     SDValue visitBR_CC(SDNode *N);
302     SDValue visitLOAD(SDNode *N);
303
304     SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
305     SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
306
307     SDValue visitSTORE(SDNode *N);
308     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
309     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
310     SDValue visitBUILD_VECTOR(SDNode *N);
311     SDValue visitCONCAT_VECTORS(SDNode *N);
312     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
313     SDValue visitVECTOR_SHUFFLE(SDNode *N);
314     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
315     SDValue visitINSERT_SUBVECTOR(SDNode *N);
316     SDValue visitMLOAD(SDNode *N);
317     SDValue visitMSTORE(SDNode *N);
318     SDValue visitMGATHER(SDNode *N);
319     SDValue visitMSCATTER(SDNode *N);
320     SDValue visitFP_TO_FP16(SDNode *N);
321     SDValue visitFP16_TO_FP(SDNode *N);
322
323     SDValue visitFADDForFMACombine(SDNode *N);
324     SDValue visitFSUBForFMACombine(SDNode *N);
325     SDValue visitFMULForFMACombine(SDNode *N);
326
327     SDValue XformToShuffleWithZero(SDNode *N);
328     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
329
330     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
331
332     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
333     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
334     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
335     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
336                              SDValue N3, ISD::CondCode CC,
337                              bool NotExtCompare = false);
338     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
339                           SDLoc DL, bool foldBooleans = true);
340
341     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
342                            SDValue &CC) const;
343     bool isOneUseSetCC(SDValue N) const;
344
345     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
346                                          unsigned HiOp);
347     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
348     SDValue CombineExtLoad(SDNode *N);
349     SDValue combineRepeatedFPDivisors(SDNode *N);
350     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
351     SDValue BuildSDIV(SDNode *N);
352     SDValue BuildSDIVPow2(SDNode *N);
353     SDValue BuildUDIV(SDNode *N);
354     SDValue BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags);
355     SDValue BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags);
356     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations,
357                                  SDNodeFlags *Flags);
358     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations,
359                                  SDNodeFlags *Flags);
360     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
361                                bool DemandHighBits = true);
362     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
363     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
364                               SDValue InnerPos, SDValue InnerNeg,
365                               unsigned PosOpcode, unsigned NegOpcode,
366                               SDLoc DL);
367     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
368     SDValue ReduceLoadWidth(SDNode *N);
369     SDValue ReduceLoadOpStoreWidth(SDNode *N);
370     SDValue TransformFPLoadStorePair(SDNode *N);
371     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
372     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
373
374     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
375
376     /// Walk up chain skipping non-aliasing memory nodes,
377     /// looking for aliasing nodes and adding them to the Aliases vector.
378     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
379                           SmallVectorImpl<SDValue> &Aliases);
380
381     /// Return true if there is any possibility that the two addresses overlap.
382     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
383
384     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
385     /// chain (aliasing node.)
386     SDValue FindBetterChain(SDNode *N, SDValue Chain);
387
388     /// Do FindBetterChain for a store and any possibly adjacent stores on
389     /// consecutive chains.
390     bool findBetterNeighborChains(StoreSDNode *St);
391
392     /// Holds a pointer to an LSBaseSDNode as well as information on where it
393     /// is located in a sequence of memory operations connected by a chain.
394     struct MemOpLink {
395       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
396       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
397       // Ptr to the mem node.
398       LSBaseSDNode *MemNode;
399       // Offset from the base ptr.
400       int64_t OffsetFromBase;
401       // What is the sequence number of this mem node.
402       // Lowest mem operand in the DAG starts at zero.
403       unsigned SequenceNum;
404     };
405
406     /// This is a helper function for MergeStoresOfConstantsOrVecElts. Returns a
407     /// constant build_vector of the stored constant values in Stores.
408     SDValue getMergedConstantVectorStore(SelectionDAG &DAG,
409                                          SDLoc SL,
410                                          ArrayRef<MemOpLink> Stores,
411                                          SmallVectorImpl<SDValue> &Chains,
412                                          EVT Ty) const;
413
414     /// This is a helper function for MergeConsecutiveStores. When the source
415     /// elements of the consecutive stores are all constants or all extracted
416     /// vector elements, try to merge them into one larger store.
417     /// \return True if a merged store was created.
418     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
419                                          EVT MemVT, unsigned NumStores,
420                                          bool IsConstantSrc, bool UseVector);
421
422     /// This is a helper function for MergeConsecutiveStores.
423     /// Stores that may be merged are placed in StoreNodes.
424     /// Loads that may alias with those stores are placed in AliasLoadNodes.
425     void getStoreMergeAndAliasCandidates(
426         StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
427         SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes);
428
429     /// Merge consecutive store operations into a wide store.
430     /// This optimization uses wide integers or vectors when possible.
431     /// \return True if some memory operations were changed.
432     bool MergeConsecutiveStores(StoreSDNode *N);
433
434     /// \brief Try to transform a truncation where C is a constant:
435     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
436     ///
437     /// \p N needs to be a truncation and its first operand an AND. Other
438     /// requirements are checked by the function (e.g. that trunc is
439     /// single-use) and if missed an empty SDValue is returned.
440     SDValue distributeTruncateThroughAnd(SDNode *N);
441
442   public:
443     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
444         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
445           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
446       ForCodeSize = DAG.getMachineFunction().getFunction()->optForSize();
447     }
448
449     /// Runs the dag combiner on all nodes in the work list
450     void Run(CombineLevel AtLevel);
451
452     SelectionDAG &getDAG() const { return DAG; }
453
454     /// Returns a type large enough to hold any valid shift amount - before type
455     /// legalization these can be huge.
456     EVT getShiftAmountTy(EVT LHSTy) {
457       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
458       if (LHSTy.isVector())
459         return LHSTy;
460       auto &DL = DAG.getDataLayout();
461       return LegalTypes ? TLI.getScalarShiftAmountTy(DL, LHSTy)
462                         : TLI.getPointerTy(DL);
463     }
464
465     /// This method returns true if we are running before type legalization or
466     /// if the specified VT is legal.
467     bool isTypeLegal(const EVT &VT) {
468       if (!LegalTypes) return true;
469       return TLI.isTypeLegal(VT);
470     }
471
472     /// Convenience wrapper around TargetLowering::getSetCCResultType
473     EVT getSetCCResultType(EVT VT) const {
474       return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
475     }
476   };
477 }
478
479
480 namespace {
481 /// This class is a DAGUpdateListener that removes any deleted
482 /// nodes from the worklist.
483 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
484   DAGCombiner &DC;
485 public:
486   explicit WorklistRemover(DAGCombiner &dc)
487     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
488
489   void NodeDeleted(SDNode *N, SDNode *E) override {
490     DC.removeFromWorklist(N);
491   }
492 };
493 }
494
495 //===----------------------------------------------------------------------===//
496 //  TargetLowering::DAGCombinerInfo implementation
497 //===----------------------------------------------------------------------===//
498
499 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
500   ((DAGCombiner*)DC)->AddToWorklist(N);
501 }
502
503 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
504   ((DAGCombiner*)DC)->removeFromWorklist(N);
505 }
506
507 SDValue TargetLowering::DAGCombinerInfo::
508 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
509   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
510 }
511
512 SDValue TargetLowering::DAGCombinerInfo::
513 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
514   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
515 }
516
517
518 SDValue TargetLowering::DAGCombinerInfo::
519 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
520   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
521 }
522
523 void TargetLowering::DAGCombinerInfo::
524 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
525   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
526 }
527
528 //===----------------------------------------------------------------------===//
529 // Helper Functions
530 //===----------------------------------------------------------------------===//
531
532 void DAGCombiner::deleteAndRecombine(SDNode *N) {
533   removeFromWorklist(N);
534
535   // If the operands of this node are only used by the node, they will now be
536   // dead. Make sure to re-visit them and recursively delete dead nodes.
537   for (const SDValue &Op : N->ops())
538     // For an operand generating multiple values, one of the values may
539     // become dead allowing further simplification (e.g. split index
540     // arithmetic from an indexed load).
541     if (Op->hasOneUse() || Op->getNumValues() > 1)
542       AddToWorklist(Op.getNode());
543
544   DAG.DeleteNode(N);
545 }
546
547 /// Return 1 if we can compute the negated form of the specified expression for
548 /// the same cost as the expression itself, or 2 if we can compute the negated
549 /// form more cheaply than the expression itself.
550 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
551                                const TargetLowering &TLI,
552                                const TargetOptions *Options,
553                                unsigned Depth = 0) {
554   // fneg is removable even if it has multiple uses.
555   if (Op.getOpcode() == ISD::FNEG) return 2;
556
557   // Don't allow anything with multiple uses.
558   if (!Op.hasOneUse()) return 0;
559
560   // Don't recurse exponentially.
561   if (Depth > 6) return 0;
562
563   switch (Op.getOpcode()) {
564   default: return false;
565   case ISD::ConstantFP:
566     // Don't invert constant FP values after legalize.  The negated constant
567     // isn't necessarily legal.
568     return LegalOperations ? 0 : 1;
569   case ISD::FADD:
570     // FIXME: determine better conditions for this xform.
571     if (!Options->UnsafeFPMath) return 0;
572
573     // After operation legalization, it might not be legal to create new FSUBs.
574     if (LegalOperations &&
575         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
576       return 0;
577
578     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
579     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
580                                     Options, Depth + 1))
581       return V;
582     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
584                               Depth + 1);
585   case ISD::FSUB:
586     // We can't turn -(A-B) into B-A when we honor signed zeros.
587     if (!Options->UnsafeFPMath) return 0;
588
589     // fold (fneg (fsub A, B)) -> (fsub B, A)
590     return 1;
591
592   case ISD::FMUL:
593   case ISD::FDIV:
594     if (Options->HonorSignDependentRoundingFPMath()) return 0;
595
596     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
597     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
598                                     Options, Depth + 1))
599       return V;
600
601     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
602                               Depth + 1);
603
604   case ISD::FP_EXTEND:
605   case ISD::FP_ROUND:
606   case ISD::FSIN:
607     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
608                               Depth + 1);
609   }
610 }
611
612 /// If isNegatibleForFree returns true, return the newly negated expression.
613 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
614                                     bool LegalOperations, unsigned Depth = 0) {
615   const TargetOptions &Options = DAG.getTarget().Options;
616   // fneg is removable even if it has multiple uses.
617   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
618
619   // Don't allow anything with multiple uses.
620   assert(Op.hasOneUse() && "Unknown reuse!");
621
622   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
623
624   const SDNodeFlags *Flags = Op.getNode()->getFlags();
625
626   switch (Op.getOpcode()) {
627   default: llvm_unreachable("Unknown code");
628   case ISD::ConstantFP: {
629     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
630     V.changeSign();
631     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
632   }
633   case ISD::FADD:
634     // FIXME: determine better conditions for this xform.
635     assert(Options.UnsafeFPMath);
636
637     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
638     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
639                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
640       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
641                          GetNegatedExpression(Op.getOperand(0), DAG,
642                                               LegalOperations, Depth+1),
643                          Op.getOperand(1), Flags);
644     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
645     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
646                        GetNegatedExpression(Op.getOperand(1), DAG,
647                                             LegalOperations, Depth+1),
648                        Op.getOperand(0), Flags);
649   case ISD::FSUB:
650     // We can't turn -(A-B) into B-A when we honor signed zeros.
651     assert(Options.UnsafeFPMath);
652
653     // fold (fneg (fsub 0, B)) -> B
654     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
655       if (N0CFP->isZero())
656         return Op.getOperand(1);
657
658     // fold (fneg (fsub A, B)) -> (fsub B, A)
659     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
660                        Op.getOperand(1), Op.getOperand(0), Flags);
661
662   case ISD::FMUL:
663   case ISD::FDIV:
664     assert(!Options.HonorSignDependentRoundingFPMath());
665
666     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
667     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
668                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
669       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
670                          GetNegatedExpression(Op.getOperand(0), DAG,
671                                               LegalOperations, Depth+1),
672                          Op.getOperand(1), Flags);
673
674     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
675     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
676                        Op.getOperand(0),
677                        GetNegatedExpression(Op.getOperand(1), DAG,
678                                             LegalOperations, Depth+1), Flags);
679
680   case ISD::FP_EXTEND:
681   case ISD::FSIN:
682     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
683                        GetNegatedExpression(Op.getOperand(0), DAG,
684                                             LegalOperations, Depth+1));
685   case ISD::FP_ROUND:
686       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
687                          GetNegatedExpression(Op.getOperand(0), DAG,
688                                               LegalOperations, Depth+1),
689                          Op.getOperand(1));
690   }
691 }
692
693 // Return true if this node is a setcc, or is a select_cc
694 // that selects between the target values used for true and false, making it
695 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
696 // the appropriate nodes based on the type of node we are checking. This
697 // simplifies life a bit for the callers.
698 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
699                                     SDValue &CC) const {
700   if (N.getOpcode() == ISD::SETCC) {
701     LHS = N.getOperand(0);
702     RHS = N.getOperand(1);
703     CC  = N.getOperand(2);
704     return true;
705   }
706
707   if (N.getOpcode() != ISD::SELECT_CC ||
708       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
709       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
710     return false;
711
712   if (TLI.getBooleanContents(N.getValueType()) ==
713       TargetLowering::UndefinedBooleanContent)
714     return false;
715
716   LHS = N.getOperand(0);
717   RHS = N.getOperand(1);
718   CC  = N.getOperand(4);
719   return true;
720 }
721
722 /// Return true if this is a SetCC-equivalent operation with only one use.
723 /// If this is true, it allows the users to invert the operation for free when
724 /// it is profitable to do so.
725 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
726   SDValue N0, N1, N2;
727   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
728     return true;
729   return false;
730 }
731
732 /// Returns true if N is a BUILD_VECTOR node whose
733 /// elements are all the same constant or undefined.
734 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
735   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
736   if (!C)
737     return false;
738
739   APInt SplatUndef;
740   unsigned SplatBitSize;
741   bool HasAnyUndefs;
742   EVT EltVT = N->getValueType(0).getVectorElementType();
743   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
744                              HasAnyUndefs) &&
745           EltVT.getSizeInBits() >= SplatBitSize);
746 }
747
748 // \brief Returns the SDNode if it is a constant integer BuildVector
749 // or constant integer.
750 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
751   if (isa<ConstantSDNode>(N))
752     return N.getNode();
753   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
754     return N.getNode();
755   return nullptr;
756 }
757
758 // \brief Returns the SDNode if it is a constant float BuildVector
759 // or constant float.
760 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
761   if (isa<ConstantFPSDNode>(N))
762     return N.getNode();
763   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
764     return N.getNode();
765   return nullptr;
766 }
767
768 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
769 // int.
770 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
771   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
772     return CN;
773
774   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
775     BitVector UndefElements;
776     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
777
778     // BuildVectors can truncate their operands. Ignore that case here.
779     // FIXME: We blindly ignore splats which include undef which is overly
780     // pessimistic.
781     if (CN && UndefElements.none() &&
782         CN->getValueType(0) == N.getValueType().getScalarType())
783       return CN;
784   }
785
786   return nullptr;
787 }
788
789 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
790 // float.
791 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
792   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
793     return CN;
794
795   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
796     BitVector UndefElements;
797     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
798
799     if (CN && UndefElements.none())
800       return CN;
801   }
802
803   return nullptr;
804 }
805
806 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
807                                     SDValue N0, SDValue N1) {
808   EVT VT = N0.getValueType();
809   if (N0.getOpcode() == Opc) {
810     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
811       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
812         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
813         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
814           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
815         return SDValue();
816       }
817       if (N0.hasOneUse()) {
818         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
819         // use
820         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
821         if (!OpNode.getNode())
822           return SDValue();
823         AddToWorklist(OpNode.getNode());
824         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
825       }
826     }
827   }
828
829   if (N1.getOpcode() == Opc) {
830     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
831       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
832         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
833         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
834           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
835         return SDValue();
836       }
837       if (N1.hasOneUse()) {
838         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
839         // use
840         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
841         if (!OpNode.getNode())
842           return SDValue();
843         AddToWorklist(OpNode.getNode());
844         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
845       }
846     }
847   }
848
849   return SDValue();
850 }
851
852 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
853                                bool AddTo) {
854   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
855   ++NodesCombined;
856   DEBUG(dbgs() << "\nReplacing.1 ";
857         N->dump(&DAG);
858         dbgs() << "\nWith: ";
859         To[0].getNode()->dump(&DAG);
860         dbgs() << " and " << NumTo-1 << " other values\n");
861   for (unsigned i = 0, e = NumTo; i != e; ++i)
862     assert((!To[i].getNode() ||
863             N->getValueType(i) == To[i].getValueType()) &&
864            "Cannot combine value to value of different type!");
865
866   WorklistRemover DeadNodes(*this);
867   DAG.ReplaceAllUsesWith(N, To);
868   if (AddTo) {
869     // Push the new nodes and any users onto the worklist
870     for (unsigned i = 0, e = NumTo; i != e; ++i) {
871       if (To[i].getNode()) {
872         AddToWorklist(To[i].getNode());
873         AddUsersToWorklist(To[i].getNode());
874       }
875     }
876   }
877
878   // Finally, if the node is now dead, remove it from the graph.  The node
879   // may not be dead if the replacement process recursively simplified to
880   // something else needing this node.
881   if (N->use_empty())
882     deleteAndRecombine(N);
883   return SDValue(N, 0);
884 }
885
886 void DAGCombiner::
887 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
888   // Replace all uses.  If any nodes become isomorphic to other nodes and
889   // are deleted, make sure to remove them from our worklist.
890   WorklistRemover DeadNodes(*this);
891   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
892
893   // Push the new node and any (possibly new) users onto the worklist.
894   AddToWorklist(TLO.New.getNode());
895   AddUsersToWorklist(TLO.New.getNode());
896
897   // Finally, if the node is now dead, remove it from the graph.  The node
898   // may not be dead if the replacement process recursively simplified to
899   // something else needing this node.
900   if (TLO.Old.getNode()->use_empty())
901     deleteAndRecombine(TLO.Old.getNode());
902 }
903
904 /// Check the specified integer node value to see if it can be simplified or if
905 /// things it uses can be simplified by bit propagation. If so, return true.
906 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
907   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
908   APInt KnownZero, KnownOne;
909   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
910     return false;
911
912   // Revisit the node.
913   AddToWorklist(Op.getNode());
914
915   // Replace the old value with the new one.
916   ++NodesCombined;
917   DEBUG(dbgs() << "\nReplacing.2 ";
918         TLO.Old.getNode()->dump(&DAG);
919         dbgs() << "\nWith: ";
920         TLO.New.getNode()->dump(&DAG);
921         dbgs() << '\n');
922
923   CommitTargetLoweringOpt(TLO);
924   return true;
925 }
926
927 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
928   SDLoc dl(Load);
929   EVT VT = Load->getValueType(0);
930   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
931
932   DEBUG(dbgs() << "\nReplacing.9 ";
933         Load->dump(&DAG);
934         dbgs() << "\nWith: ";
935         Trunc.getNode()->dump(&DAG);
936         dbgs() << '\n');
937   WorklistRemover DeadNodes(*this);
938   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
939   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
940   deleteAndRecombine(Load);
941   AddToWorklist(Trunc.getNode());
942 }
943
944 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
945   Replace = false;
946   SDLoc dl(Op);
947   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
948     EVT MemVT = LD->getMemoryVT();
949     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
950       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
951                                                        : ISD::EXTLOAD)
952       : LD->getExtensionType();
953     Replace = true;
954     return DAG.getExtLoad(ExtType, dl, PVT,
955                           LD->getChain(), LD->getBasePtr(),
956                           MemVT, LD->getMemOperand());
957   }
958
959   unsigned Opc = Op.getOpcode();
960   switch (Opc) {
961   default: break;
962   case ISD::AssertSext:
963     return DAG.getNode(ISD::AssertSext, dl, PVT,
964                        SExtPromoteOperand(Op.getOperand(0), PVT),
965                        Op.getOperand(1));
966   case ISD::AssertZext:
967     return DAG.getNode(ISD::AssertZext, dl, PVT,
968                        ZExtPromoteOperand(Op.getOperand(0), PVT),
969                        Op.getOperand(1));
970   case ISD::Constant: {
971     unsigned ExtOpc =
972       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
973     return DAG.getNode(ExtOpc, dl, PVT, Op);
974   }
975   }
976
977   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
978     return SDValue();
979   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
980 }
981
982 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
983   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
984     return SDValue();
985   EVT OldVT = Op.getValueType();
986   SDLoc dl(Op);
987   bool Replace = false;
988   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
989   if (!NewOp.getNode())
990     return SDValue();
991   AddToWorklist(NewOp.getNode());
992
993   if (Replace)
994     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
995   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
996                      DAG.getValueType(OldVT));
997 }
998
999 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
1000   EVT OldVT = Op.getValueType();
1001   SDLoc dl(Op);
1002   bool Replace = false;
1003   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
1004   if (!NewOp.getNode())
1005     return SDValue();
1006   AddToWorklist(NewOp.getNode());
1007
1008   if (Replace)
1009     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
1010   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
1011 }
1012
1013 /// Promote the specified integer binary operation if the target indicates it is
1014 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1015 /// i32 since i16 instructions are longer.
1016 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
1017   if (!LegalOperations)
1018     return SDValue();
1019
1020   EVT VT = Op.getValueType();
1021   if (VT.isVector() || !VT.isInteger())
1022     return SDValue();
1023
1024   // If operation type is 'undesirable', e.g. i16 on x86, consider
1025   // promoting it.
1026   unsigned Opc = Op.getOpcode();
1027   if (TLI.isTypeDesirableForOp(Opc, VT))
1028     return SDValue();
1029
1030   EVT PVT = VT;
1031   // Consult target whether it is a good idea to promote this operation and
1032   // what's the right type to promote it to.
1033   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1034     assert(PVT != VT && "Don't know what type to promote to!");
1035
1036     bool Replace0 = false;
1037     SDValue N0 = Op.getOperand(0);
1038     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1039     if (!NN0.getNode())
1040       return SDValue();
1041
1042     bool Replace1 = false;
1043     SDValue N1 = Op.getOperand(1);
1044     SDValue NN1;
1045     if (N0 == N1)
1046       NN1 = NN0;
1047     else {
1048       NN1 = PromoteOperand(N1, PVT, Replace1);
1049       if (!NN1.getNode())
1050         return SDValue();
1051     }
1052
1053     AddToWorklist(NN0.getNode());
1054     if (NN1.getNode())
1055       AddToWorklist(NN1.getNode());
1056
1057     if (Replace0)
1058       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1059     if (Replace1)
1060       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1061
1062     DEBUG(dbgs() << "\nPromoting ";
1063           Op.getNode()->dump(&DAG));
1064     SDLoc dl(Op);
1065     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1066                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1067   }
1068   return SDValue();
1069 }
1070
1071 /// Promote the specified integer shift operation if the target indicates it is
1072 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1073 /// i32 since i16 instructions are longer.
1074 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1075   if (!LegalOperations)
1076     return SDValue();
1077
1078   EVT VT = Op.getValueType();
1079   if (VT.isVector() || !VT.isInteger())
1080     return SDValue();
1081
1082   // If operation type is 'undesirable', e.g. i16 on x86, consider
1083   // promoting it.
1084   unsigned Opc = Op.getOpcode();
1085   if (TLI.isTypeDesirableForOp(Opc, VT))
1086     return SDValue();
1087
1088   EVT PVT = VT;
1089   // Consult target whether it is a good idea to promote this operation and
1090   // what's the right type to promote it to.
1091   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1092     assert(PVT != VT && "Don't know what type to promote to!");
1093
1094     bool Replace = false;
1095     SDValue N0 = Op.getOperand(0);
1096     if (Opc == ISD::SRA)
1097       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1098     else if (Opc == ISD::SRL)
1099       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1100     else
1101       N0 = PromoteOperand(N0, PVT, Replace);
1102     if (!N0.getNode())
1103       return SDValue();
1104
1105     AddToWorklist(N0.getNode());
1106     if (Replace)
1107       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1108
1109     DEBUG(dbgs() << "\nPromoting ";
1110           Op.getNode()->dump(&DAG));
1111     SDLoc dl(Op);
1112     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1113                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1114   }
1115   return SDValue();
1116 }
1117
1118 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1119   if (!LegalOperations)
1120     return SDValue();
1121
1122   EVT VT = Op.getValueType();
1123   if (VT.isVector() || !VT.isInteger())
1124     return SDValue();
1125
1126   // If operation type is 'undesirable', e.g. i16 on x86, consider
1127   // promoting it.
1128   unsigned Opc = Op.getOpcode();
1129   if (TLI.isTypeDesirableForOp(Opc, VT))
1130     return SDValue();
1131
1132   EVT PVT = VT;
1133   // Consult target whether it is a good idea to promote this operation and
1134   // what's the right type to promote it to.
1135   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1136     assert(PVT != VT && "Don't know what type to promote to!");
1137     // fold (aext (aext x)) -> (aext x)
1138     // fold (aext (zext x)) -> (zext x)
1139     // fold (aext (sext x)) -> (sext x)
1140     DEBUG(dbgs() << "\nPromoting ";
1141           Op.getNode()->dump(&DAG));
1142     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1143   }
1144   return SDValue();
1145 }
1146
1147 bool DAGCombiner::PromoteLoad(SDValue Op) {
1148   if (!LegalOperations)
1149     return false;
1150
1151   EVT VT = Op.getValueType();
1152   if (VT.isVector() || !VT.isInteger())
1153     return false;
1154
1155   // If operation type is 'undesirable', e.g. i16 on x86, consider
1156   // promoting it.
1157   unsigned Opc = Op.getOpcode();
1158   if (TLI.isTypeDesirableForOp(Opc, VT))
1159     return false;
1160
1161   EVT PVT = VT;
1162   // Consult target whether it is a good idea to promote this operation and
1163   // what's the right type to promote it to.
1164   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1165     assert(PVT != VT && "Don't know what type to promote to!");
1166
1167     SDLoc dl(Op);
1168     SDNode *N = Op.getNode();
1169     LoadSDNode *LD = cast<LoadSDNode>(N);
1170     EVT MemVT = LD->getMemoryVT();
1171     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1172       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1173                                                        : ISD::EXTLOAD)
1174       : LD->getExtensionType();
1175     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1176                                    LD->getChain(), LD->getBasePtr(),
1177                                    MemVT, LD->getMemOperand());
1178     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1179
1180     DEBUG(dbgs() << "\nPromoting ";
1181           N->dump(&DAG);
1182           dbgs() << "\nTo: ";
1183           Result.getNode()->dump(&DAG);
1184           dbgs() << '\n');
1185     WorklistRemover DeadNodes(*this);
1186     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1187     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1188     deleteAndRecombine(N);
1189     AddToWorklist(Result.getNode());
1190     return true;
1191   }
1192   return false;
1193 }
1194
1195 /// \brief Recursively delete a node which has no uses and any operands for
1196 /// which it is the only use.
1197 ///
1198 /// Note that this both deletes the nodes and removes them from the worklist.
1199 /// It also adds any nodes who have had a user deleted to the worklist as they
1200 /// may now have only one use and subject to other combines.
1201 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1202   if (!N->use_empty())
1203     return false;
1204
1205   SmallSetVector<SDNode *, 16> Nodes;
1206   Nodes.insert(N);
1207   do {
1208     N = Nodes.pop_back_val();
1209     if (!N)
1210       continue;
1211
1212     if (N->use_empty()) {
1213       for (const SDValue &ChildN : N->op_values())
1214         Nodes.insert(ChildN.getNode());
1215
1216       removeFromWorklist(N);
1217       DAG.DeleteNode(N);
1218     } else {
1219       AddToWorklist(N);
1220     }
1221   } while (!Nodes.empty());
1222   return true;
1223 }
1224
1225 //===----------------------------------------------------------------------===//
1226 //  Main DAG Combiner implementation
1227 //===----------------------------------------------------------------------===//
1228
1229 void DAGCombiner::Run(CombineLevel AtLevel) {
1230   // set the instance variables, so that the various visit routines may use it.
1231   Level = AtLevel;
1232   LegalOperations = Level >= AfterLegalizeVectorOps;
1233   LegalTypes = Level >= AfterLegalizeTypes;
1234
1235   // Add all the dag nodes to the worklist.
1236   for (SDNode &Node : DAG.allnodes())
1237     AddToWorklist(&Node);
1238
1239   // Create a dummy node (which is not added to allnodes), that adds a reference
1240   // to the root node, preventing it from being deleted, and tracking any
1241   // changes of the root.
1242   HandleSDNode Dummy(DAG.getRoot());
1243
1244   // while the worklist isn't empty, find a node and
1245   // try and combine it.
1246   while (!WorklistMap.empty()) {
1247     SDNode *N;
1248     // The Worklist holds the SDNodes in order, but it may contain null entries.
1249     do {
1250       N = Worklist.pop_back_val();
1251     } while (!N);
1252
1253     bool GoodWorklistEntry = WorklistMap.erase(N);
1254     (void)GoodWorklistEntry;
1255     assert(GoodWorklistEntry &&
1256            "Found a worklist entry without a corresponding map entry!");
1257
1258     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1259     // N is deleted from the DAG, since they too may now be dead or may have a
1260     // reduced number of uses, allowing other xforms.
1261     if (recursivelyDeleteUnusedNodes(N))
1262       continue;
1263
1264     WorklistRemover DeadNodes(*this);
1265
1266     // If this combine is running after legalizing the DAG, re-legalize any
1267     // nodes pulled off the worklist.
1268     if (Level == AfterLegalizeDAG) {
1269       SmallSetVector<SDNode *, 16> UpdatedNodes;
1270       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1271
1272       for (SDNode *LN : UpdatedNodes) {
1273         AddToWorklist(LN);
1274         AddUsersToWorklist(LN);
1275       }
1276       if (!NIsValid)
1277         continue;
1278     }
1279
1280     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1281
1282     // Add any operands of the new node which have not yet been combined to the
1283     // worklist as well. Because the worklist uniques things already, this
1284     // won't repeatedly process the same operand.
1285     CombinedNodes.insert(N);
1286     for (const SDValue &ChildN : N->op_values())
1287       if (!CombinedNodes.count(ChildN.getNode()))
1288         AddToWorklist(ChildN.getNode());
1289
1290     SDValue RV = combine(N);
1291
1292     if (!RV.getNode())
1293       continue;
1294
1295     ++NodesCombined;
1296
1297     // If we get back the same node we passed in, rather than a new node or
1298     // zero, we know that the node must have defined multiple values and
1299     // CombineTo was used.  Since CombineTo takes care of the worklist
1300     // mechanics for us, we have no work to do in this case.
1301     if (RV.getNode() == N)
1302       continue;
1303
1304     assert(N->getOpcode() != ISD::DELETED_NODE &&
1305            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1306            "Node was deleted but visit returned new node!");
1307
1308     DEBUG(dbgs() << " ... into: ";
1309           RV.getNode()->dump(&DAG));
1310
1311     // Transfer debug value.
1312     DAG.TransferDbgValues(SDValue(N, 0), RV);
1313     if (N->getNumValues() == RV.getNode()->getNumValues())
1314       DAG.ReplaceAllUsesWith(N, RV.getNode());
1315     else {
1316       assert(N->getValueType(0) == RV.getValueType() &&
1317              N->getNumValues() == 1 && "Type mismatch");
1318       SDValue OpV = RV;
1319       DAG.ReplaceAllUsesWith(N, &OpV);
1320     }
1321
1322     // Push the new node and any users onto the worklist
1323     AddToWorklist(RV.getNode());
1324     AddUsersToWorklist(RV.getNode());
1325
1326     // Finally, if the node is now dead, remove it from the graph.  The node
1327     // may not be dead if the replacement process recursively simplified to
1328     // something else needing this node. This will also take care of adding any
1329     // operands which have lost a user to the worklist.
1330     recursivelyDeleteUnusedNodes(N);
1331   }
1332
1333   // If the root changed (e.g. it was a dead load, update the root).
1334   DAG.setRoot(Dummy.getValue());
1335   DAG.RemoveDeadNodes();
1336 }
1337
1338 SDValue DAGCombiner::visit(SDNode *N) {
1339   switch (N->getOpcode()) {
1340   default: break;
1341   case ISD::TokenFactor:        return visitTokenFactor(N);
1342   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1343   case ISD::ADD:                return visitADD(N);
1344   case ISD::SUB:                return visitSUB(N);
1345   case ISD::ADDC:               return visitADDC(N);
1346   case ISD::SUBC:               return visitSUBC(N);
1347   case ISD::ADDE:               return visitADDE(N);
1348   case ISD::SUBE:               return visitSUBE(N);
1349   case ISD::MUL:                return visitMUL(N);
1350   case ISD::SDIV:               return visitSDIV(N);
1351   case ISD::UDIV:               return visitUDIV(N);
1352   case ISD::SREM:
1353   case ISD::UREM:               return visitREM(N);
1354   case ISD::MULHU:              return visitMULHU(N);
1355   case ISD::MULHS:              return visitMULHS(N);
1356   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1357   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1358   case ISD::SMULO:              return visitSMULO(N);
1359   case ISD::UMULO:              return visitUMULO(N);
1360   case ISD::SMIN:
1361   case ISD::SMAX:
1362   case ISD::UMIN:
1363   case ISD::UMAX:               return visitIMINMAX(N);
1364   case ISD::AND:                return visitAND(N);
1365   case ISD::OR:                 return visitOR(N);
1366   case ISD::XOR:                return visitXOR(N);
1367   case ISD::SHL:                return visitSHL(N);
1368   case ISD::SRA:                return visitSRA(N);
1369   case ISD::SRL:                return visitSRL(N);
1370   case ISD::ROTR:
1371   case ISD::ROTL:               return visitRotate(N);
1372   case ISD::BSWAP:              return visitBSWAP(N);
1373   case ISD::CTLZ:               return visitCTLZ(N);
1374   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1375   case ISD::CTTZ:               return visitCTTZ(N);
1376   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1377   case ISD::CTPOP:              return visitCTPOP(N);
1378   case ISD::SELECT:             return visitSELECT(N);
1379   case ISD::VSELECT:            return visitVSELECT(N);
1380   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1381   case ISD::SETCC:              return visitSETCC(N);
1382   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1383   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1384   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1385   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1386   case ISD::SIGN_EXTEND_VECTOR_INREG: return visitSIGN_EXTEND_VECTOR_INREG(N);
1387   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1388   case ISD::BITCAST:            return visitBITCAST(N);
1389   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1390   case ISD::FADD:               return visitFADD(N);
1391   case ISD::FSUB:               return visitFSUB(N);
1392   case ISD::FMUL:               return visitFMUL(N);
1393   case ISD::FMA:                return visitFMA(N);
1394   case ISD::FDIV:               return visitFDIV(N);
1395   case ISD::FREM:               return visitFREM(N);
1396   case ISD::FSQRT:              return visitFSQRT(N);
1397   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1398   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1399   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1400   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1401   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1402   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1403   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1404   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1405   case ISD::FNEG:               return visitFNEG(N);
1406   case ISD::FABS:               return visitFABS(N);
1407   case ISD::FFLOOR:             return visitFFLOOR(N);
1408   case ISD::FMINNUM:            return visitFMINNUM(N);
1409   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1410   case ISD::FCEIL:              return visitFCEIL(N);
1411   case ISD::FTRUNC:             return visitFTRUNC(N);
1412   case ISD::BRCOND:             return visitBRCOND(N);
1413   case ISD::BR_CC:              return visitBR_CC(N);
1414   case ISD::LOAD:               return visitLOAD(N);
1415   case ISD::STORE:              return visitSTORE(N);
1416   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1417   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1418   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1419   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1420   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1421   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1422   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1423   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1424   case ISD::MGATHER:            return visitMGATHER(N);
1425   case ISD::MLOAD:              return visitMLOAD(N);
1426   case ISD::MSCATTER:           return visitMSCATTER(N);
1427   case ISD::MSTORE:             return visitMSTORE(N);
1428   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1429   case ISD::FP16_TO_FP:         return visitFP16_TO_FP(N);
1430   }
1431   return SDValue();
1432 }
1433
1434 SDValue DAGCombiner::combine(SDNode *N) {
1435   SDValue RV = visit(N);
1436
1437   // If nothing happened, try a target-specific DAG combine.
1438   if (!RV.getNode()) {
1439     assert(N->getOpcode() != ISD::DELETED_NODE &&
1440            "Node was deleted but visit returned NULL!");
1441
1442     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1443         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1444
1445       // Expose the DAG combiner to the target combiner impls.
1446       TargetLowering::DAGCombinerInfo
1447         DagCombineInfo(DAG, Level, false, this);
1448
1449       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1450     }
1451   }
1452
1453   // If nothing happened still, try promoting the operation.
1454   if (!RV.getNode()) {
1455     switch (N->getOpcode()) {
1456     default: break;
1457     case ISD::ADD:
1458     case ISD::SUB:
1459     case ISD::MUL:
1460     case ISD::AND:
1461     case ISD::OR:
1462     case ISD::XOR:
1463       RV = PromoteIntBinOp(SDValue(N, 0));
1464       break;
1465     case ISD::SHL:
1466     case ISD::SRA:
1467     case ISD::SRL:
1468       RV = PromoteIntShiftOp(SDValue(N, 0));
1469       break;
1470     case ISD::SIGN_EXTEND:
1471     case ISD::ZERO_EXTEND:
1472     case ISD::ANY_EXTEND:
1473       RV = PromoteExtend(SDValue(N, 0));
1474       break;
1475     case ISD::LOAD:
1476       if (PromoteLoad(SDValue(N, 0)))
1477         RV = SDValue(N, 0);
1478       break;
1479     }
1480   }
1481
1482   // If N is a commutative binary node, try commuting it to enable more
1483   // sdisel CSE.
1484   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1485       N->getNumValues() == 1) {
1486     SDValue N0 = N->getOperand(0);
1487     SDValue N1 = N->getOperand(1);
1488
1489     // Constant operands are canonicalized to RHS.
1490     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1491       SDValue Ops[] = {N1, N0};
1492       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1493                                             N->getFlags());
1494       if (CSENode)
1495         return SDValue(CSENode, 0);
1496     }
1497   }
1498
1499   return RV;
1500 }
1501
1502 /// Given a node, return its input chain if it has one, otherwise return a null
1503 /// sd operand.
1504 static SDValue getInputChainForNode(SDNode *N) {
1505   if (unsigned NumOps = N->getNumOperands()) {
1506     if (N->getOperand(0).getValueType() == MVT::Other)
1507       return N->getOperand(0);
1508     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1509       return N->getOperand(NumOps-1);
1510     for (unsigned i = 1; i < NumOps-1; ++i)
1511       if (N->getOperand(i).getValueType() == MVT::Other)
1512         return N->getOperand(i);
1513   }
1514   return SDValue();
1515 }
1516
1517 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1518   // If N has two operands, where one has an input chain equal to the other,
1519   // the 'other' chain is redundant.
1520   if (N->getNumOperands() == 2) {
1521     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1522       return N->getOperand(0);
1523     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1524       return N->getOperand(1);
1525   }
1526
1527   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1528   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1529   SmallPtrSet<SDNode*, 16> SeenOps;
1530   bool Changed = false;             // If we should replace this token factor.
1531
1532   // Start out with this token factor.
1533   TFs.push_back(N);
1534
1535   // Iterate through token factors.  The TFs grows when new token factors are
1536   // encountered.
1537   for (unsigned i = 0; i < TFs.size(); ++i) {
1538     SDNode *TF = TFs[i];
1539
1540     // Check each of the operands.
1541     for (const SDValue &Op : TF->op_values()) {
1542
1543       switch (Op.getOpcode()) {
1544       case ISD::EntryToken:
1545         // Entry tokens don't need to be added to the list. They are
1546         // redundant.
1547         Changed = true;
1548         break;
1549
1550       case ISD::TokenFactor:
1551         if (Op.hasOneUse() &&
1552             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1553           // Queue up for processing.
1554           TFs.push_back(Op.getNode());
1555           // Clean up in case the token factor is removed.
1556           AddToWorklist(Op.getNode());
1557           Changed = true;
1558           break;
1559         }
1560         // Fall thru
1561
1562       default:
1563         // Only add if it isn't already in the list.
1564         if (SeenOps.insert(Op.getNode()).second)
1565           Ops.push_back(Op);
1566         else
1567           Changed = true;
1568         break;
1569       }
1570     }
1571   }
1572
1573   SDValue Result;
1574
1575   // If we've changed things around then replace token factor.
1576   if (Changed) {
1577     if (Ops.empty()) {
1578       // The entry token is the only possible outcome.
1579       Result = DAG.getEntryNode();
1580     } else {
1581       // New and improved token factor.
1582       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1583     }
1584
1585     // Add users to worklist if AA is enabled, since it may introduce
1586     // a lot of new chained token factors while removing memory deps.
1587     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1588       : DAG.getSubtarget().useAA();
1589     return CombineTo(N, Result, UseAA /*add to worklist*/);
1590   }
1591
1592   return Result;
1593 }
1594
1595 /// MERGE_VALUES can always be eliminated.
1596 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1597   WorklistRemover DeadNodes(*this);
1598   // Replacing results may cause a different MERGE_VALUES to suddenly
1599   // be CSE'd with N, and carry its uses with it. Iterate until no
1600   // uses remain, to ensure that the node can be safely deleted.
1601   // First add the users of this node to the work list so that they
1602   // can be tried again once they have new operands.
1603   AddUsersToWorklist(N);
1604   do {
1605     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1606       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1607   } while (!N->use_empty());
1608   deleteAndRecombine(N);
1609   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1610 }
1611
1612 static bool isNullConstant(SDValue V) {
1613   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1614   return Const != nullptr && Const->isNullValue();
1615 }
1616
1617 static bool isNullFPConstant(SDValue V) {
1618   ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
1619   return Const != nullptr && Const->isZero() && !Const->isNegative();
1620 }
1621
1622 static bool isAllOnesConstant(SDValue V) {
1623   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1624   return Const != nullptr && Const->isAllOnesValue();
1625 }
1626
1627 static bool isOneConstant(SDValue V) {
1628   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
1629   return Const != nullptr && Const->isOne();
1630 }
1631
1632 /// If \p N is a ContantSDNode with isOpaque() == false return it casted to a
1633 /// ContantSDNode pointer else nullptr.
1634 static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
1635   ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
1636   return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
1637 }
1638
1639 SDValue DAGCombiner::visitADD(SDNode *N) {
1640   SDValue N0 = N->getOperand(0);
1641   SDValue N1 = N->getOperand(1);
1642   EVT VT = N0.getValueType();
1643
1644   // fold vector ops
1645   if (VT.isVector()) {
1646     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1647       return FoldedVOp;
1648
1649     // fold (add x, 0) -> x, vector edition
1650     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1651       return N0;
1652     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1653       return N1;
1654   }
1655
1656   // fold (add x, undef) -> undef
1657   if (N0.getOpcode() == ISD::UNDEF)
1658     return N0;
1659   if (N1.getOpcode() == ISD::UNDEF)
1660     return N1;
1661   // fold (add c1, c2) -> c1+c2
1662   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1663   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1664   if (N0C && N1C)
1665     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1666   // canonicalize constant to RHS
1667   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1668      !isConstantIntBuildVectorOrConstantInt(N1))
1669     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1670   // fold (add x, 0) -> x
1671   if (isNullConstant(N1))
1672     return N0;
1673   // fold (add Sym, c) -> Sym+c
1674   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1675     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1676         GA->getOpcode() == ISD::GlobalAddress)
1677       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1678                                   GA->getOffset() +
1679                                     (uint64_t)N1C->getSExtValue());
1680   // fold ((c1-A)+c2) -> (c1+c2)-A
1681   if (N1C && N0.getOpcode() == ISD::SUB)
1682     if (ConstantSDNode *N0C = getAsNonOpaqueConstant(N0.getOperand(0))) {
1683       SDLoc DL(N);
1684       return DAG.getNode(ISD::SUB, DL, VT,
1685                          DAG.getConstant(N1C->getAPIntValue()+
1686                                          N0C->getAPIntValue(), DL, VT),
1687                          N0.getOperand(1));
1688     }
1689   // reassociate add
1690   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1691     return RADD;
1692   // fold ((0-A) + B) -> B-A
1693   if (N0.getOpcode() == ISD::SUB && isNullConstant(N0.getOperand(0)))
1694     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1695   // fold (A + (0-B)) -> A-B
1696   if (N1.getOpcode() == ISD::SUB && isNullConstant(N1.getOperand(0)))
1697     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1698   // fold (A+(B-A)) -> B
1699   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1700     return N1.getOperand(0);
1701   // fold ((B-A)+A) -> B
1702   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1703     return N0.getOperand(0);
1704   // fold (A+(B-(A+C))) to (B-C)
1705   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1706       N0 == N1.getOperand(1).getOperand(0))
1707     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1708                        N1.getOperand(1).getOperand(1));
1709   // fold (A+(B-(C+A))) to (B-C)
1710   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1711       N0 == N1.getOperand(1).getOperand(1))
1712     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1713                        N1.getOperand(1).getOperand(0));
1714   // fold (A+((B-A)+or-C)) to (B+or-C)
1715   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1716       N1.getOperand(0).getOpcode() == ISD::SUB &&
1717       N0 == N1.getOperand(0).getOperand(1))
1718     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1719                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1720
1721   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1722   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1723     SDValue N00 = N0.getOperand(0);
1724     SDValue N01 = N0.getOperand(1);
1725     SDValue N10 = N1.getOperand(0);
1726     SDValue N11 = N1.getOperand(1);
1727
1728     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1729       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1730                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1731                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1732   }
1733
1734   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1735     return SDValue(N, 0);
1736
1737   // fold (a+b) -> (a|b) iff a and b share no bits.
1738   if (VT.isInteger() && !VT.isVector()) {
1739     APInt LHSZero, LHSOne;
1740     APInt RHSZero, RHSOne;
1741     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1742
1743     if (LHSZero.getBoolValue()) {
1744       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1745
1746       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1747       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1748       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1749         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1750           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1751       }
1752     }
1753   }
1754
1755   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1756   if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
1757       isNullConstant(N1.getOperand(0).getOperand(0)))
1758     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1759                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1760                                    N1.getOperand(0).getOperand(1),
1761                                    N1.getOperand(1)));
1762   if (N0.getOpcode() == ISD::SHL && N0.getOperand(0).getOpcode() == ISD::SUB &&
1763       isNullConstant(N0.getOperand(0).getOperand(0)))
1764     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1765                        DAG.getNode(ISD::SHL, SDLoc(N), VT,
1766                                    N0.getOperand(0).getOperand(1),
1767                                    N0.getOperand(1)));
1768
1769   if (N1.getOpcode() == ISD::AND) {
1770     SDValue AndOp0 = N1.getOperand(0);
1771     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1772     unsigned DestBits = VT.getScalarType().getSizeInBits();
1773
1774     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1775     // and similar xforms where the inner op is either ~0 or 0.
1776     if (NumSignBits == DestBits && isOneConstant(N1->getOperand(1))) {
1777       SDLoc DL(N);
1778       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1779     }
1780   }
1781
1782   // add (sext i1), X -> sub X, (zext i1)
1783   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1784       N0.getOperand(0).getValueType() == MVT::i1 &&
1785       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1786     SDLoc DL(N);
1787     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1788     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1789   }
1790
1791   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1792   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1793     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1794     if (TN->getVT() == MVT::i1) {
1795       SDLoc DL(N);
1796       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1797                                  DAG.getConstant(1, DL, VT));
1798       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1799     }
1800   }
1801
1802   return SDValue();
1803 }
1804
1805 SDValue DAGCombiner::visitADDC(SDNode *N) {
1806   SDValue N0 = N->getOperand(0);
1807   SDValue N1 = N->getOperand(1);
1808   EVT VT = N0.getValueType();
1809
1810   // If the flag result is dead, turn this into an ADD.
1811   if (!N->hasAnyUseOfValue(1))
1812     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1813                      DAG.getNode(ISD::CARRY_FALSE,
1814                                  SDLoc(N), MVT::Glue));
1815
1816   // canonicalize constant to RHS.
1817   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1818   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1819   if (N0C && !N1C)
1820     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1821
1822   // fold (addc x, 0) -> x + no carry out
1823   if (isNullConstant(N1))
1824     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1825                                         SDLoc(N), MVT::Glue));
1826
1827   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1828   APInt LHSZero, LHSOne;
1829   APInt RHSZero, RHSOne;
1830   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1831
1832   if (LHSZero.getBoolValue()) {
1833     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1834
1835     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1836     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1837     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1838       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1839                        DAG.getNode(ISD::CARRY_FALSE,
1840                                    SDLoc(N), MVT::Glue));
1841   }
1842
1843   return SDValue();
1844 }
1845
1846 SDValue DAGCombiner::visitADDE(SDNode *N) {
1847   SDValue N0 = N->getOperand(0);
1848   SDValue N1 = N->getOperand(1);
1849   SDValue CarryIn = N->getOperand(2);
1850
1851   // canonicalize constant to RHS
1852   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1853   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1854   if (N0C && !N1C)
1855     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1856                        N1, N0, CarryIn);
1857
1858   // fold (adde x, y, false) -> (addc x, y)
1859   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1860     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1861
1862   return SDValue();
1863 }
1864
1865 // Since it may not be valid to emit a fold to zero for vector initializers
1866 // check if we can before folding.
1867 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1868                              SelectionDAG &DAG,
1869                              bool LegalOperations, bool LegalTypes) {
1870   if (!VT.isVector())
1871     return DAG.getConstant(0, DL, VT);
1872   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1873     return DAG.getConstant(0, DL, VT);
1874   return SDValue();
1875 }
1876
1877 SDValue DAGCombiner::visitSUB(SDNode *N) {
1878   SDValue N0 = N->getOperand(0);
1879   SDValue N1 = N->getOperand(1);
1880   EVT VT = N0.getValueType();
1881
1882   // fold vector ops
1883   if (VT.isVector()) {
1884     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1885       return FoldedVOp;
1886
1887     // fold (sub x, 0) -> x, vector edition
1888     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1889       return N0;
1890   }
1891
1892   // fold (sub x, x) -> 0
1893   // FIXME: Refactor this and xor and other similar operations together.
1894   if (N0 == N1)
1895     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1896   // fold (sub c1, c2) -> c1-c2
1897   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
1898   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
1899   if (N0C && N1C)
1900     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1901   // fold (sub x, c) -> (add x, -c)
1902   if (N1C) {
1903     SDLoc DL(N);
1904     return DAG.getNode(ISD::ADD, DL, VT, N0,
1905                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1906   }
1907   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1908   if (isAllOnesConstant(N0))
1909     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1910   // fold A-(A-B) -> B
1911   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1912     return N1.getOperand(1);
1913   // fold (A+B)-A -> B
1914   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1915     return N0.getOperand(1);
1916   // fold (A+B)-B -> A
1917   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1918     return N0.getOperand(0);
1919   // fold C2-(A+C1) -> (C2-C1)-A
1920   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1921     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1922   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1923     SDLoc DL(N);
1924     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1925                                    DL, VT);
1926     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1927                        N1.getOperand(0));
1928   }
1929   // fold ((A+(B+or-C))-B) -> A+or-C
1930   if (N0.getOpcode() == ISD::ADD &&
1931       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1932        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1933       N0.getOperand(1).getOperand(0) == N1)
1934     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1935                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1936   // fold ((A+(C+B))-B) -> A+C
1937   if (N0.getOpcode() == ISD::ADD &&
1938       N0.getOperand(1).getOpcode() == ISD::ADD &&
1939       N0.getOperand(1).getOperand(1) == N1)
1940     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1941                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1942   // fold ((A-(B-C))-C) -> A-B
1943   if (N0.getOpcode() == ISD::SUB &&
1944       N0.getOperand(1).getOpcode() == ISD::SUB &&
1945       N0.getOperand(1).getOperand(1) == N1)
1946     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1947                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1948
1949   // If either operand of a sub is undef, the result is undef
1950   if (N0.getOpcode() == ISD::UNDEF)
1951     return N0;
1952   if (N1.getOpcode() == ISD::UNDEF)
1953     return N1;
1954
1955   // If the relocation model supports it, consider symbol offsets.
1956   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1957     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1958       // fold (sub Sym, c) -> Sym-c
1959       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1960         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1961                                     GA->getOffset() -
1962                                       (uint64_t)N1C->getSExtValue());
1963       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1964       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1965         if (GA->getGlobal() == GB->getGlobal())
1966           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1967                                  SDLoc(N), VT);
1968     }
1969
1970   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1971   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1972     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1973     if (TN->getVT() == MVT::i1) {
1974       SDLoc DL(N);
1975       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1976                                  DAG.getConstant(1, DL, VT));
1977       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1978     }
1979   }
1980
1981   return SDValue();
1982 }
1983
1984 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1985   SDValue N0 = N->getOperand(0);
1986   SDValue N1 = N->getOperand(1);
1987   EVT VT = N0.getValueType();
1988   SDLoc DL(N);
1989
1990   // If the flag result is dead, turn this into an SUB.
1991   if (!N->hasAnyUseOfValue(1))
1992     return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
1993                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1994
1995   // fold (subc x, x) -> 0 + no borrow
1996   if (N0 == N1)
1997     return CombineTo(N, DAG.getConstant(0, DL, VT),
1998                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
1999
2000   // fold (subc x, 0) -> x + no borrow
2001   if (isNullConstant(N1))
2002     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2003
2004   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
2005   if (isAllOnesConstant(N0))
2006     return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
2007                      DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
2008
2009   return SDValue();
2010 }
2011
2012 SDValue DAGCombiner::visitSUBE(SDNode *N) {
2013   SDValue N0 = N->getOperand(0);
2014   SDValue N1 = N->getOperand(1);
2015   SDValue CarryIn = N->getOperand(2);
2016
2017   // fold (sube x, y, false) -> (subc x, y)
2018   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
2019     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
2020
2021   return SDValue();
2022 }
2023
2024 SDValue DAGCombiner::visitMUL(SDNode *N) {
2025   SDValue N0 = N->getOperand(0);
2026   SDValue N1 = N->getOperand(1);
2027   EVT VT = N0.getValueType();
2028
2029   // fold (mul x, undef) -> 0
2030   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2031     return DAG.getConstant(0, SDLoc(N), VT);
2032
2033   bool N0IsConst = false;
2034   bool N1IsConst = false;
2035   bool N1IsOpaqueConst = false;
2036   bool N0IsOpaqueConst = false;
2037   APInt ConstValue0, ConstValue1;
2038   // fold vector ops
2039   if (VT.isVector()) {
2040     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2041       return FoldedVOp;
2042
2043     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2044     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2045   } else {
2046     N0IsConst = isa<ConstantSDNode>(N0);
2047     if (N0IsConst) {
2048       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2049       N0IsOpaqueConst = cast<ConstantSDNode>(N0)->isOpaque();
2050     }
2051     N1IsConst = isa<ConstantSDNode>(N1);
2052     if (N1IsConst) {
2053       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2054       N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
2055     }
2056   }
2057
2058   // fold (mul c1, c2) -> c1*c2
2059   if (N0IsConst && N1IsConst && !N0IsOpaqueConst && !N1IsOpaqueConst)
2060     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2061                                       N0.getNode(), N1.getNode());
2062
2063   // canonicalize constant to RHS (vector doesn't have to splat)
2064   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2065      !isConstantIntBuildVectorOrConstantInt(N1))
2066     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2067   // fold (mul x, 0) -> 0
2068   if (N1IsConst && ConstValue1 == 0)
2069     return N1;
2070   // We require a splat of the entire scalar bit width for non-contiguous
2071   // bit patterns.
2072   bool IsFullSplat =
2073     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2074   // fold (mul x, 1) -> x
2075   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2076     return N0;
2077   // fold (mul x, -1) -> 0-x
2078   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2079     SDLoc DL(N);
2080     return DAG.getNode(ISD::SUB, DL, VT,
2081                        DAG.getConstant(0, DL, VT), N0);
2082   }
2083   // fold (mul x, (1 << c)) -> x << c
2084   if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isPowerOf2() &&
2085       IsFullSplat) {
2086     SDLoc DL(N);
2087     return DAG.getNode(ISD::SHL, DL, VT, N0,
2088                        DAG.getConstant(ConstValue1.logBase2(), DL,
2089                                        getShiftAmountTy(N0.getValueType())));
2090   }
2091   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2092   if (N1IsConst && !N1IsOpaqueConst && (-ConstValue1).isPowerOf2() &&
2093       IsFullSplat) {
2094     unsigned Log2Val = (-ConstValue1).logBase2();
2095     SDLoc DL(N);
2096     // FIXME: If the input is something that is easily negated (e.g. a
2097     // single-use add), we should put the negate there.
2098     return DAG.getNode(ISD::SUB, DL, VT,
2099                        DAG.getConstant(0, DL, VT),
2100                        DAG.getNode(ISD::SHL, DL, VT, N0,
2101                             DAG.getConstant(Log2Val, DL,
2102                                       getShiftAmountTy(N0.getValueType()))));
2103   }
2104
2105   APInt Val;
2106   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2107   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2108       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2109                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2110     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2111                              N1, N0.getOperand(1));
2112     AddToWorklist(C3.getNode());
2113     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2114                        N0.getOperand(0), C3);
2115   }
2116
2117   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2118   // use.
2119   {
2120     SDValue Sh(nullptr,0), Y(nullptr,0);
2121     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2122     if (N0.getOpcode() == ISD::SHL &&
2123         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2124                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2125         N0.getNode()->hasOneUse()) {
2126       Sh = N0; Y = N1;
2127     } else if (N1.getOpcode() == ISD::SHL &&
2128                isa<ConstantSDNode>(N1.getOperand(1)) &&
2129                N1.getNode()->hasOneUse()) {
2130       Sh = N1; Y = N0;
2131     }
2132
2133     if (Sh.getNode()) {
2134       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2135                                 Sh.getOperand(0), Y);
2136       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2137                          Mul, Sh.getOperand(1));
2138     }
2139   }
2140
2141   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2142   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2143       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2144                      isa<ConstantSDNode>(N0.getOperand(1))))
2145     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2146                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2147                                    N0.getOperand(0), N1),
2148                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2149                                    N0.getOperand(1), N1));
2150
2151   // reassociate mul
2152   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2153     return RMUL;
2154
2155   return SDValue();
2156 }
2157
2158 /// Return true if divmod libcall is available.
2159 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2160                                      const TargetLowering &TLI) {
2161   RTLIB::Libcall LC;
2162   switch (Node->getSimpleValueType(0).SimpleTy) {
2163   default: return false; // No libcall for vector types.
2164   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2165   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2166   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2167   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2168   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2169   }
2170
2171   return TLI.getLibcallName(LC) != nullptr;
2172 }
2173
2174 /// Issue divrem if both quotient and remainder are needed.
2175 SDValue DAGCombiner::useDivRem(SDNode *Node) {
2176   if (Node->use_empty())
2177     return SDValue(); // This is a dead node, leave it alone.
2178
2179   EVT VT = Node->getValueType(0);
2180   if (!TLI.isTypeLegal(VT))
2181     return SDValue();
2182
2183   unsigned Opcode = Node->getOpcode();
2184   bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
2185
2186   unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2187   // If DIVREM is going to get expanded into a libcall,
2188   // but there is no libcall available, then don't combine.
2189   if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
2190       !isDivRemLibcallAvailable(Node, isSigned, TLI))
2191     return SDValue();
2192
2193   // If div is legal, it's better to do the normal expansion
2194   unsigned OtherOpcode = 0;
2195   if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
2196     OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
2197     if (TLI.isOperationLegalOrCustom(Opcode, VT))
2198       return SDValue();
2199   } else {
2200     OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2201     if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
2202       return SDValue();
2203   }
2204
2205   SDValue Op0 = Node->getOperand(0);
2206   SDValue Op1 = Node->getOperand(1);
2207   SDValue combined;
2208   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2209          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2210     SDNode *User = *UI;
2211     if (User == Node || User->use_empty())
2212       continue;
2213     // Convert the other matching node(s), too;
2214     // otherwise, the DIVREM may get target-legalized into something
2215     // target-specific that we won't be able to recognize.
2216     unsigned UserOpc = User->getOpcode();
2217     if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
2218         User->getOperand(0) == Op0 &&
2219         User->getOperand(1) == Op1) {
2220       if (!combined) {
2221         if (UserOpc == OtherOpcode) {
2222           SDVTList VTs = DAG.getVTList(VT, VT);
2223           combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
2224         } else if (UserOpc == DivRemOpc) {
2225           combined = SDValue(User, 0);
2226         } else {
2227           assert(UserOpc == Opcode);
2228           continue;
2229         }
2230       }
2231       if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
2232         CombineTo(User, combined);
2233       else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
2234         CombineTo(User, combined.getValue(1));
2235     }
2236   }
2237   return combined;
2238 }
2239
2240 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2241   SDValue N0 = N->getOperand(0);
2242   SDValue N1 = N->getOperand(1);
2243   EVT VT = N->getValueType(0);
2244
2245   // fold vector ops
2246   if (VT.isVector())
2247     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2248       return FoldedVOp;
2249
2250   SDLoc DL(N);
2251
2252   // fold (sdiv c1, c2) -> c1/c2
2253   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2254   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2255   if (N0C && N1C && !N0C->isOpaque() && !N1C->isOpaque())
2256     return DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, N0C, N1C);
2257   // fold (sdiv X, 1) -> X
2258   if (N1C && N1C->isOne())
2259     return N0;
2260   // fold (sdiv X, -1) -> 0-X
2261   if (N1C && N1C->isAllOnesValue())
2262     return DAG.getNode(ISD::SUB, DL, VT,
2263                        DAG.getConstant(0, DL, VT), N0);
2264
2265   // If we know the sign bits of both operands are zero, strength reduce to a
2266   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2267   if (!VT.isVector()) {
2268     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2269       return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
2270   }
2271
2272   // fold (sdiv X, pow2) -> simple ops after legalize
2273   // FIXME: We check for the exact bit here because the generic lowering gives
2274   // better results in that case. The target-specific lowering should learn how
2275   // to handle exact sdivs efficiently.
2276   if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2277       !cast<BinaryWithFlagsSDNode>(N)->Flags.hasExact() &&
2278       (N1C->getAPIntValue().isPowerOf2() ||
2279        (-N1C->getAPIntValue()).isPowerOf2())) {
2280     // Target-specific implementation of sdiv x, pow2.
2281     if (SDValue Res = BuildSDIVPow2(N))
2282       return Res;
2283
2284     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2285
2286     // Splat the sign bit into the register
2287     SDValue SGN =
2288         DAG.getNode(ISD::SRA, DL, VT, N0,
2289                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2290                                     getShiftAmountTy(N0.getValueType())));
2291     AddToWorklist(SGN.getNode());
2292
2293     // Add (N0 < 0) ? abs2 - 1 : 0;
2294     SDValue SRL =
2295         DAG.getNode(ISD::SRL, DL, VT, SGN,
2296                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2297                                     getShiftAmountTy(SGN.getValueType())));
2298     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2299     AddToWorklist(SRL.getNode());
2300     AddToWorklist(ADD.getNode());    // Divide by pow2
2301     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2302                   DAG.getConstant(lg2, DL,
2303                                   getShiftAmountTy(ADD.getValueType())));
2304
2305     // If we're dividing by a positive value, we're done.  Otherwise, we must
2306     // negate the result.
2307     if (N1C->getAPIntValue().isNonNegative())
2308       return SRA;
2309
2310     AddToWorklist(SRA.getNode());
2311     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2312   }
2313
2314   // If integer divide is expensive and we satisfy the requirements, emit an
2315   // alternate sequence.  Targets may check function attributes for size/speed
2316   // trade-offs.
2317   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2318   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2319     if (SDValue Op = BuildSDIV(N))
2320       return Op;
2321
2322   // sdiv, srem -> sdivrem
2323   if (SDValue DivRem = useDivRem(N))
2324     return DivRem;
2325
2326   // undef / X -> 0
2327   if (N0.getOpcode() == ISD::UNDEF)
2328     return DAG.getConstant(0, DL, VT);
2329   // X / undef -> undef
2330   if (N1.getOpcode() == ISD::UNDEF)
2331     return N1;
2332
2333   return SDValue();
2334 }
2335
2336 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2337   SDValue N0 = N->getOperand(0);
2338   SDValue N1 = N->getOperand(1);
2339   EVT VT = N->getValueType(0);
2340
2341   // fold vector ops
2342   if (VT.isVector())
2343     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2344       return FoldedVOp;
2345
2346   SDLoc DL(N);
2347
2348   // fold (udiv c1, c2) -> c1/c2
2349   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2350   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2351   if (N0C && N1C)
2352     if (SDValue Folded = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT,
2353                                                     N0C, N1C))
2354       return Folded;
2355   // fold (udiv x, (1 << c)) -> x >>u c
2356   if (N1C && !N1C->isOpaque() && N1C->getAPIntValue().isPowerOf2())
2357     return DAG.getNode(ISD::SRL, DL, VT, N0,
2358                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2359                                        getShiftAmountTy(N0.getValueType())));
2360
2361   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2362   if (N1.getOpcode() == ISD::SHL) {
2363     if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2364       if (SHC->getAPIntValue().isPowerOf2()) {
2365         EVT ADDVT = N1.getOperand(1).getValueType();
2366         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2367                                   N1.getOperand(1),
2368                                   DAG.getConstant(SHC->getAPIntValue()
2369                                                                   .logBase2(),
2370                                                   DL, ADDVT));
2371         AddToWorklist(Add.getNode());
2372         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2373       }
2374     }
2375   }
2376
2377   // fold (udiv x, c) -> alternate
2378   AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
2379   if (N1C && !TLI.isIntDivCheap(N->getValueType(0), Attr))
2380     if (SDValue Op = BuildUDIV(N))
2381       return Op;
2382
2383   // sdiv, srem -> sdivrem
2384   if (SDValue DivRem = useDivRem(N))
2385     return DivRem;
2386
2387   // undef / X -> 0
2388   if (N0.getOpcode() == ISD::UNDEF)
2389     return DAG.getConstant(0, DL, VT);
2390   // X / undef -> undef
2391   if (N1.getOpcode() == ISD::UNDEF)
2392     return N1;
2393
2394   return SDValue();
2395 }
2396
2397 // handles ISD::SREM and ISD::UREM
2398 SDValue DAGCombiner::visitREM(SDNode *N) {
2399   unsigned Opcode = N->getOpcode();
2400   SDValue N0 = N->getOperand(0);
2401   SDValue N1 = N->getOperand(1);
2402   EVT VT = N->getValueType(0);
2403   bool isSigned = (Opcode == ISD::SREM);
2404   SDLoc DL(N);
2405
2406   // fold (rem c1, c2) -> c1%c2
2407   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2408   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2409   if (N0C && N1C)
2410     if (SDValue Folded = DAG.FoldConstantArithmetic(Opcode, DL, VT, N0C, N1C))
2411       return Folded;
2412
2413   if (isSigned) {
2414     // If we know the sign bits of both operands are zero, strength reduce to a
2415     // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2416     if (!VT.isVector()) {
2417       if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2418         return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
2419     }
2420   } else {
2421     // fold (urem x, pow2) -> (and x, pow2-1)
2422     if (N1C && !N1C->isNullValue() && !N1C->isOpaque() &&
2423         N1C->getAPIntValue().isPowerOf2()) {
2424       return DAG.getNode(ISD::AND, DL, VT, N0,
2425                          DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2426     }
2427     // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2428     if (N1.getOpcode() == ISD::SHL) {
2429       if (ConstantSDNode *SHC = getAsNonOpaqueConstant(N1.getOperand(0))) {
2430         if (SHC->getAPIntValue().isPowerOf2()) {
2431           SDValue Add =
2432             DAG.getNode(ISD::ADD, DL, VT, N1,
2433                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2434                                  VT));
2435           AddToWorklist(Add.getNode());
2436           return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2437         }
2438       }
2439     }
2440   }
2441
2442   // If X/C can be simplified by the division-by-constant logic, lower
2443   // X%C to the equivalent of X-X/C*C.
2444   if (N1C && !N1C->isNullValue()) {
2445     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
2446     SDValue Div = DAG.getNode(DivOpcode, DL, VT, N0, N1);
2447     AddToWorklist(Div.getNode());
2448     SDValue OptimizedDiv = combine(Div.getNode());
2449     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2450       SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
2451       SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
2452       AddToWorklist(Mul.getNode());
2453       return Sub;
2454     }
2455   }
2456
2457   // sdiv, srem -> sdivrem
2458   if (SDValue DivRem = useDivRem(N))
2459     return DivRem.getValue(1);
2460
2461   // undef % X -> 0
2462   if (N0.getOpcode() == ISD::UNDEF)
2463     return DAG.getConstant(0, DL, VT);
2464   // X % undef -> undef
2465   if (N1.getOpcode() == ISD::UNDEF)
2466     return N1;
2467
2468   return SDValue();
2469 }
2470
2471 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2472   SDValue N0 = N->getOperand(0);
2473   SDValue N1 = N->getOperand(1);
2474   EVT VT = N->getValueType(0);
2475   SDLoc DL(N);
2476
2477   // fold (mulhs x, 0) -> 0
2478   if (isNullConstant(N1))
2479     return N1;
2480   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2481   if (isOneConstant(N1)) {
2482     SDLoc DL(N);
2483     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2484                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2485                                        DL,
2486                                        getShiftAmountTy(N0.getValueType())));
2487   }
2488   // fold (mulhs x, undef) -> 0
2489   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2490     return DAG.getConstant(0, SDLoc(N), VT);
2491
2492   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2493   // plus a shift.
2494   if (VT.isSimple() && !VT.isVector()) {
2495     MVT Simple = VT.getSimpleVT();
2496     unsigned SimpleSize = Simple.getSizeInBits();
2497     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2500       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2501       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2502       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2503             DAG.getConstant(SimpleSize, DL,
2504                             getShiftAmountTy(N1.getValueType())));
2505       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2513   SDValue N0 = N->getOperand(0);
2514   SDValue N1 = N->getOperand(1);
2515   EVT VT = N->getValueType(0);
2516   SDLoc DL(N);
2517
2518   // fold (mulhu x, 0) -> 0
2519   if (isNullConstant(N1))
2520     return N1;
2521   // fold (mulhu x, 1) -> 0
2522   if (isOneConstant(N1))
2523     return DAG.getConstant(0, DL, N0.getValueType());
2524   // fold (mulhu x, undef) -> 0
2525   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2526     return DAG.getConstant(0, DL, VT);
2527
2528   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2529   // plus a shift.
2530   if (VT.isSimple() && !VT.isVector()) {
2531     MVT Simple = VT.getSimpleVT();
2532     unsigned SimpleSize = Simple.getSizeInBits();
2533     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2534     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2535       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2536       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2537       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2538       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2539             DAG.getConstant(SimpleSize, DL,
2540                             getShiftAmountTy(N1.getValueType())));
2541       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2542     }
2543   }
2544
2545   return SDValue();
2546 }
2547
2548 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2549 /// give the opcodes for the two computations that are being performed. Return
2550 /// true if a simplification was made.
2551 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2552                                                 unsigned HiOp) {
2553   // If the high half is not needed, just compute the low half.
2554   bool HiExists = N->hasAnyUseOfValue(1);
2555   if (!HiExists &&
2556       (!LegalOperations ||
2557        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2558     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2559     return CombineTo(N, Res, Res);
2560   }
2561
2562   // If the low half is not needed, just compute the high half.
2563   bool LoExists = N->hasAnyUseOfValue(0);
2564   if (!LoExists &&
2565       (!LegalOperations ||
2566        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2567     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2568     return CombineTo(N, Res, Res);
2569   }
2570
2571   // If both halves are used, return as it is.
2572   if (LoExists && HiExists)
2573     return SDValue();
2574
2575   // If the two computed results can be simplified separately, separate them.
2576   if (LoExists) {
2577     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2578     AddToWorklist(Lo.getNode());
2579     SDValue LoOpt = combine(Lo.getNode());
2580     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2581         (!LegalOperations ||
2582          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2583       return CombineTo(N, LoOpt, LoOpt);
2584   }
2585
2586   if (HiExists) {
2587     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2588     AddToWorklist(Hi.getNode());
2589     SDValue HiOpt = combine(Hi.getNode());
2590     if (HiOpt.getNode() && HiOpt != Hi &&
2591         (!LegalOperations ||
2592          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2593       return CombineTo(N, HiOpt, HiOpt);
2594   }
2595
2596   return SDValue();
2597 }
2598
2599 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2600   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
2601     return Res;
2602
2603   EVT VT = N->getValueType(0);
2604   SDLoc DL(N);
2605
2606   // If the type is twice as wide is legal, transform the mulhu to a wider
2607   // multiply plus a shift.
2608   if (VT.isSimple() && !VT.isVector()) {
2609     MVT Simple = VT.getSimpleVT();
2610     unsigned SimpleSize = Simple.getSizeInBits();
2611     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2612     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2613       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2614       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2615       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2616       // Compute the high part as N1.
2617       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2618             DAG.getConstant(SimpleSize, DL,
2619                             getShiftAmountTy(Lo.getValueType())));
2620       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2621       // Compute the low part as N0.
2622       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2623       return CombineTo(N, Lo, Hi);
2624     }
2625   }
2626
2627   return SDValue();
2628 }
2629
2630 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2631   if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
2632     return Res;
2633
2634   EVT VT = N->getValueType(0);
2635   SDLoc DL(N);
2636
2637   // If the type is twice as wide is legal, transform the mulhu to a wider
2638   // multiply plus a shift.
2639   if (VT.isSimple() && !VT.isVector()) {
2640     MVT Simple = VT.getSimpleVT();
2641     unsigned SimpleSize = Simple.getSizeInBits();
2642     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2643     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2644       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2645       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2646       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2647       // Compute the high part as N1.
2648       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2649             DAG.getConstant(SimpleSize, DL,
2650                             getShiftAmountTy(Lo.getValueType())));
2651       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2652       // Compute the low part as N0.
2653       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2654       return CombineTo(N, Lo, Hi);
2655     }
2656   }
2657
2658   return SDValue();
2659 }
2660
2661 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2662   // (smulo x, 2) -> (saddo x, x)
2663   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2664     if (C2->getAPIntValue() == 2)
2665       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2666                          N->getOperand(0), N->getOperand(0));
2667
2668   return SDValue();
2669 }
2670
2671 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2672   // (umulo x, 2) -> (uaddo x, x)
2673   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2674     if (C2->getAPIntValue() == 2)
2675       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2676                          N->getOperand(0), N->getOperand(0));
2677
2678   return SDValue();
2679 }
2680
2681 SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
2682   SDValue N0 = N->getOperand(0);
2683   SDValue N1 = N->getOperand(1);
2684   EVT VT = N0.getValueType();
2685
2686   // fold vector ops
2687   if (VT.isVector())
2688     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2689       return FoldedVOp;
2690
2691   // fold (add c1, c2) -> c1+c2
2692   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
2693   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
2694   if (N0C && N1C)
2695     return DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, N0C, N1C);
2696
2697   // canonicalize constant to RHS
2698   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2699      !isConstantIntBuildVectorOrConstantInt(N1))
2700     return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
2701
2702   return SDValue();
2703 }
2704
2705 /// If this is a binary operator with two operands of the same opcode, try to
2706 /// simplify it.
2707 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2708   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2709   EVT VT = N0.getValueType();
2710   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2711
2712   // Bail early if none of these transforms apply.
2713   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2714
2715   // For each of OP in AND/OR/XOR:
2716   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2717   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2718   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2719   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2720   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2721   //
2722   // do not sink logical op inside of a vector extend, since it may combine
2723   // into a vsetcc.
2724   EVT Op0VT = N0.getOperand(0).getValueType();
2725   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2726        N0.getOpcode() == ISD::SIGN_EXTEND ||
2727        N0.getOpcode() == ISD::BSWAP ||
2728        // Avoid infinite looping with PromoteIntBinOp.
2729        (N0.getOpcode() == ISD::ANY_EXTEND &&
2730         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2731        (N0.getOpcode() == ISD::TRUNCATE &&
2732         (!TLI.isZExtFree(VT, Op0VT) ||
2733          !TLI.isTruncateFree(Op0VT, VT)) &&
2734         TLI.isTypeLegal(Op0VT))) &&
2735       !VT.isVector() &&
2736       Op0VT == N1.getOperand(0).getValueType() &&
2737       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2738     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2739                                  N0.getOperand(0).getValueType(),
2740                                  N0.getOperand(0), N1.getOperand(0));
2741     AddToWorklist(ORNode.getNode());
2742     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2743   }
2744
2745   // For each of OP in SHL/SRL/SRA/AND...
2746   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2747   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2748   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2749   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2750        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2751       N0.getOperand(1) == N1.getOperand(1)) {
2752     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2753                                  N0.getOperand(0).getValueType(),
2754                                  N0.getOperand(0), N1.getOperand(0));
2755     AddToWorklist(ORNode.getNode());
2756     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2757                        ORNode, N0.getOperand(1));
2758   }
2759
2760   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2761   // Only perform this optimization after type legalization and before
2762   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2763   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2764   // we don't want to undo this promotion.
2765   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2766   // on scalars.
2767   if ((N0.getOpcode() == ISD::BITCAST ||
2768        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2769       Level == AfterLegalizeTypes) {
2770     SDValue In0 = N0.getOperand(0);
2771     SDValue In1 = N1.getOperand(0);
2772     EVT In0Ty = In0.getValueType();
2773     EVT In1Ty = In1.getValueType();
2774     SDLoc DL(N);
2775     // If both incoming values are integers, and the original types are the
2776     // same.
2777     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2778       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2779       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2780       AddToWorklist(Op.getNode());
2781       return BC;
2782     }
2783   }
2784
2785   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2786   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2787   // If both shuffles use the same mask, and both shuffle within a single
2788   // vector, then it is worthwhile to move the swizzle after the operation.
2789   // The type-legalizer generates this pattern when loading illegal
2790   // vector types from memory. In many cases this allows additional shuffle
2791   // optimizations.
2792   // There are other cases where moving the shuffle after the xor/and/or
2793   // is profitable even if shuffles don't perform a swizzle.
2794   // If both shuffles use the same mask, and both shuffles have the same first
2795   // or second operand, then it might still be profitable to move the shuffle
2796   // after the xor/and/or operation.
2797   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2798     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2799     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2800
2801     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2802            "Inputs to shuffles are not the same type");
2803
2804     // Check that both shuffles use the same mask. The masks are known to be of
2805     // the same length because the result vector type is the same.
2806     // Check also that shuffles have only one use to avoid introducing extra
2807     // instructions.
2808     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2809         SVN0->getMask().equals(SVN1->getMask())) {
2810       SDValue ShOp = N0->getOperand(1);
2811
2812       // Don't try to fold this node if it requires introducing a
2813       // build vector of all zeros that might be illegal at this stage.
2814       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2815         if (!LegalTypes)
2816           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2817         else
2818           ShOp = SDValue();
2819       }
2820
2821       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2822       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2823       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2824       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2825         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2826                                       N0->getOperand(0), N1->getOperand(0));
2827         AddToWorklist(NewNode.getNode());
2828         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2829                                     &SVN0->getMask()[0]);
2830       }
2831
2832       // Don't try to fold this node if it requires introducing a
2833       // build vector of all zeros that might be illegal at this stage.
2834       ShOp = N0->getOperand(0);
2835       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2836         if (!LegalTypes)
2837           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2838         else
2839           ShOp = SDValue();
2840       }
2841
2842       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2843       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2844       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2845       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2846         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2847                                       N0->getOperand(1), N1->getOperand(1));
2848         AddToWorklist(NewNode.getNode());
2849         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2850                                     &SVN0->getMask()[0]);
2851       }
2852     }
2853   }
2854
2855   return SDValue();
2856 }
2857
2858 /// This contains all DAGCombine rules which reduce two values combined by
2859 /// an And operation to a single value. This makes them reusable in the context
2860 /// of visitSELECT(). Rules involving constants are not included as
2861 /// visitSELECT() already handles those cases.
2862 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2863                                   SDNode *LocReference) {
2864   EVT VT = N1.getValueType();
2865
2866   // fold (and x, undef) -> 0
2867   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2868     return DAG.getConstant(0, SDLoc(LocReference), VT);
2869   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2870   SDValue LL, LR, RL, RR, CC0, CC1;
2871   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2872     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2873     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2874
2875     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2876         LL.getValueType().isInteger()) {
2877       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2878       if (isNullConstant(LR) && Op1 == ISD::SETEQ) {
2879         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2880                                      LR.getValueType(), LL, RL);
2881         AddToWorklist(ORNode.getNode());
2882         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2883       }
2884       if (isAllOnesConstant(LR)) {
2885         // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2886         if (Op1 == ISD::SETEQ) {
2887           SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2888                                         LR.getValueType(), LL, RL);
2889           AddToWorklist(ANDNode.getNode());
2890           return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2891         }
2892         // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2893         if (Op1 == ISD::SETGT) {
2894           SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2895                                        LR.getValueType(), LL, RL);
2896           AddToWorklist(ORNode.getNode());
2897           return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2898         }
2899       }
2900     }
2901     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2902     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2903         Op0 == Op1 && LL.getValueType().isInteger() &&
2904       Op0 == ISD::SETNE && ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
2905                             (isAllOnesConstant(LR) && isNullConstant(RR)))) {
2906       SDLoc DL(N0);
2907       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2908                                     LL, DAG.getConstant(1, DL,
2909                                                         LL.getValueType()));
2910       AddToWorklist(ADDNode.getNode());
2911       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2912                           DAG.getConstant(2, DL, LL.getValueType()),
2913                           ISD::SETUGE);
2914     }
2915     // canonicalize equivalent to ll == rl
2916     if (LL == RR && LR == RL) {
2917       Op1 = ISD::getSetCCSwappedOperands(Op1);
2918       std::swap(RL, RR);
2919     }
2920     if (LL == RL && LR == RR) {
2921       bool isInteger = LL.getValueType().isInteger();
2922       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2923       if (Result != ISD::SETCC_INVALID &&
2924           (!LegalOperations ||
2925            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2926             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
2927         EVT CCVT = getSetCCResultType(LL.getValueType());
2928         if (N0.getValueType() == CCVT ||
2929             (!LegalOperations && N0.getValueType() == MVT::i1))
2930           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2931                               LL, LR, Result);
2932       }
2933     }
2934   }
2935
2936   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937       VT.getSizeInBits() <= 64) {
2938     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939       APInt ADDC = ADDI->getAPIntValue();
2940       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942         // immediate for an add, but it is legal if its top c2 bits are set,
2943         // transform the ADD so the immediate doesn't need to be materialized
2944         // in a register.
2945         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947                                              SRLI->getZExtValue());
2948           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2949             ADDC |= Mask;
2950             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2951               SDLoc DL(N0);
2952               SDValue NewAdd =
2953                 DAG.getNode(ISD::ADD, DL, VT,
2954                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2955               CombineTo(N0.getNode(), NewAdd);
2956               // Return N so it doesn't get rechecked!
2957               return SDValue(LocReference, 0);
2958             }
2959           }
2960         }
2961       }
2962     }
2963   }
2964
2965   return SDValue();
2966 }
2967
2968 SDValue DAGCombiner::visitAND(SDNode *N) {
2969   SDValue N0 = N->getOperand(0);
2970   SDValue N1 = N->getOperand(1);
2971   EVT VT = N1.getValueType();
2972
2973   // fold vector ops
2974   if (VT.isVector()) {
2975     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2976       return FoldedVOp;
2977
2978     // fold (and x, 0) -> 0, vector edition
2979     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2980       // do not return N0, because undef node may exist in N0
2981       return DAG.getConstant(
2982           APInt::getNullValue(
2983               N0.getValueType().getScalarType().getSizeInBits()),
2984           SDLoc(N), N0.getValueType());
2985     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2986       // do not return N1, because undef node may exist in N1
2987       return DAG.getConstant(
2988           APInt::getNullValue(
2989               N1.getValueType().getScalarType().getSizeInBits()),
2990           SDLoc(N), N1.getValueType());
2991
2992     // fold (and x, -1) -> x, vector edition
2993     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2994       return N1;
2995     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2996       return N0;
2997   }
2998
2999   // fold (and c1, c2) -> c1&c2
3000   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3001   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3002   if (N0C && N1C && !N1C->isOpaque())
3003     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
3004   // canonicalize constant to RHS
3005   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3006      !isConstantIntBuildVectorOrConstantInt(N1))
3007     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
3008   // fold (and x, -1) -> x
3009   if (isAllOnesConstant(N1))
3010     return N0;
3011   // if (and x, c) is known to be zero, return 0
3012   unsigned BitWidth = VT.getScalarType().getSizeInBits();
3013   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3014                                    APInt::getAllOnesValue(BitWidth)))
3015     return DAG.getConstant(0, SDLoc(N), VT);
3016   // reassociate and
3017   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
3018     return RAND;
3019   // fold (and (or x, C), D) -> D if (C & D) == D
3020   if (N1C && N0.getOpcode() == ISD::OR)
3021     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3022       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
3023         return N1;
3024   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
3025   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3026     SDValue N0Op0 = N0.getOperand(0);
3027     APInt Mask = ~N1C->getAPIntValue();
3028     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
3029     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
3030       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
3031                                  N0.getValueType(), N0Op0);
3032
3033       // Replace uses of the AND with uses of the Zero extend node.
3034       CombineTo(N, Zext);
3035
3036       // We actually want to replace all uses of the any_extend with the
3037       // zero_extend, to avoid duplicating things.  This will later cause this
3038       // AND to be folded.
3039       CombineTo(N0.getNode(), Zext);
3040       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3041     }
3042   }
3043   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
3044   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
3045   // already be zero by virtue of the width of the base type of the load.
3046   //
3047   // the 'X' node here can either be nothing or an extract_vector_elt to catch
3048   // more cases.
3049   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
3050        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
3051       N0.getOpcode() == ISD::LOAD) {
3052     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
3053                                          N0 : N0.getOperand(0) );
3054
3055     // Get the constant (if applicable) the zero'th operand is being ANDed with.
3056     // This can be a pure constant or a vector splat, in which case we treat the
3057     // vector as a scalar and use the splat value.
3058     APInt Constant = APInt::getNullValue(1);
3059     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
3060       Constant = C->getAPIntValue();
3061     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
3062       APInt SplatValue, SplatUndef;
3063       unsigned SplatBitSize;
3064       bool HasAnyUndefs;
3065       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
3066                                              SplatBitSize, HasAnyUndefs);
3067       if (IsSplat) {
3068         // Undef bits can contribute to a possible optimisation if set, so
3069         // set them.
3070         SplatValue |= SplatUndef;
3071
3072         // The splat value may be something like "0x00FFFFFF", which means 0 for
3073         // the first vector value and FF for the rest, repeating. We need a mask
3074         // that will apply equally to all members of the vector, so AND all the
3075         // lanes of the constant together.
3076         EVT VT = Vector->getValueType(0);
3077         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
3078
3079         // If the splat value has been compressed to a bitlength lower
3080         // than the size of the vector lane, we need to re-expand it to
3081         // the lane size.
3082         if (BitWidth > SplatBitSize)
3083           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
3084                SplatBitSize < BitWidth;
3085                SplatBitSize = SplatBitSize * 2)
3086             SplatValue |= SplatValue.shl(SplatBitSize);
3087
3088         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
3089         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
3090         if (SplatBitSize % BitWidth == 0) {
3091           Constant = APInt::getAllOnesValue(BitWidth);
3092           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
3093             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
3094         }
3095       }
3096     }
3097
3098     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
3099     // actually legal and isn't going to get expanded, else this is a false
3100     // optimisation.
3101     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
3102                                                     Load->getValueType(0),
3103                                                     Load->getMemoryVT());
3104
3105     // Resize the constant to the same size as the original memory access before
3106     // extension. If it is still the AllOnesValue then this AND is completely
3107     // unneeded.
3108     Constant =
3109       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
3110
3111     bool B;
3112     switch (Load->getExtensionType()) {
3113     default: B = false; break;
3114     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
3115     case ISD::ZEXTLOAD:
3116     case ISD::NON_EXTLOAD: B = true; break;
3117     }
3118
3119     if (B && Constant.isAllOnesValue()) {
3120       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
3121       // preserve semantics once we get rid of the AND.
3122       SDValue NewLoad(Load, 0);
3123       if (Load->getExtensionType() == ISD::EXTLOAD) {
3124         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
3125                               Load->getValueType(0), SDLoc(Load),
3126                               Load->getChain(), Load->getBasePtr(),
3127                               Load->getOffset(), Load->getMemoryVT(),
3128                               Load->getMemOperand());
3129         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3130         if (Load->getNumValues() == 3) {
3131           // PRE/POST_INC loads have 3 values.
3132           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3133                            NewLoad.getValue(2) };
3134           CombineTo(Load, To, 3, true);
3135         } else {
3136           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3137         }
3138       }
3139
3140       // Fold the AND away, taking care not to fold to the old load node if we
3141       // replaced it.
3142       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3143
3144       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3145     }
3146   }
3147
3148   // fold (and (load x), 255) -> (zextload x, i8)
3149   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3150   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3151   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3152               (N0.getOpcode() == ISD::ANY_EXTEND &&
3153                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3154     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3155     LoadSDNode *LN0 = HasAnyExt
3156       ? cast<LoadSDNode>(N0.getOperand(0))
3157       : cast<LoadSDNode>(N0);
3158     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3159         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3160       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3161       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3162         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3163         EVT LoadedVT = LN0->getMemoryVT();
3164         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3165
3166         if (ExtVT == LoadedVT &&
3167             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3168                                                     ExtVT))) {
3169
3170           SDValue NewLoad =
3171             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3172                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3173                            LN0->getMemOperand());
3174           AddToWorklist(N);
3175           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3176           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3177         }
3178
3179         // Do not change the width of a volatile load.
3180         // Do not generate loads of non-round integer types since these can
3181         // be expensive (and would be wrong if the type is not byte sized).
3182         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3183             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3184                                                     ExtVT))) {
3185           EVT PtrType = LN0->getOperand(1).getValueType();
3186
3187           unsigned Alignment = LN0->getAlignment();
3188           SDValue NewPtr = LN0->getBasePtr();
3189
3190           // For big endian targets, we need to add an offset to the pointer
3191           // to load the correct bytes.  For little endian systems, we merely
3192           // need to read fewer bytes from the same pointer.
3193           if (DAG.getDataLayout().isBigEndian()) {
3194             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3195             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3196             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3197             SDLoc DL(LN0);
3198             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3199                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3200             Alignment = MinAlign(Alignment, PtrOff);
3201           }
3202
3203           AddToWorklist(NewPtr.getNode());
3204
3205           SDValue Load =
3206             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3207                            LN0->getChain(), NewPtr,
3208                            LN0->getPointerInfo(),
3209                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3210                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3211           AddToWorklist(N);
3212           CombineTo(LN0, Load, Load.getValue(1));
3213           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3214         }
3215       }
3216     }
3217   }
3218
3219   if (SDValue Combined = visitANDLike(N0, N1, N))
3220     return Combined;
3221
3222   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3223   if (N0.getOpcode() == N1.getOpcode())
3224     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3225       return Tmp;
3226
3227   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3228   // fold (and (sra)) -> (and (srl)) when possible.
3229   if (!VT.isVector() &&
3230       SimplifyDemandedBits(SDValue(N, 0)))
3231     return SDValue(N, 0);
3232
3233   // fold (zext_inreg (extload x)) -> (zextload x)
3234   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3235     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3236     EVT MemVT = LN0->getMemoryVT();
3237     // If we zero all the possible extended bits, then we can turn this into
3238     // a zextload if we are running before legalize or the operation is legal.
3239     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3240     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3241                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3242         ((!LegalOperations && !LN0->isVolatile()) ||
3243          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3244       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3245                                        LN0->getChain(), LN0->getBasePtr(),
3246                                        MemVT, LN0->getMemOperand());
3247       AddToWorklist(N);
3248       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3249       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3250     }
3251   }
3252   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3253   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3254       N0.hasOneUse()) {
3255     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3256     EVT MemVT = LN0->getMemoryVT();
3257     // If we zero all the possible extended bits, then we can turn this into
3258     // a zextload if we are running before legalize or the operation is legal.
3259     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3260     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3261                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3262         ((!LegalOperations && !LN0->isVolatile()) ||
3263          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3264       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3265                                        LN0->getChain(), LN0->getBasePtr(),
3266                                        MemVT, LN0->getMemOperand());
3267       AddToWorklist(N);
3268       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3269       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3270     }
3271   }
3272   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3273   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3274     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3275                                        N0.getOperand(1), false);
3276     if (BSwap.getNode())
3277       return BSwap;
3278   }
3279
3280   return SDValue();
3281 }
3282
3283 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3284 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3285                                         bool DemandHighBits) {
3286   if (!LegalOperations)
3287     return SDValue();
3288
3289   EVT VT = N->getValueType(0);
3290   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3291     return SDValue();
3292   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3293     return SDValue();
3294
3295   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3296   bool LookPassAnd0 = false;
3297   bool LookPassAnd1 = false;
3298   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3299       std::swap(N0, N1);
3300   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3301       std::swap(N0, N1);
3302   if (N0.getOpcode() == ISD::AND) {
3303     if (!N0.getNode()->hasOneUse())
3304       return SDValue();
3305     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306     if (!N01C || N01C->getZExtValue() != 0xFF00)
3307       return SDValue();
3308     N0 = N0.getOperand(0);
3309     LookPassAnd0 = true;
3310   }
3311
3312   if (N1.getOpcode() == ISD::AND) {
3313     if (!N1.getNode()->hasOneUse())
3314       return SDValue();
3315     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3316     if (!N11C || N11C->getZExtValue() != 0xFF)
3317       return SDValue();
3318     N1 = N1.getOperand(0);
3319     LookPassAnd1 = true;
3320   }
3321
3322   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3323     std::swap(N0, N1);
3324   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3325     return SDValue();
3326   if (!N0.getNode()->hasOneUse() ||
3327       !N1.getNode()->hasOneUse())
3328     return SDValue();
3329
3330   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3331   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3332   if (!N01C || !N11C)
3333     return SDValue();
3334   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3335     return SDValue();
3336
3337   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3338   SDValue N00 = N0->getOperand(0);
3339   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3340     if (!N00.getNode()->hasOneUse())
3341       return SDValue();
3342     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3343     if (!N001C || N001C->getZExtValue() != 0xFF)
3344       return SDValue();
3345     N00 = N00.getOperand(0);
3346     LookPassAnd0 = true;
3347   }
3348
3349   SDValue N10 = N1->getOperand(0);
3350   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3351     if (!N10.getNode()->hasOneUse())
3352       return SDValue();
3353     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3354     if (!N101C || N101C->getZExtValue() != 0xFF00)
3355       return SDValue();
3356     N10 = N10.getOperand(0);
3357     LookPassAnd1 = true;
3358   }
3359
3360   if (N00 != N10)
3361     return SDValue();
3362
3363   // Make sure everything beyond the low halfword gets set to zero since the SRL
3364   // 16 will clear the top bits.
3365   unsigned OpSizeInBits = VT.getSizeInBits();
3366   if (DemandHighBits && OpSizeInBits > 16) {
3367     // If the left-shift isn't masked out then the only way this is a bswap is
3368     // if all bits beyond the low 8 are 0. In that case the entire pattern
3369     // reduces to a left shift anyway: leave it for other parts of the combiner.
3370     if (!LookPassAnd0)
3371       return SDValue();
3372
3373     // However, if the right shift isn't masked out then it might be because
3374     // it's not needed. See if we can spot that too.
3375     if (!LookPassAnd1 &&
3376         !DAG.MaskedValueIsZero(
3377             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3378       return SDValue();
3379   }
3380
3381   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3382   if (OpSizeInBits > 16) {
3383     SDLoc DL(N);
3384     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3385                       DAG.getConstant(OpSizeInBits - 16, DL,
3386                                       getShiftAmountTy(VT)));
3387   }
3388   return Res;
3389 }
3390
3391 /// Return true if the specified node is an element that makes up a 32-bit
3392 /// packed halfword byteswap.
3393 /// ((x & 0x000000ff) << 8) |
3394 /// ((x & 0x0000ff00) >> 8) |
3395 /// ((x & 0x00ff0000) << 8) |
3396 /// ((x & 0xff000000) >> 8)
3397 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3398   if (!N.getNode()->hasOneUse())
3399     return false;
3400
3401   unsigned Opc = N.getOpcode();
3402   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3403     return false;
3404
3405   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3406   if (!N1C)
3407     return false;
3408
3409   unsigned Num;
3410   switch (N1C->getZExtValue()) {
3411   default:
3412     return false;
3413   case 0xFF:       Num = 0; break;
3414   case 0xFF00:     Num = 1; break;
3415   case 0xFF0000:   Num = 2; break;
3416   case 0xFF000000: Num = 3; break;
3417   }
3418
3419   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3420   SDValue N0 = N.getOperand(0);
3421   if (Opc == ISD::AND) {
3422     if (Num == 0 || Num == 2) {
3423       // (x >> 8) & 0xff
3424       // (x >> 8) & 0xff0000
3425       if (N0.getOpcode() != ISD::SRL)
3426         return false;
3427       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3428       if (!C || C->getZExtValue() != 8)
3429         return false;
3430     } else {
3431       // (x << 8) & 0xff00
3432       // (x << 8) & 0xff000000
3433       if (N0.getOpcode() != ISD::SHL)
3434         return false;
3435       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3436       if (!C || C->getZExtValue() != 8)
3437         return false;
3438     }
3439   } else if (Opc == ISD::SHL) {
3440     // (x & 0xff) << 8
3441     // (x & 0xff0000) << 8
3442     if (Num != 0 && Num != 2)
3443       return false;
3444     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3445     if (!C || C->getZExtValue() != 8)
3446       return false;
3447   } else { // Opc == ISD::SRL
3448     // (x & 0xff00) >> 8
3449     // (x & 0xff000000) >> 8
3450     if (Num != 1 && Num != 3)
3451       return false;
3452     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3453     if (!C || C->getZExtValue() != 8)
3454       return false;
3455   }
3456
3457   if (Parts[Num])
3458     return false;
3459
3460   Parts[Num] = N0.getOperand(0).getNode();
3461   return true;
3462 }
3463
3464 /// Match a 32-bit packed halfword bswap. That is
3465 /// ((x & 0x000000ff) << 8) |
3466 /// ((x & 0x0000ff00) >> 8) |
3467 /// ((x & 0x00ff0000) << 8) |
3468 /// ((x & 0xff000000) >> 8)
3469 /// => (rotl (bswap x), 16)
3470 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3471   if (!LegalOperations)
3472     return SDValue();
3473
3474   EVT VT = N->getValueType(0);
3475   if (VT != MVT::i32)
3476     return SDValue();
3477   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3478     return SDValue();
3479
3480   // Look for either
3481   // (or (or (and), (and)), (or (and), (and)))
3482   // (or (or (or (and), (and)), (and)), (and))
3483   if (N0.getOpcode() != ISD::OR)
3484     return SDValue();
3485   SDValue N00 = N0.getOperand(0);
3486   SDValue N01 = N0.getOperand(1);
3487   SDNode *Parts[4] = {};
3488
3489   if (N1.getOpcode() == ISD::OR &&
3490       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3491     // (or (or (and), (and)), (or (and), (and)))
3492     SDValue N000 = N00.getOperand(0);
3493     if (!isBSwapHWordElement(N000, Parts))
3494       return SDValue();
3495
3496     SDValue N001 = N00.getOperand(1);
3497     if (!isBSwapHWordElement(N001, Parts))
3498       return SDValue();
3499     SDValue N010 = N01.getOperand(0);
3500     if (!isBSwapHWordElement(N010, Parts))
3501       return SDValue();
3502     SDValue N011 = N01.getOperand(1);
3503     if (!isBSwapHWordElement(N011, Parts))
3504       return SDValue();
3505   } else {
3506     // (or (or (or (and), (and)), (and)), (and))
3507     if (!isBSwapHWordElement(N1, Parts))
3508       return SDValue();
3509     if (!isBSwapHWordElement(N01, Parts))
3510       return SDValue();
3511     if (N00.getOpcode() != ISD::OR)
3512       return SDValue();
3513     SDValue N000 = N00.getOperand(0);
3514     if (!isBSwapHWordElement(N000, Parts))
3515       return SDValue();
3516     SDValue N001 = N00.getOperand(1);
3517     if (!isBSwapHWordElement(N001, Parts))
3518       return SDValue();
3519   }
3520
3521   // Make sure the parts are all coming from the same node.
3522   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3523     return SDValue();
3524
3525   SDLoc DL(N);
3526   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3527                               SDValue(Parts[0], 0));
3528
3529   // Result of the bswap should be rotated by 16. If it's not legal, then
3530   // do  (x << 16) | (x >> 16).
3531   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3532   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3533     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3534   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3535     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3536   return DAG.getNode(ISD::OR, DL, VT,
3537                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3538                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3539 }
3540
3541 /// This contains all DAGCombine rules which reduce two values combined by
3542 /// an Or operation to a single value \see visitANDLike().
3543 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3544   EVT VT = N1.getValueType();
3545   // fold (or x, undef) -> -1
3546   if (!LegalOperations &&
3547       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3548     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3549     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3550                            SDLoc(LocReference), VT);
3551   }
3552   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3553   SDValue LL, LR, RL, RR, CC0, CC1;
3554   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3555     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3556     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3557
3558     if (LR == RR && Op0 == Op1 && LL.getValueType().isInteger()) {
3559       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3560       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3561       if (isNullConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3562         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3563                                      LR.getValueType(), LL, RL);
3564         AddToWorklist(ORNode.getNode());
3565         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3566       }
3567       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3568       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3569       if (isAllOnesConstant(LR) && (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3570         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3571                                       LR.getValueType(), LL, RL);
3572         AddToWorklist(ANDNode.getNode());
3573         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3574       }
3575     }
3576     // canonicalize equivalent to ll == rl
3577     if (LL == RR && LR == RL) {
3578       Op1 = ISD::getSetCCSwappedOperands(Op1);
3579       std::swap(RL, RR);
3580     }
3581     if (LL == RL && LR == RR) {
3582       bool isInteger = LL.getValueType().isInteger();
3583       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3584       if (Result != ISD::SETCC_INVALID &&
3585           (!LegalOperations ||
3586            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3587             TLI.isOperationLegal(ISD::SETCC, LL.getValueType())))) {
3588         EVT CCVT = getSetCCResultType(LL.getValueType());
3589         if (N0.getValueType() == CCVT ||
3590             (!LegalOperations && N0.getValueType() == MVT::i1))
3591           return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3592                               LL, LR, Result);
3593       }
3594     }
3595   }
3596
3597   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3598   if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
3599       // Don't increase # computations.
3600       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3601     // We can only do this xform if we know that bits from X that are set in C2
3602     // but not in C1 are already zero.  Likewise for Y.
3603     if (const ConstantSDNode *N0O1C =
3604         getAsNonOpaqueConstant(N0.getOperand(1))) {
3605       if (const ConstantSDNode *N1O1C =
3606           getAsNonOpaqueConstant(N1.getOperand(1))) {
3607         // We can only do this xform if we know that bits from X that are set in
3608         // C2 but not in C1 are already zero.  Likewise for Y.
3609         const APInt &LHSMask = N0O1C->getAPIntValue();
3610         const APInt &RHSMask = N1O1C->getAPIntValue();
3611
3612         if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3613             DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3614           SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3615                                   N0.getOperand(0), N1.getOperand(0));
3616           SDLoc DL(LocReference);
3617           return DAG.getNode(ISD::AND, DL, VT, X,
3618                              DAG.getConstant(LHSMask | RHSMask, DL, VT));
3619         }
3620       }
3621     }
3622   }
3623
3624   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3625   if (N0.getOpcode() == ISD::AND &&
3626       N1.getOpcode() == ISD::AND &&
3627       N0.getOperand(0) == N1.getOperand(0) &&
3628       // Don't increase # computations.
3629       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3630     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3631                             N0.getOperand(1), N1.getOperand(1));
3632     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3633   }
3634
3635   return SDValue();
3636 }
3637
3638 SDValue DAGCombiner::visitOR(SDNode *N) {
3639   SDValue N0 = N->getOperand(0);
3640   SDValue N1 = N->getOperand(1);
3641   EVT VT = N1.getValueType();
3642
3643   // fold vector ops
3644   if (VT.isVector()) {
3645     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3646       return FoldedVOp;
3647
3648     // fold (or x, 0) -> x, vector edition
3649     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3650       return N1;
3651     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3652       return N0;
3653
3654     // fold (or x, -1) -> -1, vector edition
3655     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3656       // do not return N0, because undef node may exist in N0
3657       return DAG.getConstant(
3658           APInt::getAllOnesValue(
3659               N0.getValueType().getScalarType().getSizeInBits()),
3660           SDLoc(N), N0.getValueType());
3661     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3662       // do not return N1, because undef node may exist in N1
3663       return DAG.getConstant(
3664           APInt::getAllOnesValue(
3665               N1.getValueType().getScalarType().getSizeInBits()),
3666           SDLoc(N), N1.getValueType());
3667
3668     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3669     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3670     // Do this only if the resulting shuffle is legal.
3671     if (isa<ShuffleVectorSDNode>(N0) &&
3672         isa<ShuffleVectorSDNode>(N1) &&
3673         // Avoid folding a node with illegal type.
3674         TLI.isTypeLegal(VT) &&
3675         N0->getOperand(1) == N1->getOperand(1) &&
3676         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3677       bool CanFold = true;
3678       unsigned NumElts = VT.getVectorNumElements();
3679       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3680       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3681       // We construct two shuffle masks:
3682       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3683       // and N1 as the second operand.
3684       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3685       // and N0 as the second operand.
3686       // We do this because OR is commutable and therefore there might be
3687       // two ways to fold this node into a shuffle.
3688       SmallVector<int,4> Mask1;
3689       SmallVector<int,4> Mask2;
3690
3691       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3692         int M0 = SV0->getMaskElt(i);
3693         int M1 = SV1->getMaskElt(i);
3694
3695         // Both shuffle indexes are undef. Propagate Undef.
3696         if (M0 < 0 && M1 < 0) {
3697           Mask1.push_back(M0);
3698           Mask2.push_back(M0);
3699           continue;
3700         }
3701
3702         if (M0 < 0 || M1 < 0 ||
3703             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3704             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3705           CanFold = false;
3706           break;
3707         }
3708
3709         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3710         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3711       }
3712
3713       if (CanFold) {
3714         // Fold this sequence only if the resulting shuffle is 'legal'.
3715         if (TLI.isShuffleMaskLegal(Mask1, VT))
3716           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3717                                       N1->getOperand(0), &Mask1[0]);
3718         if (TLI.isShuffleMaskLegal(Mask2, VT))
3719           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3720                                       N0->getOperand(0), &Mask2[0]);
3721       }
3722     }
3723   }
3724
3725   // fold (or c1, c2) -> c1|c2
3726   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
3727   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3728   if (N0C && N1C && !N1C->isOpaque())
3729     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3730   // canonicalize constant to RHS
3731   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3732      !isConstantIntBuildVectorOrConstantInt(N1))
3733     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3734   // fold (or x, 0) -> x
3735   if (isNullConstant(N1))
3736     return N0;
3737   // fold (or x, -1) -> -1
3738   if (isAllOnesConstant(N1))
3739     return N1;
3740   // fold (or x, c) -> c iff (x & ~c) == 0
3741   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3742     return N1;
3743
3744   if (SDValue Combined = visitORLike(N0, N1, N))
3745     return Combined;
3746
3747   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3748   if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
3749     return BSwap;
3750   if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
3751     return BSwap;
3752
3753   // reassociate or
3754   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3755     return ROR;
3756   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3757   // iff (c1 & c2) == 0.
3758   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3759              isa<ConstantSDNode>(N0.getOperand(1))) {
3760     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3761     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3762       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3763                                                    N1C, C1))
3764         return DAG.getNode(
3765             ISD::AND, SDLoc(N), VT,
3766             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3767       return SDValue();
3768     }
3769   }
3770   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3771   if (N0.getOpcode() == N1.getOpcode())
3772     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
3773       return Tmp;
3774
3775   // See if this is some rotate idiom.
3776   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3777     return SDValue(Rot, 0);
3778
3779   // Simplify the operands using demanded-bits information.
3780   if (!VT.isVector() &&
3781       SimplifyDemandedBits(SDValue(N, 0)))
3782     return SDValue(N, 0);
3783
3784   return SDValue();
3785 }
3786
3787 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3788 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3789   if (Op.getOpcode() == ISD::AND) {
3790     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3791       Mask = Op.getOperand(1);
3792       Op = Op.getOperand(0);
3793     } else {
3794       return false;
3795     }
3796   }
3797
3798   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3799     Shift = Op;
3800     return true;
3801   }
3802
3803   return false;
3804 }
3805
3806 // Return true if we can prove that, whenever Neg and Pos are both in the
3807 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3808 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3809 //
3810 //     (or (shift1 X, Neg), (shift2 X, Pos))
3811 //
3812 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3813 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3814 // to consider shift amounts with defined behavior.
3815 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3816   // If OpSize is a power of 2 then:
3817   //
3818   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3819   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3820   //
3821   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3822   // for the stronger condition:
3823   //
3824   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3825   //
3826   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3827   // we can just replace Neg with Neg' for the rest of the function.
3828   //
3829   // In other cases we check for the even stronger condition:
3830   //
3831   //     Neg == OpSize - Pos                                    [B]
3832   //
3833   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3834   // behavior if Pos == 0 (and consequently Neg == OpSize).
3835   //
3836   // We could actually use [A] whenever OpSize is a power of 2, but the
3837   // only extra cases that it would match are those uninteresting ones
3838   // where Neg and Pos are never in range at the same time.  E.g. for
3839   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3840   // as well as (sub 32, Pos), but:
3841   //
3842   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3843   //
3844   // always invokes undefined behavior for 32-bit X.
3845   //
3846   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3847   unsigned MaskLoBits = 0;
3848   if (Neg.getOpcode() == ISD::AND &&
3849       isPowerOf2_64(OpSize) &&
3850       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3851       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3852     Neg = Neg.getOperand(0);
3853     MaskLoBits = Log2_64(OpSize);
3854   }
3855
3856   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3857   if (Neg.getOpcode() != ISD::SUB)
3858     return 0;
3859   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3860   if (!NegC)
3861     return 0;
3862   SDValue NegOp1 = Neg.getOperand(1);
3863
3864   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3865   // Pos'.  The truncation is redundant for the purpose of the equality.
3866   if (MaskLoBits &&
3867       Pos.getOpcode() == ISD::AND &&
3868       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3869       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3870     Pos = Pos.getOperand(0);
3871
3872   // The condition we need is now:
3873   //
3874   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3875   //
3876   // If NegOp1 == Pos then we need:
3877   //
3878   //              OpSize & Mask == NegC & Mask
3879   //
3880   // (because "x & Mask" is a truncation and distributes through subtraction).
3881   APInt Width;
3882   if (Pos == NegOp1)
3883     Width = NegC->getAPIntValue();
3884   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3885   // Then the condition we want to prove becomes:
3886   //
3887   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3888   //
3889   // which, again because "x & Mask" is a truncation, becomes:
3890   //
3891   //                NegC & Mask == (OpSize - PosC) & Mask
3892   //              OpSize & Mask == (NegC + PosC) & Mask
3893   else if (Pos.getOpcode() == ISD::ADD &&
3894            Pos.getOperand(0) == NegOp1 &&
3895            Pos.getOperand(1).getOpcode() == ISD::Constant)
3896     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3897              NegC->getAPIntValue());
3898   else
3899     return false;
3900
3901   // Now we just need to check that OpSize & Mask == Width & Mask.
3902   if (MaskLoBits)
3903     // Opsize & Mask is 0 since Mask is Opsize - 1.
3904     return Width.getLoBits(MaskLoBits) == 0;
3905   return Width == OpSize;
3906 }
3907
3908 // A subroutine of MatchRotate used once we have found an OR of two opposite
3909 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3910 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3911 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3912 // Neg with outer conversions stripped away.
3913 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3914                                        SDValue Neg, SDValue InnerPos,
3915                                        SDValue InnerNeg, unsigned PosOpcode,
3916                                        unsigned NegOpcode, SDLoc DL) {
3917   // fold (or (shl x, (*ext y)),
3918   //          (srl x, (*ext (sub 32, y)))) ->
3919   //   (rotl x, y) or (rotr x, (sub 32, y))
3920   //
3921   // fold (or (shl x, (*ext (sub 32, y))),
3922   //          (srl x, (*ext y))) ->
3923   //   (rotr x, y) or (rotl x, (sub 32, y))
3924   EVT VT = Shifted.getValueType();
3925   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3926     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3927     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3928                        HasPos ? Pos : Neg).getNode();
3929   }
3930
3931   return nullptr;
3932 }
3933
3934 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3935 // idioms for rotate, and if the target supports rotation instructions, generate
3936 // a rot[lr].
3937 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3938   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3939   EVT VT = LHS.getValueType();
3940   if (!TLI.isTypeLegal(VT)) return nullptr;
3941
3942   // The target must have at least one rotate flavor.
3943   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3944   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3945   if (!HasROTL && !HasROTR) return nullptr;
3946
3947   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3948   SDValue LHSShift;   // The shift.
3949   SDValue LHSMask;    // AND value if any.
3950   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3951     return nullptr; // Not part of a rotate.
3952
3953   SDValue RHSShift;   // The shift.
3954   SDValue RHSMask;    // AND value if any.
3955   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3956     return nullptr; // Not part of a rotate.
3957
3958   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3959     return nullptr;   // Not shifting the same value.
3960
3961   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3962     return nullptr;   // Shifts must disagree.
3963
3964   // Canonicalize shl to left side in a shl/srl pair.
3965   if (RHSShift.getOpcode() == ISD::SHL) {
3966     std::swap(LHS, RHS);
3967     std::swap(LHSShift, RHSShift);
3968     std::swap(LHSMask , RHSMask );
3969   }
3970
3971   unsigned OpSizeInBits = VT.getSizeInBits();
3972   SDValue LHSShiftArg = LHSShift.getOperand(0);
3973   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3974   SDValue RHSShiftArg = RHSShift.getOperand(0);
3975   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3976
3977   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3978   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3979   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3980       RHSShiftAmt.getOpcode() == ISD::Constant) {
3981     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3982     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3983     if ((LShVal + RShVal) != OpSizeInBits)
3984       return nullptr;
3985
3986     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3987                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3988
3989     // If there is an AND of either shifted operand, apply it to the result.
3990     if (LHSMask.getNode() || RHSMask.getNode()) {
3991       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3992
3993       if (LHSMask.getNode()) {
3994         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3995         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3996       }
3997       if (RHSMask.getNode()) {
3998         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3999         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
4000       }
4001
4002       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
4003     }
4004
4005     return Rot.getNode();
4006   }
4007
4008   // If there is a mask here, and we have a variable shift, we can't be sure
4009   // that we're masking out the right stuff.
4010   if (LHSMask.getNode() || RHSMask.getNode())
4011     return nullptr;
4012
4013   // If the shift amount is sign/zext/any-extended just peel it off.
4014   SDValue LExtOp0 = LHSShiftAmt;
4015   SDValue RExtOp0 = RHSShiftAmt;
4016   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4017        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4018        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4019        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
4020       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
4021        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
4022        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
4023        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
4024     LExtOp0 = LHSShiftAmt.getOperand(0);
4025     RExtOp0 = RHSShiftAmt.getOperand(0);
4026   }
4027
4028   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
4029                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
4030   if (TryL)
4031     return TryL;
4032
4033   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
4034                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
4035   if (TryR)
4036     return TryR;
4037
4038   return nullptr;
4039 }
4040
4041 SDValue DAGCombiner::visitXOR(SDNode *N) {
4042   SDValue N0 = N->getOperand(0);
4043   SDValue N1 = N->getOperand(1);
4044   EVT VT = N0.getValueType();
4045
4046   // fold vector ops
4047   if (VT.isVector()) {
4048     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4049       return FoldedVOp;
4050
4051     // fold (xor x, 0) -> x, vector edition
4052     if (ISD::isBuildVectorAllZeros(N0.getNode()))
4053       return N1;
4054     if (ISD::isBuildVectorAllZeros(N1.getNode()))
4055       return N0;
4056   }
4057
4058   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
4059   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
4060     return DAG.getConstant(0, SDLoc(N), VT);
4061   // fold (xor x, undef) -> undef
4062   if (N0.getOpcode() == ISD::UNDEF)
4063     return N0;
4064   if (N1.getOpcode() == ISD::UNDEF)
4065     return N1;
4066   // fold (xor c1, c2) -> c1^c2
4067   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4068   ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
4069   if (N0C && N1C)
4070     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
4071   // canonicalize constant to RHS
4072   if (isConstantIntBuildVectorOrConstantInt(N0) &&
4073      !isConstantIntBuildVectorOrConstantInt(N1))
4074     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
4075   // fold (xor x, 0) -> x
4076   if (isNullConstant(N1))
4077     return N0;
4078   // reassociate xor
4079   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
4080     return RXOR;
4081
4082   // fold !(x cc y) -> (x !cc y)
4083   SDValue LHS, RHS, CC;
4084   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
4085     bool isInt = LHS.getValueType().isInteger();
4086     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
4087                                                isInt);
4088
4089     if (!LegalOperations ||
4090         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
4091       switch (N0.getOpcode()) {
4092       default:
4093         llvm_unreachable("Unhandled SetCC Equivalent!");
4094       case ISD::SETCC:
4095         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
4096       case ISD::SELECT_CC:
4097         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
4098                                N0.getOperand(3), NotCC);
4099       }
4100     }
4101   }
4102
4103   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
4104   if (isOneConstant(N1) && N0.getOpcode() == ISD::ZERO_EXTEND &&
4105       N0.getNode()->hasOneUse() &&
4106       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
4107     SDValue V = N0.getOperand(0);
4108     SDLoc DL(N0);
4109     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
4110                     DAG.getConstant(1, DL, V.getValueType()));
4111     AddToWorklist(V.getNode());
4112     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
4113   }
4114
4115   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
4116   if (isOneConstant(N1) && VT == MVT::i1 &&
4117       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4118     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4119     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
4120       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4121       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4122       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4123       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4124       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4125     }
4126   }
4127   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4128   if (isAllOnesConstant(N1) &&
4129       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4130     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4131     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4132       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4133       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4134       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4135       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4136       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4137     }
4138   }
4139   // fold (xor (and x, y), y) -> (and (not x), y)
4140   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4141       N0->getOperand(1) == N1) {
4142     SDValue X = N0->getOperand(0);
4143     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4144     AddToWorklist(NotX.getNode());
4145     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4146   }
4147   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4148   if (N1C && N0.getOpcode() == ISD::XOR) {
4149     if (const ConstantSDNode *N00C = getAsNonOpaqueConstant(N0.getOperand(0))) {
4150       SDLoc DL(N);
4151       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4152                          DAG.getConstant(N1C->getAPIntValue() ^
4153                                          N00C->getAPIntValue(), DL, VT));
4154     }
4155     if (const ConstantSDNode *N01C = getAsNonOpaqueConstant(N0.getOperand(1))) {
4156       SDLoc DL(N);
4157       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4158                          DAG.getConstant(N1C->getAPIntValue() ^
4159                                          N01C->getAPIntValue(), DL, VT));
4160     }
4161   }
4162   // fold (xor x, x) -> 0
4163   if (N0 == N1)
4164     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4165
4166   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4167   // Here is a concrete example of this equivalence:
4168   // i16   x ==  14
4169   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4170   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4171   //
4172   // =>
4173   //
4174   // i16     ~1      == 0b1111111111111110
4175   // i16 rol(~1, 14) == 0b1011111111111111
4176   //
4177   // Some additional tips to help conceptualize this transform:
4178   // - Try to see the operation as placing a single zero in a value of all ones.
4179   // - There exists no value for x which would allow the result to contain zero.
4180   // - Values of x larger than the bitwidth are undefined and do not require a
4181   //   consistent result.
4182   // - Pushing the zero left requires shifting one bits in from the right.
4183   // A rotate left of ~1 is a nice way of achieving the desired result.
4184   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0.getOpcode() == ISD::SHL
4185       && isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
4186     SDLoc DL(N);
4187     return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4188                        N0.getOperand(1));
4189   }
4190
4191   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4192   if (N0.getOpcode() == N1.getOpcode())
4193     if (SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N))
4194       return Tmp;
4195
4196   // Simplify the expression using non-local knowledge.
4197   if (!VT.isVector() &&
4198       SimplifyDemandedBits(SDValue(N, 0)))
4199     return SDValue(N, 0);
4200
4201   return SDValue();
4202 }
4203
4204 /// Handle transforms common to the three shifts, when the shift amount is a
4205 /// constant.
4206 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4207   SDNode *LHS = N->getOperand(0).getNode();
4208   if (!LHS->hasOneUse()) return SDValue();
4209
4210   // We want to pull some binops through shifts, so that we have (and (shift))
4211   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4212   // thing happens with address calculations, so it's important to canonicalize
4213   // it.
4214   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4215
4216   switch (LHS->getOpcode()) {
4217   default: return SDValue();
4218   case ISD::OR:
4219   case ISD::XOR:
4220     HighBitSet = false; // We can only transform sra if the high bit is clear.
4221     break;
4222   case ISD::AND:
4223     HighBitSet = true;  // We can only transform sra if the high bit is set.
4224     break;
4225   case ISD::ADD:
4226     if (N->getOpcode() != ISD::SHL)
4227       return SDValue(); // only shl(add) not sr[al](add).
4228     HighBitSet = false; // We can only transform sra if the high bit is clear.
4229     break;
4230   }
4231
4232   // We require the RHS of the binop to be a constant and not opaque as well.
4233   ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS->getOperand(1));
4234   if (!BinOpCst) return SDValue();
4235
4236   // FIXME: disable this unless the input to the binop is a shift by a constant.
4237   // If it is not a shift, it pessimizes some common cases like:
4238   //
4239   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4240   //    int bar(int *X, int i) { return X[i & 255]; }
4241   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4242   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4243        BinOpLHSVal->getOpcode() != ISD::SRA &&
4244        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4245       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4246     return SDValue();
4247
4248   EVT VT = N->getValueType(0);
4249
4250   // If this is a signed shift right, and the high bit is modified by the
4251   // logical operation, do not perform the transformation. The highBitSet
4252   // boolean indicates the value of the high bit of the constant which would
4253   // cause it to be modified for this operation.
4254   if (N->getOpcode() == ISD::SRA) {
4255     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4256     if (BinOpRHSSignSet != HighBitSet)
4257       return SDValue();
4258   }
4259
4260   if (!TLI.isDesirableToCommuteWithShift(LHS))
4261     return SDValue();
4262
4263   // Fold the constants, shifting the binop RHS by the shift amount.
4264   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4265                                N->getValueType(0),
4266                                LHS->getOperand(1), N->getOperand(1));
4267   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4268
4269   // Create the new shift.
4270   SDValue NewShift = DAG.getNode(N->getOpcode(),
4271                                  SDLoc(LHS->getOperand(0)),
4272                                  VT, LHS->getOperand(0), N->getOperand(1));
4273
4274   // Create the new binop.
4275   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4276 }
4277
4278 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4279   assert(N->getOpcode() == ISD::TRUNCATE);
4280   assert(N->getOperand(0).getOpcode() == ISD::AND);
4281
4282   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4283   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4284     SDValue N01 = N->getOperand(0).getOperand(1);
4285
4286     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4287       if (!N01C->isOpaque()) {
4288         EVT TruncVT = N->getValueType(0);
4289         SDValue N00 = N->getOperand(0).getOperand(0);
4290         APInt TruncC = N01C->getAPIntValue();
4291         TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4292         SDLoc DL(N);
4293
4294         return DAG.getNode(ISD::AND, DL, TruncVT,
4295                            DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4296                            DAG.getConstant(TruncC, DL, TruncVT));
4297       }
4298     }
4299   }
4300
4301   return SDValue();
4302 }
4303
4304 SDValue DAGCombiner::visitRotate(SDNode *N) {
4305   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4306   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4307       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4308     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4309     if (NewOp1.getNode())
4310       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4311                          N->getOperand(0), NewOp1);
4312   }
4313   return SDValue();
4314 }
4315
4316 SDValue DAGCombiner::visitSHL(SDNode *N) {
4317   SDValue N0 = N->getOperand(0);
4318   SDValue N1 = N->getOperand(1);
4319   EVT VT = N0.getValueType();
4320   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4321
4322   // fold vector ops
4323   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4324   if (VT.isVector()) {
4325     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4326       return FoldedVOp;
4327
4328     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4329     // If setcc produces all-one true value then:
4330     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4331     if (N1CV && N1CV->isConstant()) {
4332       if (N0.getOpcode() == ISD::AND) {
4333         SDValue N00 = N0->getOperand(0);
4334         SDValue N01 = N0->getOperand(1);
4335         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4336
4337         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4338             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4339                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4340           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4341                                                      N01CV, N1CV))
4342             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4343         }
4344       } else {
4345         N1C = isConstOrConstSplat(N1);
4346       }
4347     }
4348   }
4349
4350   // fold (shl c1, c2) -> c1<<c2
4351   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4352   if (N0C && N1C && !N1C->isOpaque())
4353     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4354   // fold (shl 0, x) -> 0
4355   if (isNullConstant(N0))
4356     return N0;
4357   // fold (shl x, c >= size(x)) -> undef
4358   if (N1C && N1C->getAPIntValue().uge(OpSizeInBits))
4359     return DAG.getUNDEF(VT);
4360   // fold (shl x, 0) -> x
4361   if (N1C && N1C->isNullValue())
4362     return N0;
4363   // fold (shl undef, x) -> 0
4364   if (N0.getOpcode() == ISD::UNDEF)
4365     return DAG.getConstant(0, SDLoc(N), VT);
4366   // if (shl x, c) is known to be zero, return 0
4367   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4368                             APInt::getAllOnesValue(OpSizeInBits)))
4369     return DAG.getConstant(0, SDLoc(N), VT);
4370   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4371   if (N1.getOpcode() == ISD::TRUNCATE &&
4372       N1.getOperand(0).getOpcode() == ISD::AND) {
4373     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4374     if (NewOp1.getNode())
4375       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4376   }
4377
4378   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4379     return SDValue(N, 0);
4380
4381   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4382   if (N1C && N0.getOpcode() == ISD::SHL) {
4383     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4384       uint64_t c1 = N0C1->getZExtValue();
4385       uint64_t c2 = N1C->getZExtValue();
4386       SDLoc DL(N);
4387       if (c1 + c2 >= OpSizeInBits)
4388         return DAG.getConstant(0, DL, VT);
4389       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4390                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4391     }
4392   }
4393
4394   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4395   // For this to be valid, the second form must not preserve any of the bits
4396   // that are shifted out by the inner shift in the first form.  This means
4397   // the outer shift size must be >= the number of bits added by the ext.
4398   // As a corollary, we don't care what kind of ext it is.
4399   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4400               N0.getOpcode() == ISD::ANY_EXTEND ||
4401               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4402       N0.getOperand(0).getOpcode() == ISD::SHL) {
4403     SDValue N0Op0 = N0.getOperand(0);
4404     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4405       uint64_t c1 = N0Op0C1->getZExtValue();
4406       uint64_t c2 = N1C->getZExtValue();
4407       EVT InnerShiftVT = N0Op0.getValueType();
4408       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4409       if (c2 >= OpSizeInBits - InnerShiftSize) {
4410         SDLoc DL(N0);
4411         if (c1 + c2 >= OpSizeInBits)
4412           return DAG.getConstant(0, DL, VT);
4413         return DAG.getNode(ISD::SHL, DL, VT,
4414                            DAG.getNode(N0.getOpcode(), DL, VT,
4415                                        N0Op0->getOperand(0)),
4416                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4417       }
4418     }
4419   }
4420
4421   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4422   // Only fold this if the inner zext has no other uses to avoid increasing
4423   // the total number of instructions.
4424   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4425       N0.getOperand(0).getOpcode() == ISD::SRL) {
4426     SDValue N0Op0 = N0.getOperand(0);
4427     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4428       uint64_t c1 = N0Op0C1->getZExtValue();
4429       if (c1 < VT.getScalarSizeInBits()) {
4430         uint64_t c2 = N1C->getZExtValue();
4431         if (c1 == c2) {
4432           SDValue NewOp0 = N0.getOperand(0);
4433           EVT CountVT = NewOp0.getOperand(1).getValueType();
4434           SDLoc DL(N);
4435           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4436                                        NewOp0,
4437                                        DAG.getConstant(c2, DL, CountVT));
4438           AddToWorklist(NewSHL.getNode());
4439           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4440         }
4441       }
4442     }
4443   }
4444
4445   // fold (shl (sr[la] exact X,  C1), C2) -> (shl    X, (C2-C1)) if C1 <= C2
4446   // fold (shl (sr[la] exact X,  C1), C2) -> (sr[la] X, (C2-C1)) if C1  > C2
4447   if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
4448       cast<BinaryWithFlagsSDNode>(N0)->Flags.hasExact()) {
4449     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4450       uint64_t C1 = N0C1->getZExtValue();
4451       uint64_t C2 = N1C->getZExtValue();
4452       SDLoc DL(N);
4453       if (C1 <= C2)
4454         return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4455                            DAG.getConstant(C2 - C1, DL, N1.getValueType()));
4456       return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
4457                          DAG.getConstant(C1 - C2, DL, N1.getValueType()));
4458     }
4459   }
4460
4461   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4462   //                               (and (srl x, (sub c1, c2), MASK)
4463   // Only fold this if the inner shift has no other uses -- if it does, folding
4464   // this will increase the total number of instructions.
4465   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4466     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4467       uint64_t c1 = N0C1->getZExtValue();
4468       if (c1 < OpSizeInBits) {
4469         uint64_t c2 = N1C->getZExtValue();
4470         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4471         SDValue Shift;
4472         if (c2 > c1) {
4473           Mask = Mask.shl(c2 - c1);
4474           SDLoc DL(N);
4475           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4476                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4477         } else {
4478           Mask = Mask.lshr(c1 - c2);
4479           SDLoc DL(N);
4480           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4481                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4482         }
4483         SDLoc DL(N0);
4484         return DAG.getNode(ISD::AND, DL, VT, Shift,
4485                            DAG.getConstant(Mask, DL, VT));
4486       }
4487     }
4488   }
4489   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4490   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4491     unsigned BitSize = VT.getScalarSizeInBits();
4492     SDLoc DL(N);
4493     SDValue HiBitsMask =
4494       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4495                                             BitSize - N1C->getZExtValue()),
4496                       DL, VT);
4497     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4498                        HiBitsMask);
4499   }
4500
4501   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4502   // Variant of version done on multiply, except mul by a power of 2 is turned
4503   // into a shift.
4504   APInt Val;
4505   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4506       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4507        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4508     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4509     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4510     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4511   }
4512
4513   // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
4514   if (N1C && N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse()) {
4515     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4516       if (SDValue Folded =
4517               DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N1), VT, N0C1, N1C))
4518         return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Folded);
4519     }
4520   }
4521
4522   if (N1C && !N1C->isOpaque())
4523     if (SDValue NewSHL = visitShiftByConstant(N, N1C))
4524       return NewSHL;
4525
4526   return SDValue();
4527 }
4528
4529 SDValue DAGCombiner::visitSRA(SDNode *N) {
4530   SDValue N0 = N->getOperand(0);
4531   SDValue N1 = N->getOperand(1);
4532   EVT VT = N0.getValueType();
4533   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4534
4535   // fold vector ops
4536   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4537   if (VT.isVector()) {
4538     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4539       return FoldedVOp;
4540
4541     N1C = isConstOrConstSplat(N1);
4542   }
4543
4544   // fold (sra c1, c2) -> (sra c1, c2)
4545   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4546   if (N0C && N1C && !N1C->isOpaque())
4547     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4548   // fold (sra 0, x) -> 0
4549   if (isNullConstant(N0))
4550     return N0;
4551   // fold (sra -1, x) -> -1
4552   if (isAllOnesConstant(N0))
4553     return N0;
4554   // fold (sra x, (setge c, size(x))) -> undef
4555   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4556     return DAG.getUNDEF(VT);
4557   // fold (sra x, 0) -> x
4558   if (N1C && N1C->isNullValue())
4559     return N0;
4560   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4561   // sext_inreg.
4562   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4563     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4564     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4565     if (VT.isVector())
4566       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4567                                ExtVT, VT.getVectorNumElements());
4568     if ((!LegalOperations ||
4569          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4570       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4571                          N0.getOperand(0), DAG.getValueType(ExtVT));
4572   }
4573
4574   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4575   if (N1C && N0.getOpcode() == ISD::SRA) {
4576     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4577       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4578       if (Sum >= OpSizeInBits)
4579         Sum = OpSizeInBits - 1;
4580       SDLoc DL(N);
4581       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4582                          DAG.getConstant(Sum, DL, N1.getValueType()));
4583     }
4584   }
4585
4586   // fold (sra (shl X, m), (sub result_size, n))
4587   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4588   // result_size - n != m.
4589   // If truncate is free for the target sext(shl) is likely to result in better
4590   // code.
4591   if (N0.getOpcode() == ISD::SHL && N1C) {
4592     // Get the two constanst of the shifts, CN0 = m, CN = n.
4593     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4594     if (N01C) {
4595       LLVMContext &Ctx = *DAG.getContext();
4596       // Determine what the truncate's result bitsize and type would be.
4597       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4598
4599       if (VT.isVector())
4600         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4601
4602       // Determine the residual right-shift amount.
4603       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4604
4605       // If the shift is not a no-op (in which case this should be just a sign
4606       // extend already), the truncated to type is legal, sign_extend is legal
4607       // on that type, and the truncate to that type is both legal and free,
4608       // perform the transform.
4609       if ((ShiftAmt > 0) &&
4610           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4611           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4612           TLI.isTruncateFree(VT, TruncVT)) {
4613
4614         SDLoc DL(N);
4615         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4616             getShiftAmountTy(N0.getOperand(0).getValueType()));
4617         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4618                                     N0.getOperand(0), Amt);
4619         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4620                                     Shift);
4621         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4622                            N->getValueType(0), Trunc);
4623       }
4624     }
4625   }
4626
4627   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4628   if (N1.getOpcode() == ISD::TRUNCATE &&
4629       N1.getOperand(0).getOpcode() == ISD::AND) {
4630     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4631     if (NewOp1.getNode())
4632       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4633   }
4634
4635   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4636   //      if c1 is equal to the number of bits the trunc removes
4637   if (N0.getOpcode() == ISD::TRUNCATE &&
4638       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4639        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4640       N0.getOperand(0).hasOneUse() &&
4641       N0.getOperand(0).getOperand(1).hasOneUse() &&
4642       N1C) {
4643     SDValue N0Op0 = N0.getOperand(0);
4644     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4645       unsigned LargeShiftVal = LargeShift->getZExtValue();
4646       EVT LargeVT = N0Op0.getValueType();
4647
4648       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4649         SDLoc DL(N);
4650         SDValue Amt =
4651           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4652                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4653         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4654                                   N0Op0.getOperand(0), Amt);
4655         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4656       }
4657     }
4658   }
4659
4660   // Simplify, based on bits shifted out of the LHS.
4661   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4662     return SDValue(N, 0);
4663
4664
4665   // If the sign bit is known to be zero, switch this to a SRL.
4666   if (DAG.SignBitIsZero(N0))
4667     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4668
4669   if (N1C && !N1C->isOpaque())
4670     if (SDValue NewSRA = visitShiftByConstant(N, N1C))
4671       return NewSRA;
4672
4673   return SDValue();
4674 }
4675
4676 SDValue DAGCombiner::visitSRL(SDNode *N) {
4677   SDValue N0 = N->getOperand(0);
4678   SDValue N1 = N->getOperand(1);
4679   EVT VT = N0.getValueType();
4680   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4681
4682   // fold vector ops
4683   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4684   if (VT.isVector()) {
4685     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4686       return FoldedVOp;
4687
4688     N1C = isConstOrConstSplat(N1);
4689   }
4690
4691   // fold (srl c1, c2) -> c1 >>u c2
4692   ConstantSDNode *N0C = getAsNonOpaqueConstant(N0);
4693   if (N0C && N1C && !N1C->isOpaque())
4694     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4695   // fold (srl 0, x) -> 0
4696   if (isNullConstant(N0))
4697     return N0;
4698   // fold (srl x, c >= size(x)) -> undef
4699   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4700     return DAG.getUNDEF(VT);
4701   // fold (srl x, 0) -> x
4702   if (N1C && N1C->isNullValue())
4703     return N0;
4704   // if (srl x, c) is known to be zero, return 0
4705   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4706                                    APInt::getAllOnesValue(OpSizeInBits)))
4707     return DAG.getConstant(0, SDLoc(N), VT);
4708
4709   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4710   if (N1C && N0.getOpcode() == ISD::SRL) {
4711     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4712       uint64_t c1 = N01C->getZExtValue();
4713       uint64_t c2 = N1C->getZExtValue();
4714       SDLoc DL(N);
4715       if (c1 + c2 >= OpSizeInBits)
4716         return DAG.getConstant(0, DL, VT);
4717       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4718                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4719     }
4720   }
4721
4722   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4723   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4724       N0.getOperand(0).getOpcode() == ISD::SRL &&
4725       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4726     uint64_t c1 =
4727       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4728     uint64_t c2 = N1C->getZExtValue();
4729     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4730     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4731     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4732     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4733     if (c1 + OpSizeInBits == InnerShiftSize) {
4734       SDLoc DL(N0);
4735       if (c1 + c2 >= InnerShiftSize)
4736         return DAG.getConstant(0, DL, VT);
4737       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4738                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4739                                      N0.getOperand(0)->getOperand(0),
4740                                      DAG.getConstant(c1 + c2, DL,
4741                                                      ShiftCountVT)));
4742     }
4743   }
4744
4745   // fold (srl (shl x, c), c) -> (and x, cst2)
4746   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4747     unsigned BitSize = N0.getScalarValueSizeInBits();
4748     if (BitSize <= 64) {
4749       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4750       SDLoc DL(N);
4751       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4752                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4753     }
4754   }
4755
4756   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4757   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4758     // Shifting in all undef bits?
4759     EVT SmallVT = N0.getOperand(0).getValueType();
4760     unsigned BitSize = SmallVT.getScalarSizeInBits();
4761     if (N1C->getZExtValue() >= BitSize)
4762       return DAG.getUNDEF(VT);
4763
4764     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4765       uint64_t ShiftAmt = N1C->getZExtValue();
4766       SDLoc DL0(N0);
4767       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4768                                        N0.getOperand(0),
4769                           DAG.getConstant(ShiftAmt, DL0,
4770                                           getShiftAmountTy(SmallVT)));
4771       AddToWorklist(SmallShift.getNode());
4772       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4773       SDLoc DL(N);
4774       return DAG.getNode(ISD::AND, DL, VT,
4775                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4776                          DAG.getConstant(Mask, DL, VT));
4777     }
4778   }
4779
4780   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4781   // bit, which is unmodified by sra.
4782   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4783     if (N0.getOpcode() == ISD::SRA)
4784       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4785   }
4786
4787   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4788   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4789       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4790     APInt KnownZero, KnownOne;
4791     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4792
4793     // If any of the input bits are KnownOne, then the input couldn't be all
4794     // zeros, thus the result of the srl will always be zero.
4795     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4796
4797     // If all of the bits input the to ctlz node are known to be zero, then
4798     // the result of the ctlz is "32" and the result of the shift is one.
4799     APInt UnknownBits = ~KnownZero;
4800     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4801
4802     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4803     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4804       // Okay, we know that only that the single bit specified by UnknownBits
4805       // could be set on input to the CTLZ node. If this bit is set, the SRL
4806       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4807       // to an SRL/XOR pair, which is likely to simplify more.
4808       unsigned ShAmt = UnknownBits.countTrailingZeros();
4809       SDValue Op = N0.getOperand(0);
4810
4811       if (ShAmt) {
4812         SDLoc DL(N0);
4813         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4814                   DAG.getConstant(ShAmt, DL,
4815                                   getShiftAmountTy(Op.getValueType())));
4816         AddToWorklist(Op.getNode());
4817       }
4818
4819       SDLoc DL(N);
4820       return DAG.getNode(ISD::XOR, DL, VT,
4821                          Op, DAG.getConstant(1, DL, VT));
4822     }
4823   }
4824
4825   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4826   if (N1.getOpcode() == ISD::TRUNCATE &&
4827       N1.getOperand(0).getOpcode() == ISD::AND) {
4828     if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
4829       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4830   }
4831
4832   // fold operands of srl based on knowledge that the low bits are not
4833   // demanded.
4834   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4835     return SDValue(N, 0);
4836
4837   if (N1C && !N1C->isOpaque())
4838     if (SDValue NewSRL = visitShiftByConstant(N, N1C))
4839       return NewSRL;
4840
4841   // Attempt to convert a srl of a load into a narrower zero-extending load.
4842   if (SDValue NarrowLoad = ReduceLoadWidth(N))
4843     return NarrowLoad;
4844
4845   // Here is a common situation. We want to optimize:
4846   //
4847   //   %a = ...
4848   //   %b = and i32 %a, 2
4849   //   %c = srl i32 %b, 1
4850   //   brcond i32 %c ...
4851   //
4852   // into
4853   //
4854   //   %a = ...
4855   //   %b = and %a, 2
4856   //   %c = setcc eq %b, 0
4857   //   brcond %c ...
4858   //
4859   // However when after the source operand of SRL is optimized into AND, the SRL
4860   // itself may not be optimized further. Look for it and add the BRCOND into
4861   // the worklist.
4862   if (N->hasOneUse()) {
4863     SDNode *Use = *N->use_begin();
4864     if (Use->getOpcode() == ISD::BRCOND)
4865       AddToWorklist(Use);
4866     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4867       // Also look pass the truncate.
4868       Use = *Use->use_begin();
4869       if (Use->getOpcode() == ISD::BRCOND)
4870         AddToWorklist(Use);
4871     }
4872   }
4873
4874   return SDValue();
4875 }
4876
4877 SDValue DAGCombiner::visitBSWAP(SDNode *N) {
4878   SDValue N0 = N->getOperand(0);
4879   EVT VT = N->getValueType(0);
4880
4881   // fold (bswap c1) -> c2
4882   if (isConstantIntBuildVectorOrConstantInt(N0))
4883     return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
4884   // fold (bswap (bswap x)) -> x
4885   if (N0.getOpcode() == ISD::BSWAP)
4886     return N0->getOperand(0);
4887   return SDValue();
4888 }
4889
4890 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4891   SDValue N0 = N->getOperand(0);
4892   EVT VT = N->getValueType(0);
4893
4894   // fold (ctlz c1) -> c2
4895   if (isConstantIntBuildVectorOrConstantInt(N0))
4896     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4897   return SDValue();
4898 }
4899
4900 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4901   SDValue N0 = N->getOperand(0);
4902   EVT VT = N->getValueType(0);
4903
4904   // fold (ctlz_zero_undef c1) -> c2
4905   if (isConstantIntBuildVectorOrConstantInt(N0))
4906     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4907   return SDValue();
4908 }
4909
4910 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4911   SDValue N0 = N->getOperand(0);
4912   EVT VT = N->getValueType(0);
4913
4914   // fold (cttz c1) -> c2
4915   if (isConstantIntBuildVectorOrConstantInt(N0))
4916     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4917   return SDValue();
4918 }
4919
4920 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4921   SDValue N0 = N->getOperand(0);
4922   EVT VT = N->getValueType(0);
4923
4924   // fold (cttz_zero_undef c1) -> c2
4925   if (isConstantIntBuildVectorOrConstantInt(N0))
4926     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4927   return SDValue();
4928 }
4929
4930 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4931   SDValue N0 = N->getOperand(0);
4932   EVT VT = N->getValueType(0);
4933
4934   // fold (ctpop c1) -> c2
4935   if (isConstantIntBuildVectorOrConstantInt(N0))
4936     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4937   return SDValue();
4938 }
4939
4940
4941 /// \brief Generate Min/Max node
4942 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4943                                    SDValue True, SDValue False,
4944                                    ISD::CondCode CC, const TargetLowering &TLI,
4945                                    SelectionDAG &DAG) {
4946   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4947     return SDValue();
4948
4949   switch (CC) {
4950   case ISD::SETOLT:
4951   case ISD::SETOLE:
4952   case ISD::SETLT:
4953   case ISD::SETLE:
4954   case ISD::SETULT:
4955   case ISD::SETULE: {
4956     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4957     if (TLI.isOperationLegal(Opcode, VT))
4958       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4959     return SDValue();
4960   }
4961   case ISD::SETOGT:
4962   case ISD::SETOGE:
4963   case ISD::SETGT:
4964   case ISD::SETGE:
4965   case ISD::SETUGT:
4966   case ISD::SETUGE: {
4967     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4968     if (TLI.isOperationLegal(Opcode, VT))
4969       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4970     return SDValue();
4971   }
4972   default:
4973     return SDValue();
4974   }
4975 }
4976
4977 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4978   SDValue N0 = N->getOperand(0);
4979   SDValue N1 = N->getOperand(1);
4980   SDValue N2 = N->getOperand(2);
4981   EVT VT = N->getValueType(0);
4982   EVT VT0 = N0.getValueType();
4983
4984   // fold (select C, X, X) -> X
4985   if (N1 == N2)
4986     return N1;
4987   if (const ConstantSDNode *N0C = dyn_cast<const ConstantSDNode>(N0)) {
4988     // fold (select true, X, Y) -> X
4989     // fold (select false, X, Y) -> Y
4990     return !N0C->isNullValue() ? N1 : N2;
4991   }
4992   // fold (select C, 1, X) -> (or C, X)
4993   if (VT == MVT::i1 && isOneConstant(N1))
4994     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4995   // fold (select C, 0, 1) -> (xor C, 1)
4996   // We can't do this reliably if integer based booleans have different contents
4997   // to floating point based booleans. This is because we can't tell whether we
4998   // have an integer-based boolean or a floating-point-based boolean unless we
4999   // can find the SETCC that produced it and inspect its operands. This is
5000   // fairly easy if C is the SETCC node, but it can potentially be
5001   // undiscoverable (or not reasonably discoverable). For example, it could be
5002   // in another basic block or it could require searching a complicated
5003   // expression.
5004   if (VT.isInteger() &&
5005       (VT0 == MVT::i1 || (VT0.isInteger() &&
5006                           TLI.getBooleanContents(false, false) ==
5007                               TLI.getBooleanContents(false, true) &&
5008                           TLI.getBooleanContents(false, false) ==
5009                               TargetLowering::ZeroOrOneBooleanContent)) &&
5010       isNullConstant(N1) && isOneConstant(N2)) {
5011     SDValue XORNode;
5012     if (VT == VT0) {
5013       SDLoc DL(N);
5014       return DAG.getNode(ISD::XOR, DL, VT0,
5015                          N0, DAG.getConstant(1, DL, VT0));
5016     }
5017     SDLoc DL0(N0);
5018     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
5019                           N0, DAG.getConstant(1, DL0, VT0));
5020     AddToWorklist(XORNode.getNode());
5021     if (VT.bitsGT(VT0))
5022       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
5023     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
5024   }
5025   // fold (select C, 0, X) -> (and (not C), X)
5026   if (VT == VT0 && VT == MVT::i1 && isNullConstant(N1)) {
5027     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5028     AddToWorklist(NOTNode.getNode());
5029     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
5030   }
5031   // fold (select C, X, 1) -> (or (not C), X)
5032   if (VT == VT0 && VT == MVT::i1 && isOneConstant(N2)) {
5033     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
5034     AddToWorklist(NOTNode.getNode());
5035     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
5036   }
5037   // fold (select C, X, 0) -> (and C, X)
5038   if (VT == MVT::i1 && isNullConstant(N2))
5039     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5040   // fold (select X, X, Y) -> (or X, Y)
5041   // fold (select X, 1, Y) -> (or X, Y)
5042   if (VT == MVT::i1 && (N0 == N1 || isOneConstant(N1)))
5043     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
5044   // fold (select X, Y, X) -> (and X, Y)
5045   // fold (select X, Y, 0) -> (and X, Y)
5046   if (VT == MVT::i1 && (N0 == N2 || isNullConstant(N2)))
5047     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
5048
5049   // If we can fold this based on the true/false value, do so.
5050   if (SimplifySelectOps(N, N1, N2))
5051     return SDValue(N, 0);  // Don't revisit N.
5052
5053   if (VT0 == MVT::i1) {
5054     // The code in this block deals with the following 2 equivalences:
5055     //    select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
5056     //    select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
5057     // The target can specify its prefered form with the
5058     // shouldNormalizeToSelectSequence() callback. However we always transform
5059     // to the right anyway if we find the inner select exists in the DAG anyway
5060     // and we always transform to the left side if we know that we can further
5061     // optimize the combination of the conditions.
5062     bool normalizeToSequence
5063       = TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
5064     // select (and Cond0, Cond1), X, Y
5065     //   -> select Cond0, (select Cond1, X, Y), Y
5066     if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
5067       SDValue Cond0 = N0->getOperand(0);
5068       SDValue Cond1 = N0->getOperand(1);
5069       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5070                                         N1.getValueType(), Cond1, N1, N2);
5071       if (normalizeToSequence || !InnerSelect.use_empty())
5072         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
5073                            InnerSelect, N2);
5074     }
5075     // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
5076     if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
5077       SDValue Cond0 = N0->getOperand(0);
5078       SDValue Cond1 = N0->getOperand(1);
5079       SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
5080                                         N1.getValueType(), Cond1, N1, N2);
5081       if (normalizeToSequence || !InnerSelect.use_empty())
5082         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
5083                            InnerSelect);
5084     }
5085
5086     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
5087     if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
5088       SDValue N1_0 = N1->getOperand(0);
5089       SDValue N1_1 = N1->getOperand(1);
5090       SDValue N1_2 = N1->getOperand(2);
5091       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
5092         // Create the actual and node if we can generate good code for it.
5093         if (!normalizeToSequence) {
5094           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
5095                                     N0, N1_0);
5096           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
5097                              N1_1, N2);
5098         }
5099         // Otherwise see if we can optimize the "and" to a better pattern.
5100         if (SDValue Combined = visitANDLike(N0, N1_0, N))
5101           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5102                              N1_1, N2);
5103       }
5104     }
5105     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
5106     if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
5107       SDValue N2_0 = N2->getOperand(0);
5108       SDValue N2_1 = N2->getOperand(1);
5109       SDValue N2_2 = N2->getOperand(2);
5110       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
5111         // Create the actual or node if we can generate good code for it.
5112         if (!normalizeToSequence) {
5113           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
5114                                    N0, N2_0);
5115           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
5116                              N1, N2_2);
5117         }
5118         // Otherwise see if we can optimize to a better pattern.
5119         if (SDValue Combined = visitORLike(N0, N2_0, N))
5120           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5121                              N1, N2_2);
5122       }
5123     }
5124   }
5125
5126   // fold selects based on a setcc into other things, such as min/max/abs
5127   if (N0.getOpcode() == ISD::SETCC) {
5128     // select x, y (fcmp lt x, y) -> fminnum x, y
5129     // select x, y (fcmp gt x, y) -> fmaxnum x, y
5130     //
5131     // This is OK if we don't care about what happens if either operand is a
5132     // NaN.
5133     //
5134
5135     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
5136     // no signed zeros as well as no nans.
5137     const TargetOptions &Options = DAG.getTarget().Options;
5138     if (Options.UnsafeFPMath &&
5139         VT.isFloatingPoint() && N0.hasOneUse() &&
5140         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
5141       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5142
5143       if (SDValue FMinMax = combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0),
5144                                                 N0.getOperand(1), N1, N2, CC,
5145                                                 TLI, DAG))
5146         return FMinMax;
5147     }
5148
5149     if ((!LegalOperations &&
5150          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
5151         TLI.isOperationLegal(ISD::SELECT_CC, VT))
5152       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
5153                          N0.getOperand(0), N0.getOperand(1),
5154                          N1, N2, N0.getOperand(2));
5155     return SimplifySelect(SDLoc(N), N0, N1, N2);
5156   }
5157
5158   return SDValue();
5159 }
5160
5161 static
5162 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5163   SDLoc DL(N);
5164   EVT LoVT, HiVT;
5165   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5166
5167   // Split the inputs.
5168   SDValue Lo, Hi, LL, LH, RL, RH;
5169   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5170   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5171
5172   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5173   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5174
5175   return std::make_pair(Lo, Hi);
5176 }
5177
5178 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5179 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5180 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5181   SDLoc dl(N);
5182   SDValue Cond = N->getOperand(0);
5183   SDValue LHS = N->getOperand(1);
5184   SDValue RHS = N->getOperand(2);
5185   EVT VT = N->getValueType(0);
5186   int NumElems = VT.getVectorNumElements();
5187   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5188          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5189          Cond.getOpcode() == ISD::BUILD_VECTOR);
5190
5191   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5192   // binary ones here.
5193   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5194     return SDValue();
5195
5196   // We're sure we have an even number of elements due to the
5197   // concat_vectors we have as arguments to vselect.
5198   // Skip BV elements until we find one that's not an UNDEF
5199   // After we find an UNDEF element, keep looping until we get to half the
5200   // length of the BV and see if all the non-undef nodes are the same.
5201   ConstantSDNode *BottomHalf = nullptr;
5202   for (int i = 0; i < NumElems / 2; ++i) {
5203     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5204       continue;
5205
5206     if (BottomHalf == nullptr)
5207       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5208     else if (Cond->getOperand(i).getNode() != BottomHalf)
5209       return SDValue();
5210   }
5211
5212   // Do the same for the second half of the BuildVector
5213   ConstantSDNode *TopHalf = nullptr;
5214   for (int i = NumElems / 2; i < NumElems; ++i) {
5215     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5216       continue;
5217
5218     if (TopHalf == nullptr)
5219       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5220     else if (Cond->getOperand(i).getNode() != TopHalf)
5221       return SDValue();
5222   }
5223
5224   assert(TopHalf && BottomHalf &&
5225          "One half of the selector was all UNDEFs and the other was all the "
5226          "same value. This should have been addressed before this function.");
5227   return DAG.getNode(
5228       ISD::CONCAT_VECTORS, dl, VT,
5229       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5230       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5231 }
5232
5233 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5234
5235   if (Level >= AfterLegalizeTypes)
5236     return SDValue();
5237
5238   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5239   SDValue Mask = MSC->getMask();
5240   SDValue Data  = MSC->getValue();
5241   SDLoc DL(N);
5242
5243   // If the MSCATTER data type requires splitting and the mask is provided by a
5244   // SETCC, then split both nodes and its operands before legalization. This
5245   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5246   // and enables future optimizations (e.g. min/max pattern matching on X86).
5247   if (Mask.getOpcode() != ISD::SETCC)
5248     return SDValue();
5249
5250   // Check if any splitting is required.
5251   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5252       TargetLowering::TypeSplitVector)
5253     return SDValue();
5254   SDValue MaskLo, MaskHi, Lo, Hi;
5255   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5256
5257   EVT LoVT, HiVT;
5258   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5259
5260   SDValue Chain = MSC->getChain();
5261
5262   EVT MemoryVT = MSC->getMemoryVT();
5263   unsigned Alignment = MSC->getOriginalAlignment();
5264
5265   EVT LoMemVT, HiMemVT;
5266   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5267
5268   SDValue DataLo, DataHi;
5269   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5270
5271   SDValue BasePtr = MSC->getBasePtr();
5272   SDValue IndexLo, IndexHi;
5273   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5274
5275   MachineMemOperand *MMO = DAG.getMachineFunction().
5276     getMachineMemOperand(MSC->getPointerInfo(),
5277                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5278                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5279
5280   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5281   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5282                             DL, OpsLo, MMO);
5283
5284   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5285   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5286                             DL, OpsHi, MMO);
5287
5288   AddToWorklist(Lo.getNode());
5289   AddToWorklist(Hi.getNode());
5290
5291   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5292 }
5293
5294 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5295
5296   if (Level >= AfterLegalizeTypes)
5297     return SDValue();
5298
5299   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5300   SDValue Mask = MST->getMask();
5301   SDValue Data  = MST->getValue();
5302   SDLoc DL(N);
5303
5304   // If the MSTORE data type requires splitting and the mask is provided by a
5305   // SETCC, then split both nodes and its operands before legalization. This
5306   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5307   // and enables future optimizations (e.g. min/max pattern matching on X86).
5308   if (Mask.getOpcode() == ISD::SETCC) {
5309
5310     // Check if any splitting is required.
5311     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5312         TargetLowering::TypeSplitVector)
5313       return SDValue();
5314
5315     SDValue MaskLo, MaskHi, Lo, Hi;
5316     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5317
5318     EVT LoVT, HiVT;
5319     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5320
5321     SDValue Chain = MST->getChain();
5322     SDValue Ptr   = MST->getBasePtr();
5323
5324     EVT MemoryVT = MST->getMemoryVT();
5325     unsigned Alignment = MST->getOriginalAlignment();
5326
5327     // if Alignment is equal to the vector size,
5328     // take the half of it for the second part
5329     unsigned SecondHalfAlignment =
5330       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5331          Alignment/2 : Alignment;
5332
5333     EVT LoMemVT, HiMemVT;
5334     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5335
5336     SDValue DataLo, DataHi;
5337     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5338
5339     MachineMemOperand *MMO = DAG.getMachineFunction().
5340       getMachineMemOperand(MST->getPointerInfo(),
5341                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5342                            Alignment, MST->getAAInfo(), MST->getRanges());
5343
5344     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5345                             MST->isTruncatingStore());
5346
5347     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5348     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5349                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5350
5351     MMO = DAG.getMachineFunction().
5352       getMachineMemOperand(MST->getPointerInfo(),
5353                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5354                            SecondHalfAlignment, MST->getAAInfo(),
5355                            MST->getRanges());
5356
5357     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5358                             MST->isTruncatingStore());
5359
5360     AddToWorklist(Lo.getNode());
5361     AddToWorklist(Hi.getNode());
5362
5363     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5364   }
5365   return SDValue();
5366 }
5367
5368 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5369
5370   if (Level >= AfterLegalizeTypes)
5371     return SDValue();
5372
5373   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5374   SDValue Mask = MGT->getMask();
5375   SDLoc DL(N);
5376
5377   // If the MGATHER result requires splitting and the mask is provided by a
5378   // SETCC, then split both nodes and its operands before legalization. This
5379   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5380   // and enables future optimizations (e.g. min/max pattern matching on X86).
5381
5382   if (Mask.getOpcode() != ISD::SETCC)
5383     return SDValue();
5384
5385   EVT VT = N->getValueType(0);
5386
5387   // Check if any splitting is required.
5388   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5389       TargetLowering::TypeSplitVector)
5390     return SDValue();
5391
5392   SDValue MaskLo, MaskHi, Lo, Hi;
5393   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5394
5395   SDValue Src0 = MGT->getValue();
5396   SDValue Src0Lo, Src0Hi;
5397   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5398
5399   EVT LoVT, HiVT;
5400   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5401
5402   SDValue Chain = MGT->getChain();
5403   EVT MemoryVT = MGT->getMemoryVT();
5404   unsigned Alignment = MGT->getOriginalAlignment();
5405
5406   EVT LoMemVT, HiMemVT;
5407   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5408
5409   SDValue BasePtr = MGT->getBasePtr();
5410   SDValue Index = MGT->getIndex();
5411   SDValue IndexLo, IndexHi;
5412   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5413
5414   MachineMemOperand *MMO = DAG.getMachineFunction().
5415     getMachineMemOperand(MGT->getPointerInfo(),
5416                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5417                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5418
5419   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5420   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5421                             MMO);
5422
5423   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5424   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5425                             MMO);
5426
5427   AddToWorklist(Lo.getNode());
5428   AddToWorklist(Hi.getNode());
5429
5430   // Build a factor node to remember that this load is independent of the
5431   // other one.
5432   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5433                       Hi.getValue(1));
5434
5435   // Legalized the chain result - switch anything that used the old chain to
5436   // use the new one.
5437   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5438
5439   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5440
5441   SDValue RetOps[] = { GatherRes, Chain };
5442   return DAG.getMergeValues(RetOps, DL);
5443 }
5444
5445 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5446
5447   if (Level >= AfterLegalizeTypes)
5448     return SDValue();
5449
5450   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5451   SDValue Mask = MLD->getMask();
5452   SDLoc DL(N);
5453
5454   // If the MLOAD result requires splitting and the mask is provided by a
5455   // SETCC, then split both nodes and its operands before legalization. This
5456   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5457   // and enables future optimizations (e.g. min/max pattern matching on X86).
5458
5459   if (Mask.getOpcode() == ISD::SETCC) {
5460     EVT VT = N->getValueType(0);
5461
5462     // Check if any splitting is required.
5463     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5464         TargetLowering::TypeSplitVector)
5465       return SDValue();
5466
5467     SDValue MaskLo, MaskHi, Lo, Hi;
5468     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5469
5470     SDValue Src0 = MLD->getSrc0();
5471     SDValue Src0Lo, Src0Hi;
5472     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5473
5474     EVT LoVT, HiVT;
5475     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5476
5477     SDValue Chain = MLD->getChain();
5478     SDValue Ptr   = MLD->getBasePtr();
5479     EVT MemoryVT = MLD->getMemoryVT();
5480     unsigned Alignment = MLD->getOriginalAlignment();
5481
5482     // if Alignment is equal to the vector size,
5483     // take the half of it for the second part
5484     unsigned SecondHalfAlignment =
5485       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5486          Alignment/2 : Alignment;
5487
5488     EVT LoMemVT, HiMemVT;
5489     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5490
5491     MachineMemOperand *MMO = DAG.getMachineFunction().
5492     getMachineMemOperand(MLD->getPointerInfo(),
5493                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5494                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5495
5496     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5497                            ISD::NON_EXTLOAD);
5498
5499     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5500     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5501                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5502
5503     MMO = DAG.getMachineFunction().
5504     getMachineMemOperand(MLD->getPointerInfo(),
5505                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5506                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5507
5508     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5509                            ISD::NON_EXTLOAD);
5510
5511     AddToWorklist(Lo.getNode());
5512     AddToWorklist(Hi.getNode());
5513
5514     // Build a factor node to remember that this load is independent of the
5515     // other one.
5516     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5517                         Hi.getValue(1));
5518
5519     // Legalized the chain result - switch anything that used the old chain to
5520     // use the new one.
5521     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5522
5523     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5524
5525     SDValue RetOps[] = { LoadRes, Chain };
5526     return DAG.getMergeValues(RetOps, DL);
5527   }
5528   return SDValue();
5529 }
5530
5531 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5532   SDValue N0 = N->getOperand(0);
5533   SDValue N1 = N->getOperand(1);
5534   SDValue N2 = N->getOperand(2);
5535   SDLoc DL(N);
5536
5537   // Canonicalize integer abs.
5538   // vselect (setg[te] X,  0),  X, -X ->
5539   // vselect (setgt    X, -1),  X, -X ->
5540   // vselect (setl[te] X,  0), -X,  X ->
5541   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5542   if (N0.getOpcode() == ISD::SETCC) {
5543     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5544     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5545     bool isAbs = false;
5546     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5547
5548     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5549          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5550         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5551       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5552     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5553              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5554       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5555
5556     if (isAbs) {
5557       EVT VT = LHS.getValueType();
5558       SDValue Shift = DAG.getNode(
5559           ISD::SRA, DL, VT, LHS,
5560           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5561       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5562       AddToWorklist(Shift.getNode());
5563       AddToWorklist(Add.getNode());
5564       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5565     }
5566   }
5567
5568   if (SimplifySelectOps(N, N1, N2))
5569     return SDValue(N, 0);  // Don't revisit N.
5570
5571   // If the VSELECT result requires splitting and the mask is provided by a
5572   // SETCC, then split both nodes and its operands before legalization. This
5573   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5574   // and enables future optimizations (e.g. min/max pattern matching on X86).
5575   if (N0.getOpcode() == ISD::SETCC) {
5576     EVT VT = N->getValueType(0);
5577
5578     // Check if any splitting is required.
5579     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5580         TargetLowering::TypeSplitVector)
5581       return SDValue();
5582
5583     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5584     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5585     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5586     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5587
5588     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5589     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5590
5591     // Add the new VSELECT nodes to the work list in case they need to be split
5592     // again.
5593     AddToWorklist(Lo.getNode());
5594     AddToWorklist(Hi.getNode());
5595
5596     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5597   }
5598
5599   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5600   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5601     return N1;
5602   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5603   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5604     return N2;
5605
5606   // The ConvertSelectToConcatVector function is assuming both the above
5607   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5608   // and addressed.
5609   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5610       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5611       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5612     if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
5613       return CV;
5614   }
5615
5616   return SDValue();
5617 }
5618
5619 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5620   SDValue N0 = N->getOperand(0);
5621   SDValue N1 = N->getOperand(1);
5622   SDValue N2 = N->getOperand(2);
5623   SDValue N3 = N->getOperand(3);
5624   SDValue N4 = N->getOperand(4);
5625   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5626
5627   // fold select_cc lhs, rhs, x, x, cc -> x
5628   if (N2 == N3)
5629     return N2;
5630
5631   // Determine if the condition we're dealing with is constant
5632   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5633                               N0, N1, CC, SDLoc(N), false);
5634   if (SCC.getNode()) {
5635     AddToWorklist(SCC.getNode());
5636
5637     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5638       if (!SCCC->isNullValue())
5639         return N2;    // cond always true -> true val
5640       else
5641         return N3;    // cond always false -> false val
5642     } else if (SCC->getOpcode() == ISD::UNDEF) {
5643       // When the condition is UNDEF, just return the first operand. This is
5644       // coherent the DAG creation, no setcc node is created in this case
5645       return N2;
5646     } else if (SCC.getOpcode() == ISD::SETCC) {
5647       // Fold to a simpler select_cc
5648       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5649                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5650                          SCC.getOperand(2));
5651     }
5652   }
5653
5654   // If we can fold this based on the true/false value, do so.
5655   if (SimplifySelectOps(N, N2, N3))
5656     return SDValue(N, 0);  // Don't revisit N.
5657
5658   // fold select_cc into other things, such as min/max/abs
5659   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5660 }
5661
5662 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5663   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5664                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5665                        SDLoc(N));
5666 }
5667
5668 /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
5669 /// a build_vector of constants.
5670 /// This function is called by the DAGCombiner when visiting sext/zext/aext
5671 /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5672 /// Vector extends are not folded if operations are legal; this is to
5673 /// avoid introducing illegal build_vector dag nodes.
5674 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5675                                          SelectionDAG &DAG, bool LegalTypes,
5676                                          bool LegalOperations) {
5677   unsigned Opcode = N->getOpcode();
5678   SDValue N0 = N->getOperand(0);
5679   EVT VT = N->getValueType(0);
5680
5681   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5682          Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5683          && "Expected EXTEND dag node in input!");
5684
5685   // fold (sext c1) -> c1
5686   // fold (zext c1) -> c1
5687   // fold (aext c1) -> c1
5688   if (isa<ConstantSDNode>(N0))
5689     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5690
5691   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5692   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5693   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5694   EVT SVT = VT.getScalarType();
5695   if (!(VT.isVector() &&
5696       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5697       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5698     return nullptr;
5699
5700   // We can fold this node into a build_vector.
5701   unsigned VTBits = SVT.getSizeInBits();
5702   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5703   SmallVector<SDValue, 8> Elts;
5704   unsigned NumElts = VT.getVectorNumElements();
5705   SDLoc DL(N);
5706
5707   for (unsigned i=0; i != NumElts; ++i) {
5708     SDValue Op = N0->getOperand(i);
5709     if (Op->getOpcode() == ISD::UNDEF) {
5710       Elts.push_back(DAG.getUNDEF(SVT));
5711       continue;
5712     }
5713
5714     SDLoc DL(Op);
5715     // Get the constant value and if needed trunc it to the size of the type.
5716     // Nodes like build_vector might have constants wider than the scalar type.
5717     APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
5718     if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
5719       Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
5720     else
5721       Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
5722   }
5723
5724   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5725 }
5726
5727 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5728 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5729 // transformation. Returns true if extension are possible and the above
5730 // mentioned transformation is profitable.
5731 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5732                                     unsigned ExtOpc,
5733                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5734                                     const TargetLowering &TLI) {
5735   bool HasCopyToRegUses = false;
5736   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5737   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5738                             UE = N0.getNode()->use_end();
5739        UI != UE; ++UI) {
5740     SDNode *User = *UI;
5741     if (User == N)
5742       continue;
5743     if (UI.getUse().getResNo() != N0.getResNo())
5744       continue;
5745     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5746     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5747       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5748       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5749         // Sign bits will be lost after a zext.
5750         return false;
5751       bool Add = false;
5752       for (unsigned i = 0; i != 2; ++i) {
5753         SDValue UseOp = User->getOperand(i);
5754         if (UseOp == N0)
5755           continue;
5756         if (!isa<ConstantSDNode>(UseOp))
5757           return false;
5758         Add = true;
5759       }
5760       if (Add)
5761         ExtendNodes.push_back(User);
5762       continue;
5763     }
5764     // If truncates aren't free and there are users we can't
5765     // extend, it isn't worthwhile.
5766     if (!isTruncFree)
5767       return false;
5768     // Remember if this value is live-out.
5769     if (User->getOpcode() == ISD::CopyToReg)
5770       HasCopyToRegUses = true;
5771   }
5772
5773   if (HasCopyToRegUses) {
5774     bool BothLiveOut = false;
5775     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5776          UI != UE; ++UI) {
5777       SDUse &Use = UI.getUse();
5778       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5779         BothLiveOut = true;
5780         break;
5781       }
5782     }
5783     if (BothLiveOut)
5784       // Both unextended and extended values are live out. There had better be
5785       // a good reason for the transformation.
5786       return ExtendNodes.size();
5787   }
5788   return true;
5789 }
5790
5791 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5792                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5793                                   ISD::NodeType ExtType) {
5794   // Extend SetCC uses if necessary.
5795   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5796     SDNode *SetCC = SetCCs[i];
5797     SmallVector<SDValue, 4> Ops;
5798
5799     for (unsigned j = 0; j != 2; ++j) {
5800       SDValue SOp = SetCC->getOperand(j);
5801       if (SOp == Trunc)
5802         Ops.push_back(ExtLoad);
5803       else
5804         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5805     }
5806
5807     Ops.push_back(SetCC->getOperand(2));
5808     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5809   }
5810 }
5811
5812 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5813 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5814   SDValue N0 = N->getOperand(0);
5815   EVT DstVT = N->getValueType(0);
5816   EVT SrcVT = N0.getValueType();
5817
5818   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5819           N->getOpcode() == ISD::ZERO_EXTEND) &&
5820          "Unexpected node type (not an extend)!");
5821
5822   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5823   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5824   //   (v8i32 (sext (v8i16 (load x))))
5825   // into:
5826   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5827   //                          (v4i32 (sextload (x + 16)))))
5828   // Where uses of the original load, i.e.:
5829   //   (v8i16 (load x))
5830   // are replaced with:
5831   //   (v8i16 (truncate
5832   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5833   //                            (v4i32 (sextload (x + 16)))))))
5834   //
5835   // This combine is only applicable to illegal, but splittable, vectors.
5836   // All legal types, and illegal non-vector types, are handled elsewhere.
5837   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5838   //
5839   if (N0->getOpcode() != ISD::LOAD)
5840     return SDValue();
5841
5842   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5843
5844   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5845       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5846       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5847     return SDValue();
5848
5849   SmallVector<SDNode *, 4> SetCCs;
5850   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5851     return SDValue();
5852
5853   ISD::LoadExtType ExtType =
5854       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5855
5856   // Try to split the vector types to get down to legal types.
5857   EVT SplitSrcVT = SrcVT;
5858   EVT SplitDstVT = DstVT;
5859   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5860          SplitSrcVT.getVectorNumElements() > 1) {
5861     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5862     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5863   }
5864
5865   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5866     return SDValue();
5867
5868   SDLoc DL(N);
5869   const unsigned NumSplits =
5870       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5871   const unsigned Stride = SplitSrcVT.getStoreSize();
5872   SmallVector<SDValue, 4> Loads;
5873   SmallVector<SDValue, 4> Chains;
5874
5875   SDValue BasePtr = LN0->getBasePtr();
5876   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5877     const unsigned Offset = Idx * Stride;
5878     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5879
5880     SDValue SplitLoad = DAG.getExtLoad(
5881         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5882         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5883         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5884         Align, LN0->getAAInfo());
5885
5886     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5887                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5888
5889     Loads.push_back(SplitLoad.getValue(0));
5890     Chains.push_back(SplitLoad.getValue(1));
5891   }
5892
5893   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5894   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5895
5896   CombineTo(N, NewValue);
5897
5898   // Replace uses of the original load (before extension)
5899   // with a truncate of the concatenated sextloaded vectors.
5900   SDValue Trunc =
5901       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5902   CombineTo(N0.getNode(), Trunc, NewChain);
5903   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5904                   (ISD::NodeType)N->getOpcode());
5905   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5906 }
5907
5908 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5909   SDValue N0 = N->getOperand(0);
5910   EVT VT = N->getValueType(0);
5911
5912   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5913                                               LegalOperations))
5914     return SDValue(Res, 0);
5915
5916   // fold (sext (sext x)) -> (sext x)
5917   // fold (sext (aext x)) -> (sext x)
5918   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5919     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5920                        N0.getOperand(0));
5921
5922   if (N0.getOpcode() == ISD::TRUNCATE) {
5923     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5924     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5925     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
5926       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5927       if (NarrowLoad.getNode() != N0.getNode()) {
5928         CombineTo(N0.getNode(), NarrowLoad);
5929         // CombineTo deleted the truncate, if needed, but not what's under it.
5930         AddToWorklist(oye);
5931       }
5932       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5933     }
5934
5935     // See if the value being truncated is already sign extended.  If so, just
5936     // eliminate the trunc/sext pair.
5937     SDValue Op = N0.getOperand(0);
5938     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5939     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5940     unsigned DestBits = VT.getScalarType().getSizeInBits();
5941     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5942
5943     if (OpBits == DestBits) {
5944       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5945       // bits, it is already ready.
5946       if (NumSignBits > DestBits-MidBits)
5947         return Op;
5948     } else if (OpBits < DestBits) {
5949       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5950       // bits, just sext from i32.
5951       if (NumSignBits > OpBits-MidBits)
5952         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5953     } else {
5954       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5955       // bits, just truncate to i32.
5956       if (NumSignBits > OpBits-MidBits)
5957         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5958     }
5959
5960     // fold (sext (truncate x)) -> (sextinreg x).
5961     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5962                                                  N0.getValueType())) {
5963       if (OpBits < DestBits)
5964         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5965       else if (OpBits > DestBits)
5966         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5967       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5968                          DAG.getValueType(N0.getValueType()));
5969     }
5970   }
5971
5972   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5973   // Only generate vector extloads when 1) they're legal, and 2) they are
5974   // deemed desirable by the target.
5975   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5976       ((!LegalOperations && !VT.isVector() &&
5977         !cast<LoadSDNode>(N0)->isVolatile()) ||
5978        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5979     bool DoXform = true;
5980     SmallVector<SDNode*, 4> SetCCs;
5981     if (!N0.hasOneUse())
5982       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5983     if (VT.isVector())
5984       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5985     if (DoXform) {
5986       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5987       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5988                                        LN0->getChain(),
5989                                        LN0->getBasePtr(), N0.getValueType(),
5990                                        LN0->getMemOperand());
5991       CombineTo(N, ExtLoad);
5992       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5993                                   N0.getValueType(), ExtLoad);
5994       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5995       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5996                       ISD::SIGN_EXTEND);
5997       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5998     }
5999   }
6000
6001   // fold (sext (load x)) to multiple smaller sextloads.
6002   // Only on illegal but splittable vectors.
6003   if (SDValue ExtLoad = CombineExtLoad(N))
6004     return ExtLoad;
6005
6006   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
6007   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
6008   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6009       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6010     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6011     EVT MemVT = LN0->getMemoryVT();
6012     if ((!LegalOperations && !LN0->isVolatile()) ||
6013         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
6014       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6015                                        LN0->getChain(),
6016                                        LN0->getBasePtr(), MemVT,
6017                                        LN0->getMemOperand());
6018       CombineTo(N, ExtLoad);
6019       CombineTo(N0.getNode(),
6020                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6021                             N0.getValueType(), ExtLoad),
6022                 ExtLoad.getValue(1));
6023       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6024     }
6025   }
6026
6027   // fold (sext (and/or/xor (load x), cst)) ->
6028   //      (and/or/xor (sextload x), (sext cst))
6029   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6030        N0.getOpcode() == ISD::XOR) &&
6031       isa<LoadSDNode>(N0.getOperand(0)) &&
6032       N0.getOperand(1).getOpcode() == ISD::Constant &&
6033       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
6034       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6035     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6036     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
6037       bool DoXform = true;
6038       SmallVector<SDNode*, 4> SetCCs;
6039       if (!N0.hasOneUse())
6040         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
6041                                           SetCCs, TLI);
6042       if (DoXform) {
6043         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
6044                                          LN0->getChain(), LN0->getBasePtr(),
6045                                          LN0->getMemoryVT(),
6046                                          LN0->getMemOperand());
6047         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6048         Mask = Mask.sext(VT.getSizeInBits());
6049         SDLoc DL(N);
6050         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6051                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6052         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6053                                     SDLoc(N0.getOperand(0)),
6054                                     N0.getOperand(0).getValueType(), ExtLoad);
6055         CombineTo(N, And);
6056         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6057         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6058                         ISD::SIGN_EXTEND);
6059         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6060       }
6061     }
6062   }
6063
6064   if (N0.getOpcode() == ISD::SETCC) {
6065     EVT N0VT = N0.getOperand(0).getValueType();
6066     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
6067     // Only do this before legalize for now.
6068     if (VT.isVector() && !LegalOperations &&
6069         TLI.getBooleanContents(N0VT) ==
6070             TargetLowering::ZeroOrNegativeOneBooleanContent) {
6071       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
6072       // of the same size as the compared operands. Only optimize sext(setcc())
6073       // if this is the case.
6074       EVT SVT = getSetCCResultType(N0VT);
6075
6076       // We know that the # elements of the results is the same as the
6077       // # elements of the compare (and the # elements of the compare result
6078       // for that matter).  Check to see that they are the same size.  If so,
6079       // we know that the element size of the sext'd result matches the
6080       // element size of the compare operands.
6081       if (VT.getSizeInBits() == SVT.getSizeInBits())
6082         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6083                              N0.getOperand(1),
6084                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6085
6086       // If the desired elements are smaller or larger than the source
6087       // elements we can use a matching integer vector type and then
6088       // truncate/sign extend
6089       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6090       if (SVT == MatchingVectorType) {
6091         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
6092                                N0.getOperand(0), N0.getOperand(1),
6093                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
6094         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
6095       }
6096     }
6097
6098     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
6099     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
6100     SDLoc DL(N);
6101     SDValue NegOne =
6102       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
6103     SDValue SCC =
6104       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6105                        NegOne, DAG.getConstant(0, DL, VT),
6106                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6107     if (SCC.getNode()) return SCC;
6108
6109     if (!VT.isVector()) {
6110       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
6111       if (!LegalOperations ||
6112           TLI.isOperationLegal(ISD::SETCC, N0.getOperand(0).getValueType())) {
6113         SDLoc DL(N);
6114         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
6115         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
6116                                      N0.getOperand(0), N0.getOperand(1), CC);
6117         return DAG.getSelect(DL, VT, SetCC,
6118                              NegOne, DAG.getConstant(0, DL, VT));
6119       }
6120     }
6121   }
6122
6123   // fold (sext x) -> (zext x) if the sign bit is known zero.
6124   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
6125       DAG.SignBitIsZero(N0))
6126     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
6127
6128   return SDValue();
6129 }
6130
6131 // isTruncateOf - If N is a truncate of some other value, return true, record
6132 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
6133 // This function computes KnownZero to avoid a duplicated call to
6134 // computeKnownBits in the caller.
6135 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
6136                          APInt &KnownZero) {
6137   APInt KnownOne;
6138   if (N->getOpcode() == ISD::TRUNCATE) {
6139     Op = N->getOperand(0);
6140     DAG.computeKnownBits(Op, KnownZero, KnownOne);
6141     return true;
6142   }
6143
6144   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
6145       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
6146     return false;
6147
6148   SDValue Op0 = N->getOperand(0);
6149   SDValue Op1 = N->getOperand(1);
6150   assert(Op0.getValueType() == Op1.getValueType());
6151
6152   if (isNullConstant(Op0))
6153     Op = Op1;
6154   else if (isNullConstant(Op1))
6155     Op = Op0;
6156   else
6157     return false;
6158
6159   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6160
6161   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6162     return false;
6163
6164   return true;
6165 }
6166
6167 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6168   SDValue N0 = N->getOperand(0);
6169   EVT VT = N->getValueType(0);
6170
6171   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6172                                               LegalOperations))
6173     return SDValue(Res, 0);
6174
6175   // fold (zext (zext x)) -> (zext x)
6176   // fold (zext (aext x)) -> (zext x)
6177   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6178     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6179                        N0.getOperand(0));
6180
6181   // fold (zext (truncate x)) -> (zext x) or
6182   //      (zext (truncate x)) -> (truncate x)
6183   // This is valid when the truncated bits of x are already zero.
6184   // FIXME: We should extend this to work for vectors too.
6185   SDValue Op;
6186   APInt KnownZero;
6187   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6188     APInt TruncatedBits =
6189       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6190       APInt(Op.getValueSizeInBits(), 0) :
6191       APInt::getBitsSet(Op.getValueSizeInBits(),
6192                         N0.getValueSizeInBits(),
6193                         std::min(Op.getValueSizeInBits(),
6194                                  VT.getSizeInBits()));
6195     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6196       if (VT.bitsGT(Op.getValueType()))
6197         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6198       if (VT.bitsLT(Op.getValueType()))
6199         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6200
6201       return Op;
6202     }
6203   }
6204
6205   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6206   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6207   if (N0.getOpcode() == ISD::TRUNCATE) {
6208     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6209       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6210       if (NarrowLoad.getNode() != N0.getNode()) {
6211         CombineTo(N0.getNode(), NarrowLoad);
6212         // CombineTo deleted the truncate, if needed, but not what's under it.
6213         AddToWorklist(oye);
6214       }
6215       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6216     }
6217   }
6218
6219   // fold (zext (truncate x)) -> (and x, mask)
6220   if (N0.getOpcode() == ISD::TRUNCATE) {
6221     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6222     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6223     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6224       SDNode *oye = N0.getNode()->getOperand(0).getNode();
6225       if (NarrowLoad.getNode() != N0.getNode()) {
6226         CombineTo(N0.getNode(), NarrowLoad);
6227         // CombineTo deleted the truncate, if needed, but not what's under it.
6228         AddToWorklist(oye);
6229       }
6230       return SDValue(N, 0); // Return N so it doesn't get rechecked!
6231     }
6232
6233     EVT SrcVT = N0.getOperand(0).getValueType();
6234     EVT MinVT = N0.getValueType();
6235
6236     // Try to mask before the extension to avoid having to generate a larger mask,
6237     // possibly over several sub-vectors.
6238     if (SrcVT.bitsLT(VT)) {
6239       if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
6240                                TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
6241         SDValue Op = N0.getOperand(0);
6242         Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6243         AddToWorklist(Op.getNode());
6244         return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
6245       }
6246     }
6247
6248     if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
6249       SDValue Op = N0.getOperand(0);
6250       if (SrcVT.bitsLT(VT)) {
6251         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6252         AddToWorklist(Op.getNode());
6253       } else if (SrcVT.bitsGT(VT)) {
6254         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6255         AddToWorklist(Op.getNode());
6256       }
6257       return DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT.getScalarType());
6258     }
6259   }
6260
6261   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6262   // if either of the casts is not free.
6263   if (N0.getOpcode() == ISD::AND &&
6264       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6265       N0.getOperand(1).getOpcode() == ISD::Constant &&
6266       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6267                            N0.getValueType()) ||
6268        !TLI.isZExtFree(N0.getValueType(), VT))) {
6269     SDValue X = N0.getOperand(0).getOperand(0);
6270     if (X.getValueType().bitsLT(VT)) {
6271       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6272     } else if (X.getValueType().bitsGT(VT)) {
6273       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6274     }
6275     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6276     Mask = Mask.zext(VT.getSizeInBits());
6277     SDLoc DL(N);
6278     return DAG.getNode(ISD::AND, DL, VT,
6279                        X, DAG.getConstant(Mask, DL, VT));
6280   }
6281
6282   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6283   // Only generate vector extloads when 1) they're legal, and 2) they are
6284   // deemed desirable by the target.
6285   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6286       ((!LegalOperations && !VT.isVector() &&
6287         !cast<LoadSDNode>(N0)->isVolatile()) ||
6288        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6289     bool DoXform = true;
6290     SmallVector<SDNode*, 4> SetCCs;
6291     if (!N0.hasOneUse())
6292       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6293     if (VT.isVector())
6294       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6295     if (DoXform) {
6296       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6297       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6298                                        LN0->getChain(),
6299                                        LN0->getBasePtr(), N0.getValueType(),
6300                                        LN0->getMemOperand());
6301       CombineTo(N, ExtLoad);
6302       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6303                                   N0.getValueType(), ExtLoad);
6304       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6305
6306       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6307                       ISD::ZERO_EXTEND);
6308       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6309     }
6310   }
6311
6312   // fold (zext (load x)) to multiple smaller zextloads.
6313   // Only on illegal but splittable vectors.
6314   if (SDValue ExtLoad = CombineExtLoad(N))
6315     return ExtLoad;
6316
6317   // fold (zext (and/or/xor (load x), cst)) ->
6318   //      (and/or/xor (zextload x), (zext cst))
6319   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6320        N0.getOpcode() == ISD::XOR) &&
6321       isa<LoadSDNode>(N0.getOperand(0)) &&
6322       N0.getOperand(1).getOpcode() == ISD::Constant &&
6323       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6324       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6325     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6326     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6327       bool DoXform = true;
6328       SmallVector<SDNode*, 4> SetCCs;
6329       if (!N0.hasOneUse())
6330         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6331                                           SetCCs, TLI);
6332       if (DoXform) {
6333         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6334                                          LN0->getChain(), LN0->getBasePtr(),
6335                                          LN0->getMemoryVT(),
6336                                          LN0->getMemOperand());
6337         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6338         Mask = Mask.zext(VT.getSizeInBits());
6339         SDLoc DL(N);
6340         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6341                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6342         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6343                                     SDLoc(N0.getOperand(0)),
6344                                     N0.getOperand(0).getValueType(), ExtLoad);
6345         CombineTo(N, And);
6346         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6347         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6348                         ISD::ZERO_EXTEND);
6349         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6350       }
6351     }
6352   }
6353
6354   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6355   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6356   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6357       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6358     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6359     EVT MemVT = LN0->getMemoryVT();
6360     if ((!LegalOperations && !LN0->isVolatile()) ||
6361         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6362       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6363                                        LN0->getChain(),
6364                                        LN0->getBasePtr(), MemVT,
6365                                        LN0->getMemOperand());
6366       CombineTo(N, ExtLoad);
6367       CombineTo(N0.getNode(),
6368                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6369                             ExtLoad),
6370                 ExtLoad.getValue(1));
6371       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6372     }
6373   }
6374
6375   if (N0.getOpcode() == ISD::SETCC) {
6376     if (!LegalOperations && VT.isVector() &&
6377         N0.getValueType().getVectorElementType() == MVT::i1) {
6378       EVT N0VT = N0.getOperand(0).getValueType();
6379       if (getSetCCResultType(N0VT) == N0.getValueType())
6380         return SDValue();
6381
6382       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6383       // Only do this before legalize for now.
6384       EVT EltVT = VT.getVectorElementType();
6385       SDLoc DL(N);
6386       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6387                                     DAG.getConstant(1, DL, EltVT));
6388       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6389         // We know that the # elements of the results is the same as the
6390         // # elements of the compare (and the # elements of the compare result
6391         // for that matter).  Check to see that they are the same size.  If so,
6392         // we know that the element size of the sext'd result matches the
6393         // element size of the compare operands.
6394         return DAG.getNode(ISD::AND, DL, VT,
6395                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6396                                          N0.getOperand(1),
6397                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6398                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6399                                        OneOps));
6400
6401       // If the desired elements are smaller or larger than the source
6402       // elements we can use a matching integer vector type and then
6403       // truncate/sign extend
6404       EVT MatchingElementType =
6405         EVT::getIntegerVT(*DAG.getContext(),
6406                           N0VT.getScalarType().getSizeInBits());
6407       EVT MatchingVectorType =
6408         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6409                          N0VT.getVectorNumElements());
6410       SDValue VsetCC =
6411         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6412                       N0.getOperand(1),
6413                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6414       return DAG.getNode(ISD::AND, DL, VT,
6415                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6416                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6417     }
6418
6419     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6420     SDLoc DL(N);
6421     SDValue SCC =
6422       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6423                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6424                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6425     if (SCC.getNode()) return SCC;
6426   }
6427
6428   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6429   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6430       isa<ConstantSDNode>(N0.getOperand(1)) &&
6431       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6432       N0.hasOneUse()) {
6433     SDValue ShAmt = N0.getOperand(1);
6434     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6435     if (N0.getOpcode() == ISD::SHL) {
6436       SDValue InnerZExt = N0.getOperand(0);
6437       // If the original shl may be shifting out bits, do not perform this
6438       // transformation.
6439       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6440         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6441       if (ShAmtVal > KnownZeroBits)
6442         return SDValue();
6443     }
6444
6445     SDLoc DL(N);
6446
6447     // Ensure that the shift amount is wide enough for the shifted value.
6448     if (VT.getSizeInBits() >= 256)
6449       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6450
6451     return DAG.getNode(N0.getOpcode(), DL, VT,
6452                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6453                        ShAmt);
6454   }
6455
6456   return SDValue();
6457 }
6458
6459 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6460   SDValue N0 = N->getOperand(0);
6461   EVT VT = N->getValueType(0);
6462
6463   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6464                                               LegalOperations))
6465     return SDValue(Res, 0);
6466
6467   // fold (aext (aext x)) -> (aext x)
6468   // fold (aext (zext x)) -> (zext x)
6469   // fold (aext (sext x)) -> (sext x)
6470   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6471       N0.getOpcode() == ISD::ZERO_EXTEND ||
6472       N0.getOpcode() == ISD::SIGN_EXTEND)
6473     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6474
6475   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6476   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6477   if (N0.getOpcode() == ISD::TRUNCATE) {
6478     if (SDValue NarrowLoad = ReduceLoadWidth(N0.getNode())) {
6479       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6480       if (NarrowLoad.getNode() != N0.getNode()) {
6481         CombineTo(N0.getNode(), NarrowLoad);
6482         // CombineTo deleted the truncate, if needed, but not what's under it.
6483         AddToWorklist(oye);
6484       }
6485       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6486     }
6487   }
6488
6489   // fold (aext (truncate x))
6490   if (N0.getOpcode() == ISD::TRUNCATE) {
6491     SDValue TruncOp = N0.getOperand(0);
6492     if (TruncOp.getValueType() == VT)
6493       return TruncOp; // x iff x size == zext size.
6494     if (TruncOp.getValueType().bitsGT(VT))
6495       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6496     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6497   }
6498
6499   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6500   // if the trunc is not free.
6501   if (N0.getOpcode() == ISD::AND &&
6502       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6503       N0.getOperand(1).getOpcode() == ISD::Constant &&
6504       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6505                           N0.getValueType())) {
6506     SDValue X = N0.getOperand(0).getOperand(0);
6507     if (X.getValueType().bitsLT(VT)) {
6508       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6509     } else if (X.getValueType().bitsGT(VT)) {
6510       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6511     }
6512     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6513     Mask = Mask.zext(VT.getSizeInBits());
6514     SDLoc DL(N);
6515     return DAG.getNode(ISD::AND, DL, VT,
6516                        X, DAG.getConstant(Mask, DL, VT));
6517   }
6518
6519   // fold (aext (load x)) -> (aext (truncate (extload x)))
6520   // None of the supported targets knows how to perform load and any_ext
6521   // on vectors in one instruction.  We only perform this transformation on
6522   // scalars.
6523   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6524       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6525       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6526     bool DoXform = true;
6527     SmallVector<SDNode*, 4> SetCCs;
6528     if (!N0.hasOneUse())
6529       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6530     if (DoXform) {
6531       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6532       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6533                                        LN0->getChain(),
6534                                        LN0->getBasePtr(), N0.getValueType(),
6535                                        LN0->getMemOperand());
6536       CombineTo(N, ExtLoad);
6537       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6538                                   N0.getValueType(), ExtLoad);
6539       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6540       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6541                       ISD::ANY_EXTEND);
6542       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6543     }
6544   }
6545
6546   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6547   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6548   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6549   if (N0.getOpcode() == ISD::LOAD &&
6550       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6551       N0.hasOneUse()) {
6552     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6553     ISD::LoadExtType ExtType = LN0->getExtensionType();
6554     EVT MemVT = LN0->getMemoryVT();
6555     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6556       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6557                                        VT, LN0->getChain(), LN0->getBasePtr(),
6558                                        MemVT, LN0->getMemOperand());
6559       CombineTo(N, ExtLoad);
6560       CombineTo(N0.getNode(),
6561                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6562                             N0.getValueType(), ExtLoad),
6563                 ExtLoad.getValue(1));
6564       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6565     }
6566   }
6567
6568   if (N0.getOpcode() == ISD::SETCC) {
6569     // For vectors:
6570     // aext(setcc) -> vsetcc
6571     // aext(setcc) -> truncate(vsetcc)
6572     // aext(setcc) -> aext(vsetcc)
6573     // Only do this before legalize for now.
6574     if (VT.isVector() && !LegalOperations) {
6575       EVT N0VT = N0.getOperand(0).getValueType();
6576         // We know that the # elements of the results is the same as the
6577         // # elements of the compare (and the # elements of the compare result
6578         // for that matter).  Check to see that they are the same size.  If so,
6579         // we know that the element size of the sext'd result matches the
6580         // element size of the compare operands.
6581       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6582         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6583                              N0.getOperand(1),
6584                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6585       // If the desired elements are smaller or larger than the source
6586       // elements we can use a matching integer vector type and then
6587       // truncate/any extend
6588       else {
6589         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6590         SDValue VsetCC =
6591           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6592                         N0.getOperand(1),
6593                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6594         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6595       }
6596     }
6597
6598     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6599     SDLoc DL(N);
6600     SDValue SCC =
6601       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6602                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6603                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6604     if (SCC.getNode())
6605       return SCC;
6606   }
6607
6608   return SDValue();
6609 }
6610
6611 /// See if the specified operand can be simplified with the knowledge that only
6612 /// the bits specified by Mask are used.  If so, return the simpler operand,
6613 /// otherwise return a null SDValue.
6614 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6615   switch (V.getOpcode()) {
6616   default: break;
6617   case ISD::Constant: {
6618     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6619     assert(CV && "Const value should be ConstSDNode.");
6620     const APInt &CVal = CV->getAPIntValue();
6621     APInt NewVal = CVal & Mask;
6622     if (NewVal != CVal)
6623       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6624     break;
6625   }
6626   case ISD::OR:
6627   case ISD::XOR:
6628     // If the LHS or RHS don't contribute bits to the or, drop them.
6629     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6630       return V.getOperand(1);
6631     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6632       return V.getOperand(0);
6633     break;
6634   case ISD::SRL:
6635     // Only look at single-use SRLs.
6636     if (!V.getNode()->hasOneUse())
6637       break;
6638     if (ConstantSDNode *RHSC = getAsNonOpaqueConstant(V.getOperand(1))) {
6639       // See if we can recursively simplify the LHS.
6640       unsigned Amt = RHSC->getZExtValue();
6641
6642       // Watch out for shift count overflow though.
6643       if (Amt >= Mask.getBitWidth()) break;
6644       APInt NewMask = Mask << Amt;
6645       if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
6646         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6647                            SimplifyLHS, V.getOperand(1));
6648     }
6649   }
6650   return SDValue();
6651 }
6652
6653 /// If the result of a wider load is shifted to right of N  bits and then
6654 /// truncated to a narrower type and where N is a multiple of number of bits of
6655 /// the narrower type, transform it to a narrower load from address + N / num of
6656 /// bits of new type. If the result is to be extended, also fold the extension
6657 /// to form a extending load.
6658 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6659   unsigned Opc = N->getOpcode();
6660
6661   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6662   SDValue N0 = N->getOperand(0);
6663   EVT VT = N->getValueType(0);
6664   EVT ExtVT = VT;
6665
6666   // This transformation isn't valid for vector loads.
6667   if (VT.isVector())
6668     return SDValue();
6669
6670   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6671   // extended to VT.
6672   if (Opc == ISD::SIGN_EXTEND_INREG) {
6673     ExtType = ISD::SEXTLOAD;
6674     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6675   } else if (Opc == ISD::SRL) {
6676     // Another special-case: SRL is basically zero-extending a narrower value.
6677     ExtType = ISD::ZEXTLOAD;
6678     N0 = SDValue(N, 0);
6679     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6680     if (!N01) return SDValue();
6681     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6682                               VT.getSizeInBits() - N01->getZExtValue());
6683   }
6684   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6685     return SDValue();
6686
6687   unsigned EVTBits = ExtVT.getSizeInBits();
6688
6689   // Do not generate loads of non-round integer types since these can
6690   // be expensive (and would be wrong if the type is not byte sized).
6691   if (!ExtVT.isRound())
6692     return SDValue();
6693
6694   unsigned ShAmt = 0;
6695   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6696     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6697       ShAmt = N01->getZExtValue();
6698       // Is the shift amount a multiple of size of VT?
6699       if ((ShAmt & (EVTBits-1)) == 0) {
6700         N0 = N0.getOperand(0);
6701         // Is the load width a multiple of size of VT?
6702         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6703           return SDValue();
6704       }
6705
6706       // At this point, we must have a load or else we can't do the transform.
6707       if (!isa<LoadSDNode>(N0)) return SDValue();
6708
6709       // Because a SRL must be assumed to *need* to zero-extend the high bits
6710       // (as opposed to anyext the high bits), we can't combine the zextload
6711       // lowering of SRL and an sextload.
6712       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6713         return SDValue();
6714
6715       // If the shift amount is larger than the input type then we're not
6716       // accessing any of the loaded bytes.  If the load was a zextload/extload
6717       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6718       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6719         return SDValue();
6720     }
6721   }
6722
6723   // If the load is shifted left (and the result isn't shifted back right),
6724   // we can fold the truncate through the shift.
6725   unsigned ShLeftAmt = 0;
6726   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6727       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6728     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6729       ShLeftAmt = N01->getZExtValue();
6730       N0 = N0.getOperand(0);
6731     }
6732   }
6733
6734   // If we haven't found a load, we can't narrow it.  Don't transform one with
6735   // multiple uses, this would require adding a new load.
6736   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6737     return SDValue();
6738
6739   // Don't change the width of a volatile load.
6740   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6741   if (LN0->isVolatile())
6742     return SDValue();
6743
6744   // Verify that we are actually reducing a load width here.
6745   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6746     return SDValue();
6747
6748   // For the transform to be legal, the load must produce only two values
6749   // (the value loaded and the chain).  Don't transform a pre-increment
6750   // load, for example, which produces an extra value.  Otherwise the
6751   // transformation is not equivalent, and the downstream logic to replace
6752   // uses gets things wrong.
6753   if (LN0->getNumValues() > 2)
6754     return SDValue();
6755
6756   // If the load that we're shrinking is an extload and we're not just
6757   // discarding the extension we can't simply shrink the load. Bail.
6758   // TODO: It would be possible to merge the extensions in some cases.
6759   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6760       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6761     return SDValue();
6762
6763   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6764     return SDValue();
6765
6766   EVT PtrType = N0.getOperand(1).getValueType();
6767
6768   if (PtrType == MVT::Untyped || PtrType.isExtended())
6769     // It's not possible to generate a constant of extended or untyped type.
6770     return SDValue();
6771
6772   // For big endian targets, we need to adjust the offset to the pointer to
6773   // load the correct bytes.
6774   if (DAG.getDataLayout().isBigEndian()) {
6775     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6776     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6777     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6778   }
6779
6780   uint64_t PtrOff = ShAmt / 8;
6781   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6782   SDLoc DL(LN0);
6783   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6784                                PtrType, LN0->getBasePtr(),
6785                                DAG.getConstant(PtrOff, DL, PtrType));
6786   AddToWorklist(NewPtr.getNode());
6787
6788   SDValue Load;
6789   if (ExtType == ISD::NON_EXTLOAD)
6790     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6791                         LN0->getPointerInfo().getWithOffset(PtrOff),
6792                         LN0->isVolatile(), LN0->isNonTemporal(),
6793                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6794   else
6795     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6796                           LN0->getPointerInfo().getWithOffset(PtrOff),
6797                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6798                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6799
6800   // Replace the old load's chain with the new load's chain.
6801   WorklistRemover DeadNodes(*this);
6802   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6803
6804   // Shift the result left, if we've swallowed a left shift.
6805   SDValue Result = Load;
6806   if (ShLeftAmt != 0) {
6807     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6808     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6809       ShImmTy = VT;
6810     // If the shift amount is as large as the result size (but, presumably,
6811     // no larger than the source) then the useful bits of the result are
6812     // zero; we can't simply return the shortened shift, because the result
6813     // of that operation is undefined.
6814     SDLoc DL(N0);
6815     if (ShLeftAmt >= VT.getSizeInBits())
6816       Result = DAG.getConstant(0, DL, VT);
6817     else
6818       Result = DAG.getNode(ISD::SHL, DL, VT,
6819                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6820   }
6821
6822   // Return the new loaded value.
6823   return Result;
6824 }
6825
6826 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6827   SDValue N0 = N->getOperand(0);
6828   SDValue N1 = N->getOperand(1);
6829   EVT VT = N->getValueType(0);
6830   EVT EVT = cast<VTSDNode>(N1)->getVT();
6831   unsigned VTBits = VT.getScalarType().getSizeInBits();
6832   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6833
6834   if (N0.isUndef())
6835     return DAG.getUNDEF(VT);
6836
6837   // fold (sext_in_reg c1) -> c1
6838   if (isConstantIntBuildVectorOrConstantInt(N0))
6839     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6840
6841   // If the input is already sign extended, just drop the extension.
6842   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6843     return N0;
6844
6845   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6846   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6847       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6848     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6849                        N0.getOperand(0), N1);
6850
6851   // fold (sext_in_reg (sext x)) -> (sext x)
6852   // fold (sext_in_reg (aext x)) -> (sext x)
6853   // if x is small enough.
6854   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6855     SDValue N00 = N0.getOperand(0);
6856     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6857         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6858       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6859   }
6860
6861   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6862   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6863     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6864
6865   // fold operands of sext_in_reg based on knowledge that the top bits are not
6866   // demanded.
6867   if (SimplifyDemandedBits(SDValue(N, 0)))
6868     return SDValue(N, 0);
6869
6870   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6871   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6872   if (SDValue NarrowLoad = ReduceLoadWidth(N))
6873     return NarrowLoad;
6874
6875   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6876   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6877   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6878   if (N0.getOpcode() == ISD::SRL) {
6879     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6880       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6881         // We can turn this into an SRA iff the input to the SRL is already sign
6882         // extended enough.
6883         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6884         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6885           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6886                              N0.getOperand(0), N0.getOperand(1));
6887       }
6888   }
6889
6890   // fold (sext_inreg (extload x)) -> (sextload x)
6891   if (ISD::isEXTLoad(N0.getNode()) &&
6892       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6893       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6894       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6895        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6896     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6897     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6898                                      LN0->getChain(),
6899                                      LN0->getBasePtr(), EVT,
6900                                      LN0->getMemOperand());
6901     CombineTo(N, ExtLoad);
6902     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6903     AddToWorklist(ExtLoad.getNode());
6904     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6905   }
6906   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6907   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6908       N0.hasOneUse() &&
6909       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6910       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6911        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6912     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6913     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6914                                      LN0->getChain(),
6915                                      LN0->getBasePtr(), EVT,
6916                                      LN0->getMemOperand());
6917     CombineTo(N, ExtLoad);
6918     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6919     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6920   }
6921
6922   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6923   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6924     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6925                                        N0.getOperand(1), false);
6926     if (BSwap.getNode())
6927       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6928                          BSwap, N1);
6929   }
6930
6931   return SDValue();
6932 }
6933
6934 SDValue DAGCombiner::visitSIGN_EXTEND_VECTOR_INREG(SDNode *N) {
6935   SDValue N0 = N->getOperand(0);
6936   EVT VT = N->getValueType(0);
6937
6938   if (N0.getOpcode() == ISD::UNDEF)
6939     return DAG.getUNDEF(VT);
6940
6941   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6942                                               LegalOperations))
6943     return SDValue(Res, 0);
6944
6945   return SDValue();
6946 }
6947
6948 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6949   SDValue N0 = N->getOperand(0);
6950   EVT VT = N->getValueType(0);
6951   bool isLE = DAG.getDataLayout().isLittleEndian();
6952
6953   // noop truncate
6954   if (N0.getValueType() == N->getValueType(0))
6955     return N0;
6956   // fold (truncate c1) -> c1
6957   if (isConstantIntBuildVectorOrConstantInt(N0))
6958     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6959   // fold (truncate (truncate x)) -> (truncate x)
6960   if (N0.getOpcode() == ISD::TRUNCATE)
6961     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6962   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6963   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6964       N0.getOpcode() == ISD::SIGN_EXTEND ||
6965       N0.getOpcode() == ISD::ANY_EXTEND) {
6966     if (N0.getOperand(0).getValueType().bitsLT(VT))
6967       // if the source is smaller than the dest, we still need an extend
6968       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6969                          N0.getOperand(0));
6970     if (N0.getOperand(0).getValueType().bitsGT(VT))
6971       // if the source is larger than the dest, than we just need the truncate
6972       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6973     // if the source and dest are the same type, we can drop both the extend
6974     // and the truncate.
6975     return N0.getOperand(0);
6976   }
6977
6978   // Fold extract-and-trunc into a narrow extract. For example:
6979   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6980   //   i32 y = TRUNCATE(i64 x)
6981   //        -- becomes --
6982   //   v16i8 b = BITCAST (v2i64 val)
6983   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6984   //
6985   // Note: We only run this optimization after type legalization (which often
6986   // creates this pattern) and before operation legalization after which
6987   // we need to be more careful about the vector instructions that we generate.
6988   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6989       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6990
6991     EVT VecTy = N0.getOperand(0).getValueType();
6992     EVT ExTy = N0.getValueType();
6993     EVT TrTy = N->getValueType(0);
6994
6995     unsigned NumElem = VecTy.getVectorNumElements();
6996     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6997
6998     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6999     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
7000
7001     SDValue EltNo = N0->getOperand(1);
7002     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
7003       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
7004       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
7005       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
7006
7007       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
7008                               NVT, N0.getOperand(0));
7009
7010       SDLoc DL(N);
7011       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
7012                          DL, TrTy, V,
7013                          DAG.getConstant(Index, DL, IndexTy));
7014     }
7015   }
7016
7017   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
7018   if (N0.getOpcode() == ISD::SELECT) {
7019     EVT SrcVT = N0.getValueType();
7020     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
7021         TLI.isTruncateFree(SrcVT, VT)) {
7022       SDLoc SL(N0);
7023       SDValue Cond = N0.getOperand(0);
7024       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
7025       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
7026       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
7027     }
7028   }
7029
7030   // Fold a series of buildvector, bitcast, and truncate if possible.
7031   // For example fold
7032   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
7033   //   (2xi32 (buildvector x, y)).
7034   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
7035       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
7036       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
7037       N0.getOperand(0).hasOneUse()) {
7038
7039     SDValue BuildVect = N0.getOperand(0);
7040     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
7041     EVT TruncVecEltTy = VT.getVectorElementType();
7042
7043     // Check that the element types match.
7044     if (BuildVectEltTy == TruncVecEltTy) {
7045       // Now we only need to compute the offset of the truncated elements.
7046       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
7047       unsigned TruncVecNumElts = VT.getVectorNumElements();
7048       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
7049
7050       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
7051              "Invalid number of elements");
7052
7053       SmallVector<SDValue, 8> Opnds;
7054       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
7055         Opnds.push_back(BuildVect.getOperand(i));
7056
7057       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
7058     }
7059   }
7060
7061   // See if we can simplify the input to this truncate through knowledge that
7062   // only the low bits are being used.
7063   // For example "trunc (or (shl x, 8), y)" // -> trunc y
7064   // Currently we only perform this optimization on scalars because vectors
7065   // may have different active low bits.
7066   if (!VT.isVector()) {
7067     SDValue Shorter =
7068       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
7069                                                VT.getSizeInBits()));
7070     if (Shorter.getNode())
7071       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
7072   }
7073   // fold (truncate (load x)) -> (smaller load x)
7074   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
7075   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
7076     if (SDValue Reduced = ReduceLoadWidth(N))
7077       return Reduced;
7078
7079     // Handle the case where the load remains an extending load even
7080     // after truncation.
7081     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
7082       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7083       if (!LN0->isVolatile() &&
7084           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
7085         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
7086                                          VT, LN0->getChain(), LN0->getBasePtr(),
7087                                          LN0->getMemoryVT(),
7088                                          LN0->getMemOperand());
7089         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
7090         return NewLoad;
7091       }
7092     }
7093   }
7094   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
7095   // where ... are all 'undef'.
7096   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
7097     SmallVector<EVT, 8> VTs;
7098     SDValue V;
7099     unsigned Idx = 0;
7100     unsigned NumDefs = 0;
7101
7102     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
7103       SDValue X = N0.getOperand(i);
7104       if (X.getOpcode() != ISD::UNDEF) {
7105         V = X;
7106         Idx = i;
7107         NumDefs++;
7108       }
7109       // Stop if more than one members are non-undef.
7110       if (NumDefs > 1)
7111         break;
7112       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
7113                                      VT.getVectorElementType(),
7114                                      X.getValueType().getVectorNumElements()));
7115     }
7116
7117     if (NumDefs == 0)
7118       return DAG.getUNDEF(VT);
7119
7120     if (NumDefs == 1) {
7121       assert(V.getNode() && "The single defined operand is empty!");
7122       SmallVector<SDValue, 8> Opnds;
7123       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
7124         if (i != Idx) {
7125           Opnds.push_back(DAG.getUNDEF(VTs[i]));
7126           continue;
7127         }
7128         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
7129         AddToWorklist(NV.getNode());
7130         Opnds.push_back(NV);
7131       }
7132       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
7133     }
7134   }
7135
7136   // Simplify the operands using demanded-bits information.
7137   if (!VT.isVector() &&
7138       SimplifyDemandedBits(SDValue(N, 0)))
7139     return SDValue(N, 0);
7140
7141   return SDValue();
7142 }
7143
7144 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
7145   SDValue Elt = N->getOperand(i);
7146   if (Elt.getOpcode() != ISD::MERGE_VALUES)
7147     return Elt.getNode();
7148   return Elt.getOperand(Elt.getResNo()).getNode();
7149 }
7150
7151 /// build_pair (load, load) -> load
7152 /// if load locations are consecutive.
7153 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7154   assert(N->getOpcode() == ISD::BUILD_PAIR);
7155
7156   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7157   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7158   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7159       LD1->getAddressSpace() != LD2->getAddressSpace())
7160     return SDValue();
7161   EVT LD1VT = LD1->getValueType(0);
7162
7163   if (ISD::isNON_EXTLoad(LD2) &&
7164       LD2->hasOneUse() &&
7165       // If both are volatile this would reduce the number of volatile loads.
7166       // If one is volatile it might be ok, but play conservative and bail out.
7167       !LD1->isVolatile() &&
7168       !LD2->isVolatile() &&
7169       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7170     unsigned Align = LD1->getAlignment();
7171     unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
7172         VT.getTypeForEVT(*DAG.getContext()));
7173
7174     if (NewAlign <= Align &&
7175         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7176       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7177                          LD1->getBasePtr(), LD1->getPointerInfo(),
7178                          false, false, false, Align);
7179   }
7180
7181   return SDValue();
7182 }
7183
7184 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7185   SDValue N0 = N->getOperand(0);
7186   EVT VT = N->getValueType(0);
7187
7188   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7189   // Only do this before legalize, since afterward the target may be depending
7190   // on the bitconvert.
7191   // First check to see if this is all constant.
7192   if (!LegalTypes &&
7193       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7194       VT.isVector()) {
7195     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7196
7197     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7198     assert(!DestEltVT.isVector() &&
7199            "Element type of vector ValueType must not be vector!");
7200     if (isSimple)
7201       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7202   }
7203
7204   // If the input is a constant, let getNode fold it.
7205   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7206     // If we can't allow illegal operations, we need to check that this is just
7207     // a fp -> int or int -> conversion and that the resulting operation will
7208     // be legal.
7209     if (!LegalOperations ||
7210         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7211          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7212         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7213          TLI.isOperationLegal(ISD::Constant, VT)))
7214       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7215   }
7216
7217   // (conv (conv x, t1), t2) -> (conv x, t2)
7218   if (N0.getOpcode() == ISD::BITCAST)
7219     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7220                        N0.getOperand(0));
7221
7222   // fold (conv (load x)) -> (load (conv*)x)
7223   // If the resultant load doesn't need a higher alignment than the original!
7224   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7225       // Do not change the width of a volatile load.
7226       !cast<LoadSDNode>(N0)->isVolatile() &&
7227       // Do not remove the cast if the types differ in endian layout.
7228       TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
7229           TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
7230       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7231       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7232     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7233     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
7234         VT.getTypeForEVT(*DAG.getContext()));
7235     unsigned OrigAlign = LN0->getAlignment();
7236
7237     if (Align <= OrigAlign) {
7238       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7239                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7240                                  LN0->isVolatile(), LN0->isNonTemporal(),
7241                                  LN0->isInvariant(), OrigAlign,
7242                                  LN0->getAAInfo());
7243       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7244       return Load;
7245     }
7246   }
7247
7248   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7249   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7250   // This often reduces constant pool loads.
7251   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7252        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7253       N0.getNode()->hasOneUse() && VT.isInteger() &&
7254       !VT.isVector() && !N0.getValueType().isVector()) {
7255     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7256                                   N0.getOperand(0));
7257     AddToWorklist(NewConv.getNode());
7258
7259     SDLoc DL(N);
7260     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7261     if (N0.getOpcode() == ISD::FNEG)
7262       return DAG.getNode(ISD::XOR, DL, VT,
7263                          NewConv, DAG.getConstant(SignBit, DL, VT));
7264     assert(N0.getOpcode() == ISD::FABS);
7265     return DAG.getNode(ISD::AND, DL, VT,
7266                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7267   }
7268
7269   // fold (bitconvert (fcopysign cst, x)) ->
7270   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7271   // Note that we don't handle (copysign x, cst) because this can always be
7272   // folded to an fneg or fabs.
7273   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7274       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7275       VT.isInteger() && !VT.isVector()) {
7276     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7277     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7278     if (isTypeLegal(IntXVT)) {
7279       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7280                               IntXVT, N0.getOperand(1));
7281       AddToWorklist(X.getNode());
7282
7283       // If X has a different width than the result/lhs, sext it or truncate it.
7284       unsigned VTWidth = VT.getSizeInBits();
7285       if (OrigXWidth < VTWidth) {
7286         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7287         AddToWorklist(X.getNode());
7288       } else if (OrigXWidth > VTWidth) {
7289         // To get the sign bit in the right place, we have to shift it right
7290         // before truncating.
7291         SDLoc DL(X);
7292         X = DAG.getNode(ISD::SRL, DL,
7293                         X.getValueType(), X,
7294                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7295                                         X.getValueType()));
7296         AddToWorklist(X.getNode());
7297         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7298         AddToWorklist(X.getNode());
7299       }
7300
7301       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7302       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7303                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7304       AddToWorklist(X.getNode());
7305
7306       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7307                                 VT, N0.getOperand(0));
7308       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7309                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7310       AddToWorklist(Cst.getNode());
7311
7312       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7313     }
7314   }
7315
7316   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7317   if (N0.getOpcode() == ISD::BUILD_PAIR)
7318     if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
7319       return CombineLD;
7320
7321   // Remove double bitcasts from shuffles - this is often a legacy of
7322   // XformToShuffleWithZero being used to combine bitmaskings (of
7323   // float vectors bitcast to integer vectors) into shuffles.
7324   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7325   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7326       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7327       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7328       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7329     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7330
7331     // If operands are a bitcast, peek through if it casts the original VT.
7332     // If operands are a constant, just bitcast back to original VT.
7333     auto PeekThroughBitcast = [&](SDValue Op) {
7334       if (Op.getOpcode() == ISD::BITCAST &&
7335           Op.getOperand(0).getValueType() == VT)
7336         return SDValue(Op.getOperand(0));
7337       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7338           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7339         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7340       return SDValue();
7341     };
7342
7343     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7344     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7345     if (!(SV0 && SV1))
7346       return SDValue();
7347
7348     int MaskScale =
7349         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7350     SmallVector<int, 8> NewMask;
7351     for (int M : SVN->getMask())
7352       for (int i = 0; i != MaskScale; ++i)
7353         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7354
7355     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7356     if (!LegalMask) {
7357       std::swap(SV0, SV1);
7358       ShuffleVectorSDNode::commuteMask(NewMask);
7359       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7360     }
7361
7362     if (LegalMask)
7363       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7364   }
7365
7366   return SDValue();
7367 }
7368
7369 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7370   EVT VT = N->getValueType(0);
7371   return CombineConsecutiveLoads(N, VT);
7372 }
7373
7374 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7375 /// operands. DstEltVT indicates the destination element value type.
7376 SDValue DAGCombiner::
7377 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7378   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7379
7380   // If this is already the right type, we're done.
7381   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7382
7383   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7384   unsigned DstBitSize = DstEltVT.getSizeInBits();
7385
7386   // If this is a conversion of N elements of one type to N elements of another
7387   // type, convert each element.  This handles FP<->INT cases.
7388   if (SrcBitSize == DstBitSize) {
7389     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7390                               BV->getValueType(0).getVectorNumElements());
7391
7392     // Due to the FP element handling below calling this routine recursively,
7393     // we can end up with a scalar-to-vector node here.
7394     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7395       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7396                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7397                                      DstEltVT, BV->getOperand(0)));
7398
7399     SmallVector<SDValue, 8> Ops;
7400     for (SDValue Op : BV->op_values()) {
7401       // If the vector element type is not legal, the BUILD_VECTOR operands
7402       // are promoted and implicitly truncated.  Make that explicit here.
7403       if (Op.getValueType() != SrcEltVT)
7404         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7405       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7406                                 DstEltVT, Op));
7407       AddToWorklist(Ops.back().getNode());
7408     }
7409     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7410   }
7411
7412   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7413   // handle annoying details of growing/shrinking FP values, we convert them to
7414   // int first.
7415   if (SrcEltVT.isFloatingPoint()) {
7416     // Convert the input float vector to a int vector where the elements are the
7417     // same sizes.
7418     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7419     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7420     SrcEltVT = IntVT;
7421   }
7422
7423   // Now we know the input is an integer vector.  If the output is a FP type,
7424   // convert to integer first, then to FP of the right size.
7425   if (DstEltVT.isFloatingPoint()) {
7426     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7427     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7428
7429     // Next, convert to FP elements of the same size.
7430     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7431   }
7432
7433   SDLoc DL(BV);
7434
7435   // Okay, we know the src/dst types are both integers of differing types.
7436   // Handling growing first.
7437   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7438   if (SrcBitSize < DstBitSize) {
7439     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7440
7441     SmallVector<SDValue, 8> Ops;
7442     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7443          i += NumInputsPerOutput) {
7444       bool isLE = DAG.getDataLayout().isLittleEndian();
7445       APInt NewBits = APInt(DstBitSize, 0);
7446       bool EltIsUndef = true;
7447       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7448         // Shift the previously computed bits over.
7449         NewBits <<= SrcBitSize;
7450         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7451         if (Op.getOpcode() == ISD::UNDEF) continue;
7452         EltIsUndef = false;
7453
7454         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7455                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7456       }
7457
7458       if (EltIsUndef)
7459         Ops.push_back(DAG.getUNDEF(DstEltVT));
7460       else
7461         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7462     }
7463
7464     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7465     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7466   }
7467
7468   // Finally, this must be the case where we are shrinking elements: each input
7469   // turns into multiple outputs.
7470   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7471   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7472                             NumOutputsPerInput*BV->getNumOperands());
7473   SmallVector<SDValue, 8> Ops;
7474
7475   for (const SDValue &Op : BV->op_values()) {
7476     if (Op.getOpcode() == ISD::UNDEF) {
7477       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7478       continue;
7479     }
7480
7481     APInt OpVal = cast<ConstantSDNode>(Op)->
7482                   getAPIntValue().zextOrTrunc(SrcBitSize);
7483
7484     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7485       APInt ThisVal = OpVal.trunc(DstBitSize);
7486       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7487       OpVal = OpVal.lshr(DstBitSize);
7488     }
7489
7490     // For big endian targets, swap the order of the pieces of each element.
7491     if (DAG.getDataLayout().isBigEndian())
7492       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7493   }
7494
7495   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7496 }
7497
7498 /// Try to perform FMA combining on a given FADD node.
7499 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7500   SDValue N0 = N->getOperand(0);
7501   SDValue N1 = N->getOperand(1);
7502   EVT VT = N->getValueType(0);
7503   SDLoc SL(N);
7504
7505   const TargetOptions &Options = DAG.getTarget().Options;
7506   bool AllowFusion =
7507       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7508
7509   // Floating-point multiply-add with intermediate rounding.
7510   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7511
7512   // Floating-point multiply-add without intermediate rounding.
7513   bool HasFMA =
7514       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7515       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7516
7517   // No valid opcode, do not combine.
7518   if (!HasFMAD && !HasFMA)
7519     return SDValue();
7520
7521   // Always prefer FMAD to FMA for precision.
7522   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7523   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7524   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7525
7526   // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
7527   // prefer to fold the multiply with fewer uses.
7528   if (Aggressive && N0.getOpcode() == ISD::FMUL &&
7529       N1.getOpcode() == ISD::FMUL) {
7530     if (N0.getNode()->use_size() > N1.getNode()->use_size())
7531       std::swap(N0, N1);
7532   }
7533
7534   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7535   if (N0.getOpcode() == ISD::FMUL &&
7536       (Aggressive || N0->hasOneUse())) {
7537     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7538                        N0.getOperand(0), N0.getOperand(1), N1);
7539   }
7540
7541   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7542   // Note: Commutes FADD operands.
7543   if (N1.getOpcode() == ISD::FMUL &&
7544       (Aggressive || N1->hasOneUse())) {
7545     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7546                        N1.getOperand(0), N1.getOperand(1), N0);
7547   }
7548
7549   // Look through FP_EXTEND nodes to do more combining.
7550   if (AllowFusion && LookThroughFPExt) {
7551     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7552     if (N0.getOpcode() == ISD::FP_EXTEND) {
7553       SDValue N00 = N0.getOperand(0);
7554       if (N00.getOpcode() == ISD::FMUL)
7555         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7556                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7557                                        N00.getOperand(0)),
7558                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7559                                        N00.getOperand(1)), N1);
7560     }
7561
7562     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7563     // Note: Commutes FADD operands.
7564     if (N1.getOpcode() == ISD::FP_EXTEND) {
7565       SDValue N10 = N1.getOperand(0);
7566       if (N10.getOpcode() == ISD::FMUL)
7567         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7568                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7569                                        N10.getOperand(0)),
7570                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7571                                        N10.getOperand(1)), N0);
7572     }
7573   }
7574
7575   // More folding opportunities when target permits.
7576   if ((AllowFusion || HasFMAD)  && Aggressive) {
7577     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7578     if (N0.getOpcode() == PreferredFusedOpcode &&
7579         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7580       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581                          N0.getOperand(0), N0.getOperand(1),
7582                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7583                                      N0.getOperand(2).getOperand(0),
7584                                      N0.getOperand(2).getOperand(1),
7585                                      N1));
7586     }
7587
7588     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7589     if (N1->getOpcode() == PreferredFusedOpcode &&
7590         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7591       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                          N1.getOperand(0), N1.getOperand(1),
7593                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7594                                      N1.getOperand(2).getOperand(0),
7595                                      N1.getOperand(2).getOperand(1),
7596                                      N0));
7597     }
7598
7599     if (AllowFusion && LookThroughFPExt) {
7600       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7601       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7602       auto FoldFAddFMAFPExtFMul = [&] (
7603           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7604         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7605                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7606                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7607                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7608                                        Z));
7609       };
7610       if (N0.getOpcode() == PreferredFusedOpcode) {
7611         SDValue N02 = N0.getOperand(2);
7612         if (N02.getOpcode() == ISD::FP_EXTEND) {
7613           SDValue N020 = N02.getOperand(0);
7614           if (N020.getOpcode() == ISD::FMUL)
7615             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7616                                         N020.getOperand(0), N020.getOperand(1),
7617                                         N1);
7618         }
7619       }
7620
7621       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7622       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
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       auto FoldFAddFPExtFMAFMul = [&] (
7627           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7628         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7629                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7630                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7631                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7632                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7633                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7634                                        Z));
7635       };
7636       if (N0.getOpcode() == ISD::FP_EXTEND) {
7637         SDValue N00 = N0.getOperand(0);
7638         if (N00.getOpcode() == PreferredFusedOpcode) {
7639           SDValue N002 = N00.getOperand(2);
7640           if (N002.getOpcode() == ISD::FMUL)
7641             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7642                                         N002.getOperand(0), N002.getOperand(1),
7643                                         N1);
7644         }
7645       }
7646
7647       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7648       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7649       if (N1.getOpcode() == PreferredFusedOpcode) {
7650         SDValue N12 = N1.getOperand(2);
7651         if (N12.getOpcode() == ISD::FP_EXTEND) {
7652           SDValue N120 = N12.getOperand(0);
7653           if (N120.getOpcode() == ISD::FMUL)
7654             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7655                                         N120.getOperand(0), N120.getOperand(1),
7656                                         N0);
7657         }
7658       }
7659
7660       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7661       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7662       // FIXME: This turns two single-precision and one double-precision
7663       // operation into two double-precision operations, which might not be
7664       // interesting for all targets, especially GPUs.
7665       if (N1.getOpcode() == ISD::FP_EXTEND) {
7666         SDValue N10 = N1.getOperand(0);
7667         if (N10.getOpcode() == PreferredFusedOpcode) {
7668           SDValue N102 = N10.getOperand(2);
7669           if (N102.getOpcode() == ISD::FMUL)
7670             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7671                                         N102.getOperand(0), N102.getOperand(1),
7672                                         N0);
7673         }
7674       }
7675     }
7676   }
7677
7678   return SDValue();
7679 }
7680
7681 /// Try to perform FMA combining on a given FSUB node.
7682 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7683   SDValue N0 = N->getOperand(0);
7684   SDValue N1 = N->getOperand(1);
7685   EVT VT = N->getValueType(0);
7686   SDLoc SL(N);
7687
7688   const TargetOptions &Options = DAG.getTarget().Options;
7689   bool AllowFusion =
7690       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7691
7692   // Floating-point multiply-add with intermediate rounding.
7693   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7694
7695   // Floating-point multiply-add without intermediate rounding.
7696   bool HasFMA =
7697       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7698       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7699
7700   // No valid opcode, do not combine.
7701   if (!HasFMAD && !HasFMA)
7702     return SDValue();
7703
7704   // Always prefer FMAD to FMA for precision.
7705   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7706   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7707   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7708
7709   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7710   if (N0.getOpcode() == ISD::FMUL &&
7711       (Aggressive || N0->hasOneUse())) {
7712     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7713                        N0.getOperand(0), N0.getOperand(1),
7714                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7715   }
7716
7717   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7718   // Note: Commutes FSUB operands.
7719   if (N1.getOpcode() == ISD::FMUL &&
7720       (Aggressive || N1->hasOneUse()))
7721     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7722                        DAG.getNode(ISD::FNEG, SL, VT,
7723                                    N1.getOperand(0)),
7724                        N1.getOperand(1), N0);
7725
7726   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7727   if (N0.getOpcode() == ISD::FNEG &&
7728       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7729       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7730     SDValue N00 = N0.getOperand(0).getOperand(0);
7731     SDValue N01 = N0.getOperand(0).getOperand(1);
7732     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7733                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7734                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7735   }
7736
7737   // Look through FP_EXTEND nodes to do more combining.
7738   if (AllowFusion && LookThroughFPExt) {
7739     // fold (fsub (fpext (fmul x, y)), z)
7740     //   -> (fma (fpext x), (fpext y), (fneg z))
7741     if (N0.getOpcode() == ISD::FP_EXTEND) {
7742       SDValue N00 = N0.getOperand(0);
7743       if (N00.getOpcode() == ISD::FMUL)
7744         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7745                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7746                                        N00.getOperand(0)),
7747                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7748                                        N00.getOperand(1)),
7749                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7750     }
7751
7752     // fold (fsub x, (fpext (fmul y, z)))
7753     //   -> (fma (fneg (fpext y)), (fpext z), x)
7754     // Note: Commutes FSUB operands.
7755     if (N1.getOpcode() == ISD::FP_EXTEND) {
7756       SDValue N10 = N1.getOperand(0);
7757       if (N10.getOpcode() == ISD::FMUL)
7758         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7759                            DAG.getNode(ISD::FNEG, SL, VT,
7760                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7761                                                    N10.getOperand(0))),
7762                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7763                                        N10.getOperand(1)),
7764                            N0);
7765     }
7766
7767     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7768     //   -> (fneg (fma (fpext x), (fpext y), z))
7769     // Note: This could be removed with appropriate canonicalization of the
7770     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7771     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7772     // from implementing the canonicalization in visitFSUB.
7773     if (N0.getOpcode() == ISD::FP_EXTEND) {
7774       SDValue N00 = N0.getOperand(0);
7775       if (N00.getOpcode() == ISD::FNEG) {
7776         SDValue N000 = N00.getOperand(0);
7777         if (N000.getOpcode() == ISD::FMUL) {
7778           return DAG.getNode(ISD::FNEG, SL, VT,
7779                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7780                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7781                                                      N000.getOperand(0)),
7782                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7783                                                      N000.getOperand(1)),
7784                                          N1));
7785         }
7786       }
7787     }
7788
7789     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7790     //   -> (fneg (fma (fpext x)), (fpext y), z)
7791     // Note: This could be removed with appropriate canonicalization of the
7792     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7793     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7794     // from implementing the canonicalization in visitFSUB.
7795     if (N0.getOpcode() == ISD::FNEG) {
7796       SDValue N00 = N0.getOperand(0);
7797       if (N00.getOpcode() == ISD::FP_EXTEND) {
7798         SDValue N000 = N00.getOperand(0);
7799         if (N000.getOpcode() == ISD::FMUL) {
7800           return DAG.getNode(ISD::FNEG, SL, VT,
7801                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7802                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7803                                                      N000.getOperand(0)),
7804                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7805                                                      N000.getOperand(1)),
7806                                          N1));
7807         }
7808       }
7809     }
7810
7811   }
7812
7813   // More folding opportunities when target permits.
7814   if ((AllowFusion || HasFMAD) && Aggressive) {
7815     // fold (fsub (fma x, y, (fmul u, v)), z)
7816     //   -> (fma x, y (fma u, v, (fneg z)))
7817     if (N0.getOpcode() == PreferredFusedOpcode &&
7818         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7819       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7820                          N0.getOperand(0), N0.getOperand(1),
7821                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7822                                      N0.getOperand(2).getOperand(0),
7823                                      N0.getOperand(2).getOperand(1),
7824                                      DAG.getNode(ISD::FNEG, SL, VT,
7825                                                  N1)));
7826     }
7827
7828     // fold (fsub x, (fma y, z, (fmul u, v)))
7829     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7830     if (N1.getOpcode() == PreferredFusedOpcode &&
7831         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7832       SDValue N20 = N1.getOperand(2).getOperand(0);
7833       SDValue N21 = N1.getOperand(2).getOperand(1);
7834       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7835                          DAG.getNode(ISD::FNEG, SL, VT,
7836                                      N1.getOperand(0)),
7837                          N1.getOperand(1),
7838                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7839                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7840
7841                                      N21, N0));
7842     }
7843
7844     if (AllowFusion && LookThroughFPExt) {
7845       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7846       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7847       if (N0.getOpcode() == PreferredFusedOpcode) {
7848         SDValue N02 = N0.getOperand(2);
7849         if (N02.getOpcode() == ISD::FP_EXTEND) {
7850           SDValue N020 = N02.getOperand(0);
7851           if (N020.getOpcode() == ISD::FMUL)
7852             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7853                                N0.getOperand(0), N0.getOperand(1),
7854                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7855                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7856                                                        N020.getOperand(0)),
7857                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7858                                                        N020.getOperand(1)),
7859                                            DAG.getNode(ISD::FNEG, SL, VT,
7860                                                        N1)));
7861         }
7862       }
7863
7864       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7865       //   -> (fma (fpext x), (fpext y),
7866       //           (fma (fpext u), (fpext v), (fneg z)))
7867       // FIXME: This turns two single-precision and one double-precision
7868       // operation into two double-precision operations, which might not be
7869       // interesting for all targets, especially GPUs.
7870       if (N0.getOpcode() == ISD::FP_EXTEND) {
7871         SDValue N00 = N0.getOperand(0);
7872         if (N00.getOpcode() == PreferredFusedOpcode) {
7873           SDValue N002 = N00.getOperand(2);
7874           if (N002.getOpcode() == ISD::FMUL)
7875             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7876                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7877                                            N00.getOperand(0)),
7878                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7879                                            N00.getOperand(1)),
7880                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7881                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7882                                                        N002.getOperand(0)),
7883                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7884                                                        N002.getOperand(1)),
7885                                            DAG.getNode(ISD::FNEG, SL, VT,
7886                                                        N1)));
7887         }
7888       }
7889
7890       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7891       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7892       if (N1.getOpcode() == PreferredFusedOpcode &&
7893         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7894         SDValue N120 = N1.getOperand(2).getOperand(0);
7895         if (N120.getOpcode() == ISD::FMUL) {
7896           SDValue N1200 = N120.getOperand(0);
7897           SDValue N1201 = N120.getOperand(1);
7898           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7899                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7900                              N1.getOperand(1),
7901                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7902                                          DAG.getNode(ISD::FNEG, SL, VT,
7903                                              DAG.getNode(ISD::FP_EXTEND, SL,
7904                                                          VT, N1200)),
7905                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7906                                                      N1201),
7907                                          N0));
7908         }
7909       }
7910
7911       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7912       //   -> (fma (fneg (fpext y)), (fpext z),
7913       //           (fma (fneg (fpext u)), (fpext v), x))
7914       // FIXME: This turns two single-precision and one double-precision
7915       // operation into two double-precision operations, which might not be
7916       // interesting for all targets, especially GPUs.
7917       if (N1.getOpcode() == ISD::FP_EXTEND &&
7918         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7919         SDValue N100 = N1.getOperand(0).getOperand(0);
7920         SDValue N101 = N1.getOperand(0).getOperand(1);
7921         SDValue N102 = N1.getOperand(0).getOperand(2);
7922         if (N102.getOpcode() == ISD::FMUL) {
7923           SDValue N1020 = N102.getOperand(0);
7924           SDValue N1021 = N102.getOperand(1);
7925           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7926                              DAG.getNode(ISD::FNEG, SL, VT,
7927                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7928                                                      N100)),
7929                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7930                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7931                                          DAG.getNode(ISD::FNEG, SL, VT,
7932                                              DAG.getNode(ISD::FP_EXTEND, SL,
7933                                                          VT, N1020)),
7934                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7935                                                      N1021),
7936                                          N0));
7937         }
7938       }
7939     }
7940   }
7941
7942   return SDValue();
7943 }
7944
7945 /// Try to perform FMA combining on a given FMUL node.
7946 SDValue DAGCombiner::visitFMULForFMACombine(SDNode *N) {
7947   SDValue N0 = N->getOperand(0);
7948   SDValue N1 = N->getOperand(1);
7949   EVT VT = N->getValueType(0);
7950   SDLoc SL(N);
7951
7952   assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
7953
7954   const TargetOptions &Options = DAG.getTarget().Options;
7955   bool AllowFusion =
7956       (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath);
7957
7958   // Floating-point multiply-add with intermediate rounding.
7959   bool HasFMAD = (LegalOperations && TLI.isOperationLegal(ISD::FMAD, VT));
7960
7961   // Floating-point multiply-add without intermediate rounding.
7962   bool HasFMA =
7963       AllowFusion && TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7964       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
7965
7966   // No valid opcode, do not combine.
7967   if (!HasFMAD && !HasFMA)
7968     return SDValue();
7969
7970   // Always prefer FMAD to FMA for precision.
7971   unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7972   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7973
7974   // fold (fmul (fadd x, +1.0), y) -> (fma x, y, y)
7975   // fold (fmul (fadd x, -1.0), y) -> (fma x, y, (fneg y))
7976   auto FuseFADD = [&](SDValue X, SDValue Y) {
7977     if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
7978       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
7979       if (XC1 && XC1->isExactlyValue(+1.0))
7980         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
7981       if (XC1 && XC1->isExactlyValue(-1.0))
7982         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
7983                            DAG.getNode(ISD::FNEG, SL, VT, Y));
7984     }
7985     return SDValue();
7986   };
7987
7988   if (SDValue FMA = FuseFADD(N0, N1))
7989     return FMA;
7990   if (SDValue FMA = FuseFADD(N1, N0))
7991     return FMA;
7992
7993   // fold (fmul (fsub +1.0, x), y) -> (fma (fneg x), y, y)
7994   // fold (fmul (fsub -1.0, x), y) -> (fma (fneg x), y, (fneg y))
7995   // fold (fmul (fsub x, +1.0), y) -> (fma x, y, (fneg y))
7996   // fold (fmul (fsub x, -1.0), y) -> (fma x, y, y)
7997   auto FuseFSUB = [&](SDValue X, SDValue Y) {
7998     if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
7999       auto XC0 = isConstOrConstSplatFP(X.getOperand(0));
8000       if (XC0 && XC0->isExactlyValue(+1.0))
8001         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8002                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8003                            Y);
8004       if (XC0 && XC0->isExactlyValue(-1.0))
8005         return DAG.getNode(PreferredFusedOpcode, SL, VT,
8006                            DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
8007                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8008
8009       auto XC1 = isConstOrConstSplatFP(X.getOperand(1));
8010       if (XC1 && XC1->isExactlyValue(+1.0))
8011         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
8012                            DAG.getNode(ISD::FNEG, SL, VT, Y));
8013       if (XC1 && XC1->isExactlyValue(-1.0))
8014         return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y, Y);
8015     }
8016     return SDValue();
8017   };
8018
8019   if (SDValue FMA = FuseFSUB(N0, N1))
8020     return FMA;
8021   if (SDValue FMA = FuseFSUB(N1, N0))
8022     return FMA;
8023
8024   return SDValue();
8025 }
8026
8027 SDValue DAGCombiner::visitFADD(SDNode *N) {
8028   SDValue N0 = N->getOperand(0);
8029   SDValue N1 = N->getOperand(1);
8030   bool N0CFP = isConstantFPBuildVectorOrConstantFP(N0);
8031   bool N1CFP = isConstantFPBuildVectorOrConstantFP(N1);
8032   EVT VT = N->getValueType(0);
8033   SDLoc DL(N);
8034   const TargetOptions &Options = DAG.getTarget().Options;
8035   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8036
8037   // fold vector ops
8038   if (VT.isVector())
8039     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8040       return FoldedVOp;
8041
8042   // fold (fadd c1, c2) -> c1 + c2
8043   if (N0CFP && N1CFP)
8044     return DAG.getNode(ISD::FADD, DL, VT, N0, N1, Flags);
8045
8046   // canonicalize constant to RHS
8047   if (N0CFP && !N1CFP)
8048     return DAG.getNode(ISD::FADD, DL, VT, N1, N0, Flags);
8049
8050   // fold (fadd A, (fneg B)) -> (fsub A, B)
8051   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8052       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
8053     return DAG.getNode(ISD::FSUB, DL, VT, N0,
8054                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8055
8056   // fold (fadd (fneg A), B) -> (fsub B, A)
8057   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
8058       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
8059     return DAG.getNode(ISD::FSUB, DL, VT, N1,
8060                        GetNegatedExpression(N0, DAG, LegalOperations), Flags);
8061
8062   // If 'unsafe math' is enabled, fold lots of things.
8063   if (Options.UnsafeFPMath) {
8064     // No FP constant should be created after legalization as Instruction
8065     // Selection pass has a hard time dealing with FP constants.
8066     bool AllowNewConst = (Level < AfterLegalizeDAG);
8067
8068     // fold (fadd A, 0) -> A
8069     if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1))
8070       if (N1C->isZero())
8071         return N0;
8072
8073     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
8074     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
8075         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1)))
8076       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
8077                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1,
8078                                      Flags),
8079                          Flags);
8080
8081     // If allowed, fold (fadd (fneg x), x) -> 0.0
8082     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
8083       return DAG.getConstantFP(0.0, DL, VT);
8084
8085     // If allowed, fold (fadd x, (fneg x)) -> 0.0
8086     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
8087       return DAG.getConstantFP(0.0, DL, VT);
8088
8089     // We can fold chains of FADD's of the same value into multiplications.
8090     // This transform is not safe in general because we are reducing the number
8091     // of rounding steps.
8092     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
8093       if (N0.getOpcode() == ISD::FMUL) {
8094         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8095         bool CFP01 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
8096
8097         // (fadd (fmul x, c), x) -> (fmul x, c+1)
8098         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
8099           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8100                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8101           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP, Flags);
8102         }
8103
8104         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
8105         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
8106             N1.getOperand(0) == N1.getOperand(1) &&
8107             N0.getOperand(0) == N1.getOperand(0)) {
8108           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
8109                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8110           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP, Flags);
8111         }
8112       }
8113
8114       if (N1.getOpcode() == ISD::FMUL) {
8115         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8116         bool CFP11 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
8117
8118         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
8119         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
8120           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8121                                        DAG.getConstantFP(1.0, DL, VT), Flags);
8122           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP, Flags);
8123         }
8124
8125         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
8126         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
8127             N0.getOperand(0) == N0.getOperand(1) &&
8128             N1.getOperand(0) == N0.getOperand(0)) {
8129           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
8130                                        DAG.getConstantFP(2.0, DL, VT), Flags);
8131           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP, Flags);
8132         }
8133       }
8134
8135       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
8136         bool CFP00 = isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
8137         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
8138         if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
8139             (N0.getOperand(0) == N1)) {
8140           return DAG.getNode(ISD::FMUL, DL, VT,
8141                              N1, DAG.getConstantFP(3.0, DL, VT), Flags);
8142         }
8143       }
8144
8145       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
8146         bool CFP10 = isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
8147         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
8148         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
8149             N1.getOperand(0) == N0) {
8150           return DAG.getNode(ISD::FMUL, DL, VT,
8151                              N0, DAG.getConstantFP(3.0, DL, VT), Flags);
8152         }
8153       }
8154
8155       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
8156       if (AllowNewConst &&
8157           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
8158           N0.getOperand(0) == N0.getOperand(1) &&
8159           N1.getOperand(0) == N1.getOperand(1) &&
8160           N0.getOperand(0) == N1.getOperand(0)) {
8161         return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
8162                            DAG.getConstantFP(4.0, DL, VT), Flags);
8163       }
8164     }
8165   } // enable-unsafe-fp-math
8166
8167   // FADD -> FMA combines:
8168   if (SDValue Fused = visitFADDForFMACombine(N)) {
8169     AddToWorklist(Fused.getNode());
8170     return Fused;
8171   }
8172
8173   return SDValue();
8174 }
8175
8176 SDValue DAGCombiner::visitFSUB(SDNode *N) {
8177   SDValue N0 = N->getOperand(0);
8178   SDValue N1 = N->getOperand(1);
8179   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8180   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8181   EVT VT = N->getValueType(0);
8182   SDLoc dl(N);
8183   const TargetOptions &Options = DAG.getTarget().Options;
8184   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8185
8186   // fold vector ops
8187   if (VT.isVector())
8188     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8189       return FoldedVOp;
8190
8191   // fold (fsub c1, c2) -> c1-c2
8192   if (N0CFP && N1CFP)
8193     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1, Flags);
8194
8195   // fold (fsub A, (fneg B)) -> (fadd A, B)
8196   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8197     return DAG.getNode(ISD::FADD, dl, VT, N0,
8198                        GetNegatedExpression(N1, DAG, LegalOperations), Flags);
8199
8200   // If 'unsafe math' is enabled, fold lots of things.
8201   if (Options.UnsafeFPMath) {
8202     // (fsub A, 0) -> A
8203     if (N1CFP && N1CFP->isZero())
8204       return N0;
8205
8206     // (fsub 0, B) -> -B
8207     if (N0CFP && N0CFP->isZero()) {
8208       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
8209         return GetNegatedExpression(N1, DAG, LegalOperations);
8210       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8211         return DAG.getNode(ISD::FNEG, dl, VT, N1);
8212     }
8213
8214     // (fsub x, x) -> 0.0
8215     if (N0 == N1)
8216       return DAG.getConstantFP(0.0f, dl, VT);
8217
8218     // (fsub x, (fadd x, y)) -> (fneg y)
8219     // (fsub x, (fadd y, x)) -> (fneg y)
8220     if (N1.getOpcode() == ISD::FADD) {
8221       SDValue N10 = N1->getOperand(0);
8222       SDValue N11 = N1->getOperand(1);
8223
8224       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
8225         return GetNegatedExpression(N11, DAG, LegalOperations);
8226
8227       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
8228         return GetNegatedExpression(N10, DAG, LegalOperations);
8229     }
8230   }
8231
8232   // FSUB -> FMA combines:
8233   if (SDValue Fused = visitFSUBForFMACombine(N)) {
8234     AddToWorklist(Fused.getNode());
8235     return Fused;
8236   }
8237
8238   return SDValue();
8239 }
8240
8241 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8242   SDValue N0 = N->getOperand(0);
8243   SDValue N1 = N->getOperand(1);
8244   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8245   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8246   EVT VT = N->getValueType(0);
8247   SDLoc DL(N);
8248   const TargetOptions &Options = DAG.getTarget().Options;
8249   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8250
8251   // fold vector ops
8252   if (VT.isVector()) {
8253     // This just handles C1 * C2 for vectors. Other vector folds are below.
8254     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8255       return FoldedVOp;
8256   }
8257
8258   // fold (fmul c1, c2) -> c1*c2
8259   if (N0CFP && N1CFP)
8260     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1, Flags);
8261
8262   // canonicalize constant to RHS
8263   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8264      !isConstantFPBuildVectorOrConstantFP(N1))
8265     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0, Flags);
8266
8267   // fold (fmul A, 1.0) -> A
8268   if (N1CFP && N1CFP->isExactlyValue(1.0))
8269     return N0;
8270
8271   if (Options.UnsafeFPMath) {
8272     // fold (fmul A, 0) -> 0
8273     if (N1CFP && N1CFP->isZero())
8274       return N1;
8275
8276     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8277     if (N0.getOpcode() == ISD::FMUL) {
8278       // Fold scalars or any vector constants (not just splats).
8279       // This fold is done in general by InstCombine, but extra fmul insts
8280       // may have been generated during lowering.
8281       SDValue N00 = N0.getOperand(0);
8282       SDValue N01 = N0.getOperand(1);
8283       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8284       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8285       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8286
8287       // Check 1: Make sure that the first operand of the inner multiply is NOT
8288       // a constant. Otherwise, we may induce infinite looping.
8289       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8290         // Check 2: Make sure that the second operand of the inner multiply and
8291         // the second operand of the outer multiply are constants.
8292         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8293             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8294           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1, Flags);
8295           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts, Flags);
8296         }
8297       }
8298     }
8299
8300     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8301     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8302     // during an early run of DAGCombiner can prevent folding with fmuls
8303     // inserted during lowering.
8304     if (N0.getOpcode() == ISD::FADD &&
8305         (N0.getOperand(0) == N0.getOperand(1)) &&
8306         N0.hasOneUse()) {
8307       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8308       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1, Flags);
8309       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts, Flags);
8310     }
8311   }
8312
8313   // fold (fmul X, 2.0) -> (fadd X, X)
8314   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8315     return DAG.getNode(ISD::FADD, DL, VT, N0, N0, Flags);
8316
8317   // fold (fmul X, -1.0) -> (fneg X)
8318   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8319     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8320       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8321
8322   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8323   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8324     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8325       // Both can be negated for free, check to see if at least one is cheaper
8326       // negated.
8327       if (LHSNeg == 2 || RHSNeg == 2)
8328         return DAG.getNode(ISD::FMUL, DL, VT,
8329                            GetNegatedExpression(N0, DAG, LegalOperations),
8330                            GetNegatedExpression(N1, DAG, LegalOperations),
8331                            Flags);
8332     }
8333   }
8334
8335   // FMUL -> FMA combines:
8336   if (SDValue Fused = visitFMULForFMACombine(N)) {
8337     AddToWorklist(Fused.getNode());
8338     return Fused;
8339   }
8340
8341   return SDValue();
8342 }
8343
8344 SDValue DAGCombiner::visitFMA(SDNode *N) {
8345   SDValue N0 = N->getOperand(0);
8346   SDValue N1 = N->getOperand(1);
8347   SDValue N2 = N->getOperand(2);
8348   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8349   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8350   EVT VT = N->getValueType(0);
8351   SDLoc dl(N);
8352   const TargetOptions &Options = DAG.getTarget().Options;
8353
8354   // Constant fold FMA.
8355   if (isa<ConstantFPSDNode>(N0) &&
8356       isa<ConstantFPSDNode>(N1) &&
8357       isa<ConstantFPSDNode>(N2)) {
8358     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8359   }
8360
8361   if (Options.UnsafeFPMath) {
8362     if (N0CFP && N0CFP->isZero())
8363       return N2;
8364     if (N1CFP && N1CFP->isZero())
8365       return N2;
8366   }
8367   // TODO: The FMA node should have flags that propagate to these nodes.
8368   if (N0CFP && N0CFP->isExactlyValue(1.0))
8369     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8370   if (N1CFP && N1CFP->isExactlyValue(1.0))
8371     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8372
8373   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8374   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8375      !isConstantFPBuildVectorOrConstantFP(N1))
8376     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8377
8378   // TODO: FMA nodes should have flags that propagate to the created nodes.
8379   // For now, create a Flags object for use with all unsafe math transforms.
8380   SDNodeFlags Flags;
8381   Flags.setUnsafeAlgebra(true);
8382
8383   if (Options.UnsafeFPMath) {
8384     // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8385     if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
8386         isConstantFPBuildVectorOrConstantFP(N1) &&
8387         isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
8388       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8389                          DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1),
8390                                      &Flags), &Flags);
8391     }
8392
8393     // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8394     if (N0.getOpcode() == ISD::FMUL &&
8395         isConstantFPBuildVectorOrConstantFP(N1) &&
8396         isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
8397       return DAG.getNode(ISD::FMA, dl, VT,
8398                          N0.getOperand(0),
8399                          DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1),
8400                                      &Flags),
8401                          N2);
8402     }
8403   }
8404
8405   // (fma x, 1, y) -> (fadd x, y)
8406   // (fma x, -1, y) -> (fadd (fneg x), y)
8407   if (N1CFP) {
8408     if (N1CFP->isExactlyValue(1.0))
8409       // TODO: The FMA node should have flags that propagate to this node.
8410       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8411
8412     if (N1CFP->isExactlyValue(-1.0) &&
8413         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8414       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8415       AddToWorklist(RHSNeg.getNode());
8416       // TODO: The FMA node should have flags that propagate to this node.
8417       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8418     }
8419   }
8420
8421   if (Options.UnsafeFPMath) {
8422     // (fma x, c, x) -> (fmul x, (c+1))
8423     if (N1CFP && N0 == N2) {
8424     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8425                          DAG.getNode(ISD::FADD, dl, VT,
8426                                      N1, DAG.getConstantFP(1.0, dl, VT),
8427                                      &Flags), &Flags);
8428     }
8429
8430     // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8431     if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
8432       return DAG.getNode(ISD::FMUL, dl, VT, N0,
8433                          DAG.getNode(ISD::FADD, dl, VT,
8434                                      N1, DAG.getConstantFP(-1.0, dl, VT),
8435                                      &Flags), &Flags);
8436     }
8437   }
8438
8439   return SDValue();
8440 }
8441
8442 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8443 // reciprocal.
8444 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8445 // Notice that this is not always beneficial. One reason is different target
8446 // may have different costs for FDIV and FMUL, so sometimes the cost of two
8447 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8448 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8449 SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
8450   if (!DAG.getTarget().Options.UnsafeFPMath)
8451     return SDValue();
8452
8453   // Skip if current node is a reciprocal.
8454   SDValue N0 = N->getOperand(0);
8455   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8456   if (N0CFP && N0CFP->isExactlyValue(1.0))
8457     return SDValue();
8458
8459   // Exit early if the target does not want this transform or if there can't
8460   // possibly be enough uses of the divisor to make the transform worthwhile.
8461   SDValue N1 = N->getOperand(1);
8462   unsigned MinUses = TLI.combineRepeatedFPDivisors();
8463   if (!MinUses || N1->use_size() < MinUses)
8464     return SDValue();
8465
8466   // Find all FDIV users of the same divisor.
8467   // Use a set because duplicates may be present in the user list.
8468   SetVector<SDNode *> Users;
8469   for (auto *U : N1->uses())
8470     if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1)
8471       Users.insert(U);
8472
8473   // Now that we have the actual number of divisor uses, make sure it meets
8474   // the minimum threshold specified by the target.
8475   if (Users.size() < MinUses)
8476     return SDValue();
8477
8478   EVT VT = N->getValueType(0);
8479   SDLoc DL(N);
8480   SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
8481   const SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8482   SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
8483
8484   // Dividend / Divisor -> Dividend * Reciprocal
8485   for (auto *U : Users) {
8486     SDValue Dividend = U->getOperand(0);
8487     if (Dividend != FPOne) {
8488       SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
8489                                     Reciprocal, Flags);
8490       CombineTo(U, NewNode);
8491     } else if (U != Reciprocal.getNode()) {
8492       // In the absence of fast-math-flags, this user node is always the
8493       // same node as Reciprocal, but with FMF they may be different nodes.
8494       CombineTo(U, Reciprocal);
8495     }
8496   }
8497   return SDValue(N, 0);  // N was replaced.
8498 }
8499
8500 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8501   SDValue N0 = N->getOperand(0);
8502   SDValue N1 = N->getOperand(1);
8503   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8504   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8505   EVT VT = N->getValueType(0);
8506   SDLoc DL(N);
8507   const TargetOptions &Options = DAG.getTarget().Options;
8508   SDNodeFlags *Flags = &cast<BinaryWithFlagsSDNode>(N)->Flags;
8509
8510   // fold vector ops
8511   if (VT.isVector())
8512     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8513       return FoldedVOp;
8514
8515   // fold (fdiv c1, c2) -> c1/c2
8516   if (N0CFP && N1CFP)
8517     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1, Flags);
8518
8519   if (Options.UnsafeFPMath) {
8520     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8521     if (N1CFP) {
8522       // Compute the reciprocal 1.0 / c2.
8523       APFloat N1APF = N1CFP->getValueAPF();
8524       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8525       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8526       // Only do the transform if the reciprocal is a legal fp immediate that
8527       // isn't too nasty (eg NaN, denormal, ...).
8528       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8529           (!LegalOperations ||
8530            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8531            // backend)... we should handle this gracefully after Legalize.
8532            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8533            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8534            TLI.isFPImmLegal(Recip, VT)))
8535         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8536                            DAG.getConstantFP(Recip, DL, VT), Flags);
8537     }
8538
8539     // If this FDIV is part of a reciprocal square root, it may be folded
8540     // into a target-specific square root estimate instruction.
8541     if (N1.getOpcode() == ISD::FSQRT) {
8542       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0), Flags)) {
8543         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8544       }
8545     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8546                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8547       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8548                                           Flags)) {
8549         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8550         AddToWorklist(RV.getNode());
8551         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8552       }
8553     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8554                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8555       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0),
8556                                           Flags)) {
8557         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8558         AddToWorklist(RV.getNode());
8559         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8560       }
8561     } else if (N1.getOpcode() == ISD::FMUL) {
8562       // Look through an FMUL. Even though this won't remove the FDIV directly,
8563       // it's still worthwhile to get rid of the FSQRT if possible.
8564       SDValue SqrtOp;
8565       SDValue OtherOp;
8566       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8567         SqrtOp = N1.getOperand(0);
8568         OtherOp = N1.getOperand(1);
8569       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8570         SqrtOp = N1.getOperand(1);
8571         OtherOp = N1.getOperand(0);
8572       }
8573       if (SqrtOp.getNode()) {
8574         // We found a FSQRT, so try to make this fold:
8575         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8576         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0), Flags)) {
8577           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp, Flags);
8578           AddToWorklist(RV.getNode());
8579           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8580         }
8581       }
8582     }
8583
8584     // Fold into a reciprocal estimate and multiply instead of a real divide.
8585     if (SDValue RV = BuildReciprocalEstimate(N1, Flags)) {
8586       AddToWorklist(RV.getNode());
8587       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV, Flags);
8588     }
8589   }
8590
8591   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8592   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8593     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8594       // Both can be negated for free, check to see if at least one is cheaper
8595       // negated.
8596       if (LHSNeg == 2 || RHSNeg == 2)
8597         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8598                            GetNegatedExpression(N0, DAG, LegalOperations),
8599                            GetNegatedExpression(N1, DAG, LegalOperations),
8600                            Flags);
8601     }
8602   }
8603
8604   if (SDValue CombineRepeatedDivisors = combineRepeatedFPDivisors(N))
8605     return CombineRepeatedDivisors;
8606
8607   return SDValue();
8608 }
8609
8610 SDValue DAGCombiner::visitFREM(SDNode *N) {
8611   SDValue N0 = N->getOperand(0);
8612   SDValue N1 = N->getOperand(1);
8613   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8614   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8615   EVT VT = N->getValueType(0);
8616
8617   // fold (frem c1, c2) -> fmod(c1,c2)
8618   if (N0CFP && N1CFP)
8619     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1,
8620                        &cast<BinaryWithFlagsSDNode>(N)->Flags);
8621
8622   return SDValue();
8623 }
8624
8625 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8626   if (!DAG.getTarget().Options.UnsafeFPMath || TLI.isFsqrtCheap())
8627     return SDValue();
8628
8629   // TODO: FSQRT nodes should have flags that propagate to the created nodes.
8630   // For now, create a Flags object for use with all unsafe math transforms.
8631   SDNodeFlags Flags;
8632   Flags.setUnsafeAlgebra(true);
8633
8634   // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8635   SDValue RV = BuildRsqrtEstimate(N->getOperand(0), &Flags);
8636   if (!RV)
8637     return SDValue();
8638
8639   EVT VT = RV.getValueType();
8640   SDLoc DL(N);
8641   RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV, &Flags);
8642   AddToWorklist(RV.getNode());
8643
8644   // Unfortunately, RV is now NaN if the input was exactly 0.
8645   // Select out this case and force the answer to 0.
8646   SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8647   EVT CCVT = getSetCCResultType(VT);
8648   SDValue ZeroCmp = DAG.getSetCC(DL, CCVT, N->getOperand(0), Zero, ISD::SETEQ);
8649   AddToWorklist(ZeroCmp.getNode());
8650   AddToWorklist(RV.getNode());
8651
8652   return DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
8653                      ZeroCmp, Zero, RV);
8654 }
8655
8656 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8657   SDValue N0 = N->getOperand(0);
8658   SDValue N1 = N->getOperand(1);
8659   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8660   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8661   EVT VT = N->getValueType(0);
8662
8663   if (N0CFP && N1CFP)  // Constant fold
8664     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8665
8666   if (N1CFP) {
8667     const APFloat& V = N1CFP->getValueAPF();
8668     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8669     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8670     if (!V.isNegative()) {
8671       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8672         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8673     } else {
8674       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8675         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8676                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8677     }
8678   }
8679
8680   // copysign(fabs(x), y) -> copysign(x, y)
8681   // copysign(fneg(x), y) -> copysign(x, y)
8682   // copysign(copysign(x,z), y) -> copysign(x, y)
8683   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8684       N0.getOpcode() == ISD::FCOPYSIGN)
8685     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8686                        N0.getOperand(0), N1);
8687
8688   // copysign(x, abs(y)) -> abs(x)
8689   if (N1.getOpcode() == ISD::FABS)
8690     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8691
8692   // copysign(x, copysign(y,z)) -> copysign(x, z)
8693   if (N1.getOpcode() == ISD::FCOPYSIGN)
8694     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8695                        N0, N1.getOperand(1));
8696
8697   // copysign(x, fp_extend(y)) -> copysign(x, y)
8698   // copysign(x, fp_round(y)) -> copysign(x, y)
8699   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8700     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8701                        N0, N1.getOperand(0));
8702
8703   return SDValue();
8704 }
8705
8706 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8707   SDValue N0 = N->getOperand(0);
8708   EVT VT = N->getValueType(0);
8709   EVT OpVT = N0.getValueType();
8710
8711   // fold (sint_to_fp c1) -> c1fp
8712   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8713       // ...but only if the target supports immediate floating-point values
8714       (!LegalOperations ||
8715        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8716     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8717
8718   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8719   // but UINT_TO_FP is legal on this target, try to convert.
8720   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8721       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8722     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8723     if (DAG.SignBitIsZero(N0))
8724       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8725   }
8726
8727   // The next optimizations are desirable only if SELECT_CC can be lowered.
8728   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8729     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8730     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8731         !VT.isVector() &&
8732         (!LegalOperations ||
8733          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8734       SDLoc DL(N);
8735       SDValue Ops[] =
8736         { N0.getOperand(0), N0.getOperand(1),
8737           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8738           N0.getOperand(2) };
8739       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8740     }
8741
8742     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8743     //      (select_cc x, y, 1.0, 0.0,, cc)
8744     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8745         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8746         (!LegalOperations ||
8747          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8748       SDLoc DL(N);
8749       SDValue Ops[] =
8750         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8751           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8752           N0.getOperand(0).getOperand(2) };
8753       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8754     }
8755   }
8756
8757   return SDValue();
8758 }
8759
8760 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8761   SDValue N0 = N->getOperand(0);
8762   EVT VT = N->getValueType(0);
8763   EVT OpVT = N0.getValueType();
8764
8765   // fold (uint_to_fp c1) -> c1fp
8766   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8767       // ...but only if the target supports immediate floating-point values
8768       (!LegalOperations ||
8769        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8770     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8771
8772   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8773   // but SINT_TO_FP is legal on this target, try to convert.
8774   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8775       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8776     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8777     if (DAG.SignBitIsZero(N0))
8778       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8779   }
8780
8781   // The next optimizations are desirable only if SELECT_CC can be lowered.
8782   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8783     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8784
8785     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8786         (!LegalOperations ||
8787          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8788       SDLoc DL(N);
8789       SDValue Ops[] =
8790         { N0.getOperand(0), N0.getOperand(1),
8791           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8792           N0.getOperand(2) };
8793       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8794     }
8795   }
8796
8797   return SDValue();
8798 }
8799
8800 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8801 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8802   SDValue N0 = N->getOperand(0);
8803   EVT VT = N->getValueType(0);
8804
8805   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8806     return SDValue();
8807
8808   SDValue Src = N0.getOperand(0);
8809   EVT SrcVT = Src.getValueType();
8810   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8811   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8812
8813   // We can safely assume the conversion won't overflow the output range,
8814   // because (for example) (uint8_t)18293.f is undefined behavior.
8815
8816   // Since we can assume the conversion won't overflow, our decision as to
8817   // whether the input will fit in the float should depend on the minimum
8818   // of the input range and output range.
8819
8820   // This means this is also safe for a signed input and unsigned output, since
8821   // a negative input would lead to undefined behavior.
8822   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8823   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8824   unsigned ActualSize = std::min(InputSize, OutputSize);
8825   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8826
8827   // We can only fold away the float conversion if the input range can be
8828   // represented exactly in the float range.
8829   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8830     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8831       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8832                                                        : ISD::ZERO_EXTEND;
8833       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8834     }
8835     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8836       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8837     if (SrcVT == VT)
8838       return Src;
8839     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8840   }
8841   return SDValue();
8842 }
8843
8844 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8845   SDValue N0 = N->getOperand(0);
8846   EVT VT = N->getValueType(0);
8847
8848   // fold (fp_to_sint c1fp) -> c1
8849   if (isConstantFPBuildVectorOrConstantFP(N0))
8850     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8851
8852   return FoldIntToFPToInt(N, DAG);
8853 }
8854
8855 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8856   SDValue N0 = N->getOperand(0);
8857   EVT VT = N->getValueType(0);
8858
8859   // fold (fp_to_uint c1fp) -> c1
8860   if (isConstantFPBuildVectorOrConstantFP(N0))
8861     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8862
8863   return FoldIntToFPToInt(N, DAG);
8864 }
8865
8866 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8867   SDValue N0 = N->getOperand(0);
8868   SDValue N1 = N->getOperand(1);
8869   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8870   EVT VT = N->getValueType(0);
8871
8872   // fold (fp_round c1fp) -> c1fp
8873   if (N0CFP)
8874     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8875
8876   // fold (fp_round (fp_extend x)) -> x
8877   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8878     return N0.getOperand(0);
8879
8880   // fold (fp_round (fp_round x)) -> (fp_round x)
8881   if (N0.getOpcode() == ISD::FP_ROUND) {
8882     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8883     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8884     // If the first fp_round isn't a value preserving truncation, it might
8885     // introduce a tie in the second fp_round, that wouldn't occur in the
8886     // single-step fp_round we want to fold to.
8887     // In other words, double rounding isn't the same as rounding.
8888     // Also, this is a value preserving truncation iff both fp_round's are.
8889     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8890       SDLoc DL(N);
8891       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8892                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8893     }
8894   }
8895
8896   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8897   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8898     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8899                               N0.getOperand(0), N1);
8900     AddToWorklist(Tmp.getNode());
8901     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8902                        Tmp, N0.getOperand(1));
8903   }
8904
8905   return SDValue();
8906 }
8907
8908 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8909   SDValue N0 = N->getOperand(0);
8910   EVT VT = N->getValueType(0);
8911   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8912   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8913
8914   // fold (fp_round_inreg c1fp) -> c1fp
8915   if (N0CFP && isTypeLegal(EVT)) {
8916     SDLoc DL(N);
8917     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8918     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8919   }
8920
8921   return SDValue();
8922 }
8923
8924 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8925   SDValue N0 = N->getOperand(0);
8926   EVT VT = N->getValueType(0);
8927
8928   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8929   if (N->hasOneUse() &&
8930       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8931     return SDValue();
8932
8933   // fold (fp_extend c1fp) -> c1fp
8934   if (isConstantFPBuildVectorOrConstantFP(N0))
8935     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8936
8937   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8938   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8939       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8940     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8941
8942   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8943   // value of X.
8944   if (N0.getOpcode() == ISD::FP_ROUND
8945       && N0.getNode()->getConstantOperandVal(1) == 1) {
8946     SDValue In = N0.getOperand(0);
8947     if (In.getValueType() == VT) return In;
8948     if (VT.bitsLT(In.getValueType()))
8949       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8950                          In, N0.getOperand(1));
8951     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8952   }
8953
8954   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8955   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8956        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8957     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8958     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8959                                      LN0->getChain(),
8960                                      LN0->getBasePtr(), N0.getValueType(),
8961                                      LN0->getMemOperand());
8962     CombineTo(N, ExtLoad);
8963     CombineTo(N0.getNode(),
8964               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8965                           N0.getValueType(), ExtLoad,
8966                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8967               ExtLoad.getValue(1));
8968     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8969   }
8970
8971   return SDValue();
8972 }
8973
8974 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8975   SDValue N0 = N->getOperand(0);
8976   EVT VT = N->getValueType(0);
8977
8978   // fold (fceil c1) -> fceil(c1)
8979   if (isConstantFPBuildVectorOrConstantFP(N0))
8980     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8981
8982   return SDValue();
8983 }
8984
8985 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8986   SDValue N0 = N->getOperand(0);
8987   EVT VT = N->getValueType(0);
8988
8989   // fold (ftrunc c1) -> ftrunc(c1)
8990   if (isConstantFPBuildVectorOrConstantFP(N0))
8991     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8992
8993   return SDValue();
8994 }
8995
8996 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8997   SDValue N0 = N->getOperand(0);
8998   EVT VT = N->getValueType(0);
8999
9000   // fold (ffloor c1) -> ffloor(c1)
9001   if (isConstantFPBuildVectorOrConstantFP(N0))
9002     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
9003
9004   return SDValue();
9005 }
9006
9007 // FIXME: FNEG and FABS have a lot in common; refactor.
9008 SDValue DAGCombiner::visitFNEG(SDNode *N) {
9009   SDValue N0 = N->getOperand(0);
9010   EVT VT = N->getValueType(0);
9011
9012   // Constant fold FNEG.
9013   if (isConstantFPBuildVectorOrConstantFP(N0))
9014     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
9015
9016   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
9017                          &DAG.getTarget().Options))
9018     return GetNegatedExpression(N0, DAG, LegalOperations);
9019
9020   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
9021   // constant pool values.
9022   if (!TLI.isFNegFree(VT) &&
9023       N0.getOpcode() == ISD::BITCAST &&
9024       N0.getNode()->hasOneUse()) {
9025     SDValue Int = N0.getOperand(0);
9026     EVT IntVT = Int.getValueType();
9027     if (IntVT.isInteger() && !IntVT.isVector()) {
9028       APInt SignMask;
9029       if (N0.getValueType().isVector()) {
9030         // For a vector, get a mask such as 0x80... per scalar element
9031         // and splat it.
9032         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9033         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9034       } else {
9035         // For a scalar, just generate 0x80...
9036         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
9037       }
9038       SDLoc DL0(N0);
9039       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
9040                         DAG.getConstant(SignMask, DL0, IntVT));
9041       AddToWorklist(Int.getNode());
9042       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
9043     }
9044   }
9045
9046   // (fneg (fmul c, x)) -> (fmul -c, x)
9047   if (N0.getOpcode() == ISD::FMUL &&
9048       (N0.getNode()->hasOneUse() || !TLI.isFNegFree(VT))) {
9049     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9050     if (CFP1) {
9051       APFloat CVal = CFP1->getValueAPF();
9052       CVal.changeSign();
9053       if (Level >= AfterLegalizeDAG &&
9054           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
9055            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
9056         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
9057                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
9058                                        N0.getOperand(1)),
9059                            &cast<BinaryWithFlagsSDNode>(N0)->Flags);
9060     }
9061   }
9062
9063   return SDValue();
9064 }
9065
9066 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
9067   SDValue N0 = N->getOperand(0);
9068   SDValue N1 = N->getOperand(1);
9069   EVT VT = N->getValueType(0);
9070   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9071   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9072
9073   if (N0CFP && N1CFP) {
9074     const APFloat &C0 = N0CFP->getValueAPF();
9075     const APFloat &C1 = N1CFP->getValueAPF();
9076     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), VT);
9077   }
9078
9079   // Canonicalize to constant on RHS.
9080   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9081      !isConstantFPBuildVectorOrConstantFP(N1))
9082     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
9083
9084   return SDValue();
9085 }
9086
9087 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
9088   SDValue N0 = N->getOperand(0);
9089   SDValue N1 = N->getOperand(1);
9090   EVT VT = N->getValueType(0);
9091   const ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
9092   const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
9093
9094   if (N0CFP && N1CFP) {
9095     const APFloat &C0 = N0CFP->getValueAPF();
9096     const APFloat &C1 = N1CFP->getValueAPF();
9097     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), VT);
9098   }
9099
9100   // Canonicalize to constant on RHS.
9101   if (isConstantFPBuildVectorOrConstantFP(N0) &&
9102      !isConstantFPBuildVectorOrConstantFP(N1))
9103     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
9104
9105   return SDValue();
9106 }
9107
9108 SDValue DAGCombiner::visitFABS(SDNode *N) {
9109   SDValue N0 = N->getOperand(0);
9110   EVT VT = N->getValueType(0);
9111
9112   // fold (fabs c1) -> fabs(c1)
9113   if (isConstantFPBuildVectorOrConstantFP(N0))
9114     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
9115
9116   // fold (fabs (fabs x)) -> (fabs x)
9117   if (N0.getOpcode() == ISD::FABS)
9118     return N->getOperand(0);
9119
9120   // fold (fabs (fneg x)) -> (fabs x)
9121   // fold (fabs (fcopysign x, y)) -> (fabs x)
9122   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
9123     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
9124
9125   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
9126   // constant pool values.
9127   if (!TLI.isFAbsFree(VT) &&
9128       N0.getOpcode() == ISD::BITCAST &&
9129       N0.getNode()->hasOneUse()) {
9130     SDValue Int = N0.getOperand(0);
9131     EVT IntVT = Int.getValueType();
9132     if (IntVT.isInteger() && !IntVT.isVector()) {
9133       APInt SignMask;
9134       if (N0.getValueType().isVector()) {
9135         // For a vector, get a mask such as 0x7f... per scalar element
9136         // and splat it.
9137         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
9138         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
9139       } else {
9140         // For a scalar, just generate 0x7f...
9141         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
9142       }
9143       SDLoc DL(N0);
9144       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
9145                         DAG.getConstant(SignMask, DL, IntVT));
9146       AddToWorklist(Int.getNode());
9147       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
9148     }
9149   }
9150
9151   return SDValue();
9152 }
9153
9154 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
9155   SDValue Chain = N->getOperand(0);
9156   SDValue N1 = N->getOperand(1);
9157   SDValue N2 = N->getOperand(2);
9158
9159   // If N is a constant we could fold this into a fallthrough or unconditional
9160   // branch. However that doesn't happen very often in normal code, because
9161   // Instcombine/SimplifyCFG should have handled the available opportunities.
9162   // If we did this folding here, it would be necessary to update the
9163   // MachineBasicBlock CFG, which is awkward.
9164
9165   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
9166   // on the target.
9167   if (N1.getOpcode() == ISD::SETCC &&
9168       TLI.isOperationLegalOrCustom(ISD::BR_CC,
9169                                    N1.getOperand(0).getValueType())) {
9170     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9171                        Chain, N1.getOperand(2),
9172                        N1.getOperand(0), N1.getOperand(1), N2);
9173   }
9174
9175   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
9176       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
9177        (N1.getOperand(0).hasOneUse() &&
9178         N1.getOperand(0).getOpcode() == ISD::SRL))) {
9179     SDNode *Trunc = nullptr;
9180     if (N1.getOpcode() == ISD::TRUNCATE) {
9181       // Look pass the truncate.
9182       Trunc = N1.getNode();
9183       N1 = N1.getOperand(0);
9184     }
9185
9186     // Match this pattern so that we can generate simpler code:
9187     //
9188     //   %a = ...
9189     //   %b = and i32 %a, 2
9190     //   %c = srl i32 %b, 1
9191     //   brcond i32 %c ...
9192     //
9193     // into
9194     //
9195     //   %a = ...
9196     //   %b = and i32 %a, 2
9197     //   %c = setcc eq %b, 0
9198     //   brcond %c ...
9199     //
9200     // This applies only when the AND constant value has one bit set and the
9201     // SRL constant is equal to the log2 of the AND constant. The back-end is
9202     // smart enough to convert the result into a TEST/JMP sequence.
9203     SDValue Op0 = N1.getOperand(0);
9204     SDValue Op1 = N1.getOperand(1);
9205
9206     if (Op0.getOpcode() == ISD::AND &&
9207         Op1.getOpcode() == ISD::Constant) {
9208       SDValue AndOp1 = Op0.getOperand(1);
9209
9210       if (AndOp1.getOpcode() == ISD::Constant) {
9211         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
9212
9213         if (AndConst.isPowerOf2() &&
9214             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
9215           SDLoc DL(N);
9216           SDValue SetCC =
9217             DAG.getSetCC(DL,
9218                          getSetCCResultType(Op0.getValueType()),
9219                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
9220                          ISD::SETNE);
9221
9222           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
9223                                           MVT::Other, Chain, SetCC, N2);
9224           // Don't add the new BRCond into the worklist or else SimplifySelectCC
9225           // will convert it back to (X & C1) >> C2.
9226           CombineTo(N, NewBRCond, false);
9227           // Truncate is dead.
9228           if (Trunc)
9229             deleteAndRecombine(Trunc);
9230           // Replace the uses of SRL with SETCC
9231           WorklistRemover DeadNodes(*this);
9232           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9233           deleteAndRecombine(N1.getNode());
9234           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9235         }
9236       }
9237     }
9238
9239     if (Trunc)
9240       // Restore N1 if the above transformation doesn't match.
9241       N1 = N->getOperand(1);
9242   }
9243
9244   // Transform br(xor(x, y)) -> br(x != y)
9245   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
9246   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
9247     SDNode *TheXor = N1.getNode();
9248     SDValue Op0 = TheXor->getOperand(0);
9249     SDValue Op1 = TheXor->getOperand(1);
9250     if (Op0.getOpcode() == Op1.getOpcode()) {
9251       // Avoid missing important xor optimizations.
9252       if (SDValue Tmp = visitXOR(TheXor)) {
9253         if (Tmp.getNode() != TheXor) {
9254           DEBUG(dbgs() << "\nReplacing.8 ";
9255                 TheXor->dump(&DAG);
9256                 dbgs() << "\nWith: ";
9257                 Tmp.getNode()->dump(&DAG);
9258                 dbgs() << '\n');
9259           WorklistRemover DeadNodes(*this);
9260           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
9261           deleteAndRecombine(TheXor);
9262           return DAG.getNode(ISD::BRCOND, SDLoc(N),
9263                              MVT::Other, Chain, Tmp, N2);
9264         }
9265
9266         // visitXOR has changed XOR's operands or replaced the XOR completely,
9267         // bail out.
9268         return SDValue(N, 0);
9269       }
9270     }
9271
9272     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
9273       bool Equal = false;
9274       if (isOneConstant(Op0) && Op0.hasOneUse() &&
9275           Op0.getOpcode() == ISD::XOR) {
9276         TheXor = Op0.getNode();
9277         Equal = true;
9278       }
9279
9280       EVT SetCCVT = N1.getValueType();
9281       if (LegalTypes)
9282         SetCCVT = getSetCCResultType(SetCCVT);
9283       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
9284                                    SetCCVT,
9285                                    Op0, Op1,
9286                                    Equal ? ISD::SETEQ : ISD::SETNE);
9287       // Replace the uses of XOR with SETCC
9288       WorklistRemover DeadNodes(*this);
9289       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
9290       deleteAndRecombine(N1.getNode());
9291       return DAG.getNode(ISD::BRCOND, SDLoc(N),
9292                          MVT::Other, Chain, SetCC, N2);
9293     }
9294   }
9295
9296   return SDValue();
9297 }
9298
9299 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9300 //
9301 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9302   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9303   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9304
9305   // If N is a constant we could fold this into a fallthrough or unconditional
9306   // branch. However that doesn't happen very often in normal code, because
9307   // Instcombine/SimplifyCFG should have handled the available opportunities.
9308   // If we did this folding here, it would be necessary to update the
9309   // MachineBasicBlock CFG, which is awkward.
9310
9311   // Use SimplifySetCC to simplify SETCC's.
9312   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9313                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9314                                false);
9315   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9316
9317   // fold to a simpler setcc
9318   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9319     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9320                        N->getOperand(0), Simp.getOperand(2),
9321                        Simp.getOperand(0), Simp.getOperand(1),
9322                        N->getOperand(4));
9323
9324   return SDValue();
9325 }
9326
9327 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9328 /// and that N may be folded in the load / store addressing mode.
9329 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9330                                     SelectionDAG &DAG,
9331                                     const TargetLowering &TLI) {
9332   EVT VT;
9333   unsigned AS;
9334
9335   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9336     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9337       return false;
9338     VT = LD->getMemoryVT();
9339     AS = LD->getAddressSpace();
9340   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9341     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9342       return false;
9343     VT = ST->getMemoryVT();
9344     AS = ST->getAddressSpace();
9345   } else
9346     return false;
9347
9348   TargetLowering::AddrMode AM;
9349   if (N->getOpcode() == ISD::ADD) {
9350     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9351     if (Offset)
9352       // [reg +/- imm]
9353       AM.BaseOffs = Offset->getSExtValue();
9354     else
9355       // [reg +/- reg]
9356       AM.Scale = 1;
9357   } else if (N->getOpcode() == ISD::SUB) {
9358     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9359     if (Offset)
9360       // [reg +/- imm]
9361       AM.BaseOffs = -Offset->getSExtValue();
9362     else
9363       // [reg +/- reg]
9364       AM.Scale = 1;
9365   } else
9366     return false;
9367
9368   return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
9369                                    VT.getTypeForEVT(*DAG.getContext()), AS);
9370 }
9371
9372 /// Try turning a load/store into a pre-indexed load/store when the base
9373 /// pointer is an add or subtract and it has other uses besides the load/store.
9374 /// After the transformation, the new indexed load/store has effectively folded
9375 /// the add/subtract in and all of its other uses are redirected to the
9376 /// new load/store.
9377 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9378   if (Level < AfterLegalizeDAG)
9379     return false;
9380
9381   bool isLoad = true;
9382   SDValue Ptr;
9383   EVT VT;
9384   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9385     if (LD->isIndexed())
9386       return false;
9387     VT = LD->getMemoryVT();
9388     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9389         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9390       return false;
9391     Ptr = LD->getBasePtr();
9392   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9393     if (ST->isIndexed())
9394       return false;
9395     VT = ST->getMemoryVT();
9396     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9397         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9398       return false;
9399     Ptr = ST->getBasePtr();
9400     isLoad = false;
9401   } else {
9402     return false;
9403   }
9404
9405   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9406   // out.  There is no reason to make this a preinc/predec.
9407   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9408       Ptr.getNode()->hasOneUse())
9409     return false;
9410
9411   // Ask the target to do addressing mode selection.
9412   SDValue BasePtr;
9413   SDValue Offset;
9414   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9415   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9416     return false;
9417
9418   // Backends without true r+i pre-indexed forms may need to pass a
9419   // constant base with a variable offset so that constant coercion
9420   // will work with the patterns in canonical form.
9421   bool Swapped = false;
9422   if (isa<ConstantSDNode>(BasePtr)) {
9423     std::swap(BasePtr, Offset);
9424     Swapped = true;
9425   }
9426
9427   // Don't create a indexed load / store with zero offset.
9428   if (isNullConstant(Offset))
9429     return false;
9430
9431   // Try turning it into a pre-indexed load / store except when:
9432   // 1) The new base ptr is a frame index.
9433   // 2) If N is a store and the new base ptr is either the same as or is a
9434   //    predecessor of the value being stored.
9435   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9436   //    that would create a cycle.
9437   // 4) All uses are load / store ops that use it as old base ptr.
9438
9439   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9440   // (plus the implicit offset) to a register to preinc anyway.
9441   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9442     return false;
9443
9444   // Check #2.
9445   if (!isLoad) {
9446     SDValue Val = cast<StoreSDNode>(N)->getValue();
9447     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9448       return false;
9449   }
9450
9451   // If the offset is a constant, there may be other adds of constants that
9452   // can be folded with this one. We should do this to avoid having to keep
9453   // a copy of the original base pointer.
9454   SmallVector<SDNode *, 16> OtherUses;
9455   if (isa<ConstantSDNode>(Offset))
9456     for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
9457                               UE = BasePtr.getNode()->use_end();
9458          UI != UE; ++UI) {
9459       SDUse &Use = UI.getUse();
9460       // Skip the use that is Ptr and uses of other results from BasePtr's
9461       // node (important for nodes that return multiple results).
9462       if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
9463         continue;
9464
9465       if (Use.getUser()->isPredecessorOf(N))
9466         continue;
9467
9468       if (Use.getUser()->getOpcode() != ISD::ADD &&
9469           Use.getUser()->getOpcode() != ISD::SUB) {
9470         OtherUses.clear();
9471         break;
9472       }
9473
9474       SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
9475       if (!isa<ConstantSDNode>(Op1)) {
9476         OtherUses.clear();
9477         break;
9478       }
9479
9480       // FIXME: In some cases, we can be smarter about this.
9481       if (Op1.getValueType() != Offset.getValueType()) {
9482         OtherUses.clear();
9483         break;
9484       }
9485
9486       OtherUses.push_back(Use.getUser());
9487     }
9488
9489   if (Swapped)
9490     std::swap(BasePtr, Offset);
9491
9492   // Now check for #3 and #4.
9493   bool RealUse = false;
9494
9495   // Caches for hasPredecessorHelper
9496   SmallPtrSet<const SDNode *, 32> Visited;
9497   SmallVector<const SDNode *, 16> Worklist;
9498
9499   for (SDNode *Use : Ptr.getNode()->uses()) {
9500     if (Use == N)
9501       continue;
9502     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9503       return false;
9504
9505     // If Ptr may be folded in addressing mode of other use, then it's
9506     // not profitable to do this transformation.
9507     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9508       RealUse = true;
9509   }
9510
9511   if (!RealUse)
9512     return false;
9513
9514   SDValue Result;
9515   if (isLoad)
9516     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9517                                 BasePtr, Offset, AM);
9518   else
9519     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9520                                  BasePtr, Offset, AM);
9521   ++PreIndexedNodes;
9522   ++NodesCombined;
9523   DEBUG(dbgs() << "\nReplacing.4 ";
9524         N->dump(&DAG);
9525         dbgs() << "\nWith: ";
9526         Result.getNode()->dump(&DAG);
9527         dbgs() << '\n');
9528   WorklistRemover DeadNodes(*this);
9529   if (isLoad) {
9530     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9531     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9532   } else {
9533     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9534   }
9535
9536   // Finally, since the node is now dead, remove it from the graph.
9537   deleteAndRecombine(N);
9538
9539   if (Swapped)
9540     std::swap(BasePtr, Offset);
9541
9542   // Replace other uses of BasePtr that can be updated to use Ptr
9543   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9544     unsigned OffsetIdx = 1;
9545     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9546       OffsetIdx = 0;
9547     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9548            BasePtr.getNode() && "Expected BasePtr operand");
9549
9550     // We need to replace ptr0 in the following expression:
9551     //   x0 * offset0 + y0 * ptr0 = t0
9552     // knowing that
9553     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9554     //
9555     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9556     // indexed load/store and the expresion that needs to be re-written.
9557     //
9558     // Therefore, we have:
9559     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9560
9561     ConstantSDNode *CN =
9562       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9563     int X0, X1, Y0, Y1;
9564     APInt Offset0 = CN->getAPIntValue();
9565     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9566
9567     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9568     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9569     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9570     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9571
9572     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9573
9574     APInt CNV = Offset0;
9575     if (X0 < 0) CNV = -CNV;
9576     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9577     else CNV = CNV - Offset1;
9578
9579     SDLoc DL(OtherUses[i]);
9580
9581     // We can now generate the new expression.
9582     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9583     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9584
9585     SDValue NewUse = DAG.getNode(Opcode,
9586                                  DL,
9587                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9588     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9589     deleteAndRecombine(OtherUses[i]);
9590   }
9591
9592   // Replace the uses of Ptr with uses of the updated base value.
9593   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9594   deleteAndRecombine(Ptr.getNode());
9595
9596   return true;
9597 }
9598
9599 /// Try to combine a load/store with a add/sub of the base pointer node into a
9600 /// post-indexed load/store. The transformation folded the add/subtract into the
9601 /// new indexed load/store effectively and all of its uses are redirected to the
9602 /// new load/store.
9603 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9604   if (Level < AfterLegalizeDAG)
9605     return false;
9606
9607   bool isLoad = true;
9608   SDValue Ptr;
9609   EVT VT;
9610   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9611     if (LD->isIndexed())
9612       return false;
9613     VT = LD->getMemoryVT();
9614     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9615         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9616       return false;
9617     Ptr = LD->getBasePtr();
9618   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9619     if (ST->isIndexed())
9620       return false;
9621     VT = ST->getMemoryVT();
9622     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9623         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9624       return false;
9625     Ptr = ST->getBasePtr();
9626     isLoad = false;
9627   } else {
9628     return false;
9629   }
9630
9631   if (Ptr.getNode()->hasOneUse())
9632     return false;
9633
9634   for (SDNode *Op : Ptr.getNode()->uses()) {
9635     if (Op == N ||
9636         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9637       continue;
9638
9639     SDValue BasePtr;
9640     SDValue Offset;
9641     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9642     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9643       // Don't create a indexed load / store with zero offset.
9644       if (isNullConstant(Offset))
9645         continue;
9646
9647       // Try turning it into a post-indexed load / store except when
9648       // 1) All uses are load / store ops that use it as base ptr (and
9649       //    it may be folded as addressing mmode).
9650       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9651       //    nor a successor of N. Otherwise, if Op is folded that would
9652       //    create a cycle.
9653
9654       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9655         continue;
9656
9657       // Check for #1.
9658       bool TryNext = false;
9659       for (SDNode *Use : BasePtr.getNode()->uses()) {
9660         if (Use == Ptr.getNode())
9661           continue;
9662
9663         // If all the uses are load / store addresses, then don't do the
9664         // transformation.
9665         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9666           bool RealUse = false;
9667           for (SDNode *UseUse : Use->uses()) {
9668             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9669               RealUse = true;
9670           }
9671
9672           if (!RealUse) {
9673             TryNext = true;
9674             break;
9675           }
9676         }
9677       }
9678
9679       if (TryNext)
9680         continue;
9681
9682       // Check for #2
9683       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9684         SDValue Result = isLoad
9685           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9686                                BasePtr, Offset, AM)
9687           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9688                                 BasePtr, Offset, AM);
9689         ++PostIndexedNodes;
9690         ++NodesCombined;
9691         DEBUG(dbgs() << "\nReplacing.5 ";
9692               N->dump(&DAG);
9693               dbgs() << "\nWith: ";
9694               Result.getNode()->dump(&DAG);
9695               dbgs() << '\n');
9696         WorklistRemover DeadNodes(*this);
9697         if (isLoad) {
9698           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9699           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9700         } else {
9701           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9702         }
9703
9704         // Finally, since the node is now dead, remove it from the graph.
9705         deleteAndRecombine(N);
9706
9707         // Replace the uses of Use with uses of the updated base value.
9708         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9709                                       Result.getValue(isLoad ? 1 : 0));
9710         deleteAndRecombine(Op);
9711         return true;
9712       }
9713     }
9714   }
9715
9716   return false;
9717 }
9718
9719 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9720 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9721   ISD::MemIndexedMode AM = LD->getAddressingMode();
9722   assert(AM != ISD::UNINDEXED);
9723   SDValue BP = LD->getOperand(1);
9724   SDValue Inc = LD->getOperand(2);
9725
9726   // Some backends use TargetConstants for load offsets, but don't expect
9727   // TargetConstants in general ADD nodes. We can convert these constants into
9728   // regular Constants (if the constant is not opaque).
9729   assert((Inc.getOpcode() != ISD::TargetConstant ||
9730           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9731          "Cannot split out indexing using opaque target constants");
9732   if (Inc.getOpcode() == ISD::TargetConstant) {
9733     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9734     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9735                           ConstInc->getValueType(0));
9736   }
9737
9738   unsigned Opc =
9739       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9740   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9741 }
9742
9743 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9744   LoadSDNode *LD  = cast<LoadSDNode>(N);
9745   SDValue Chain = LD->getChain();
9746   SDValue Ptr   = LD->getBasePtr();
9747
9748   // If load is not volatile and there are no uses of the loaded value (and
9749   // the updated indexed value in case of indexed loads), change uses of the
9750   // chain value into uses of the chain input (i.e. delete the dead load).
9751   if (!LD->isVolatile()) {
9752     if (N->getValueType(1) == MVT::Other) {
9753       // Unindexed loads.
9754       if (!N->hasAnyUseOfValue(0)) {
9755         // It's not safe to use the two value CombineTo variant here. e.g.
9756         // v1, chain2 = load chain1, loc
9757         // v2, chain3 = load chain2, loc
9758         // v3         = add v2, c
9759         // Now we replace use of chain2 with chain1.  This makes the second load
9760         // isomorphic to the one we are deleting, and thus makes this load live.
9761         DEBUG(dbgs() << "\nReplacing.6 ";
9762               N->dump(&DAG);
9763               dbgs() << "\nWith chain: ";
9764               Chain.getNode()->dump(&DAG);
9765               dbgs() << "\n");
9766         WorklistRemover DeadNodes(*this);
9767         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9768
9769         if (N->use_empty())
9770           deleteAndRecombine(N);
9771
9772         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9773       }
9774     } else {
9775       // Indexed loads.
9776       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9777
9778       // If this load has an opaque TargetConstant offset, then we cannot split
9779       // the indexing into an add/sub directly (that TargetConstant may not be
9780       // valid for a different type of node, and we cannot convert an opaque
9781       // target constant into a regular constant).
9782       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9783                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9784
9785       if (!N->hasAnyUseOfValue(0) &&
9786           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9787         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9788         SDValue Index;
9789         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9790           Index = SplitIndexingFromLoad(LD);
9791           // Try to fold the base pointer arithmetic into subsequent loads and
9792           // stores.
9793           AddUsersToWorklist(N);
9794         } else
9795           Index = DAG.getUNDEF(N->getValueType(1));
9796         DEBUG(dbgs() << "\nReplacing.7 ";
9797               N->dump(&DAG);
9798               dbgs() << "\nWith: ";
9799               Undef.getNode()->dump(&DAG);
9800               dbgs() << " and 2 other values\n");
9801         WorklistRemover DeadNodes(*this);
9802         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9803         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9804         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9805         deleteAndRecombine(N);
9806         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9807       }
9808     }
9809   }
9810
9811   // If this load is directly stored, replace the load value with the stored
9812   // value.
9813   // TODO: Handle store large -> read small portion.
9814   // TODO: Handle TRUNCSTORE/LOADEXT
9815   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9816     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9817       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9818       if (PrevST->getBasePtr() == Ptr &&
9819           PrevST->getValue().getValueType() == N->getValueType(0))
9820       return CombineTo(N, Chain.getOperand(1), Chain);
9821     }
9822   }
9823
9824   // Try to infer better alignment information than the load already has.
9825   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9826     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9827       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9828         SDValue NewLoad =
9829                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9830                               LD->getValueType(0),
9831                               Chain, Ptr, LD->getPointerInfo(),
9832                               LD->getMemoryVT(),
9833                               LD->isVolatile(), LD->isNonTemporal(),
9834                               LD->isInvariant(), Align, LD->getAAInfo());
9835         if (NewLoad.getNode() != N)
9836           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9837       }
9838     }
9839   }
9840
9841   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9842                                                   : DAG.getSubtarget().useAA();
9843 #ifndef NDEBUG
9844   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9845       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9846     UseAA = false;
9847 #endif
9848   if (UseAA && LD->isUnindexed()) {
9849     // Walk up chain skipping non-aliasing memory nodes.
9850     SDValue BetterChain = FindBetterChain(N, Chain);
9851
9852     // If there is a better chain.
9853     if (Chain != BetterChain) {
9854       SDValue ReplLoad;
9855
9856       // Replace the chain to void dependency.
9857       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9858         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9859                                BetterChain, Ptr, LD->getMemOperand());
9860       } else {
9861         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9862                                   LD->getValueType(0),
9863                                   BetterChain, Ptr, LD->getMemoryVT(),
9864                                   LD->getMemOperand());
9865       }
9866
9867       // Create token factor to keep old chain connected.
9868       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9869                                   MVT::Other, Chain, ReplLoad.getValue(1));
9870
9871       // Make sure the new and old chains are cleaned up.
9872       AddToWorklist(Token.getNode());
9873
9874       // Replace uses with load result and token factor. Don't add users
9875       // to work list.
9876       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9877     }
9878   }
9879
9880   // Try transforming N to an indexed load.
9881   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9882     return SDValue(N, 0);
9883
9884   // Try to slice up N to more direct loads if the slices are mapped to
9885   // different register banks or pairing can take place.
9886   if (SliceUpLoad(N))
9887     return SDValue(N, 0);
9888
9889   return SDValue();
9890 }
9891
9892 namespace {
9893 /// \brief Helper structure used to slice a load in smaller loads.
9894 /// Basically a slice is obtained from the following sequence:
9895 /// Origin = load Ty1, Base
9896 /// Shift = srl Ty1 Origin, CstTy Amount
9897 /// Inst = trunc Shift to Ty2
9898 ///
9899 /// Then, it will be rewriten into:
9900 /// Slice = load SliceTy, Base + SliceOffset
9901 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9902 ///
9903 /// SliceTy is deduced from the number of bits that are actually used to
9904 /// build Inst.
9905 struct LoadedSlice {
9906   /// \brief Helper structure used to compute the cost of a slice.
9907   struct Cost {
9908     /// Are we optimizing for code size.
9909     bool ForCodeSize;
9910     /// Various cost.
9911     unsigned Loads;
9912     unsigned Truncates;
9913     unsigned CrossRegisterBanksCopies;
9914     unsigned ZExts;
9915     unsigned Shift;
9916
9917     Cost(bool ForCodeSize = false)
9918         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9919           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9920
9921     /// \brief Get the cost of one isolated slice.
9922     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9923         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9924           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9925       EVT TruncType = LS.Inst->getValueType(0);
9926       EVT LoadedType = LS.getLoadedType();
9927       if (TruncType != LoadedType &&
9928           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9929         ZExts = 1;
9930     }
9931
9932     /// \brief Account for slicing gain in the current cost.
9933     /// Slicing provide a few gains like removing a shift or a
9934     /// truncate. This method allows to grow the cost of the original
9935     /// load with the gain from this slice.
9936     void addSliceGain(const LoadedSlice &LS) {
9937       // Each slice saves a truncate.
9938       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9939       if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
9940                               LS.Inst->getValueType(0)))
9941         ++Truncates;
9942       // If there is a shift amount, this slice gets rid of it.
9943       if (LS.Shift)
9944         ++Shift;
9945       // If this slice can merge a cross register bank copy, account for it.
9946       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9947         ++CrossRegisterBanksCopies;
9948     }
9949
9950     Cost &operator+=(const Cost &RHS) {
9951       Loads += RHS.Loads;
9952       Truncates += RHS.Truncates;
9953       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9954       ZExts += RHS.ZExts;
9955       Shift += RHS.Shift;
9956       return *this;
9957     }
9958
9959     bool operator==(const Cost &RHS) const {
9960       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9961              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9962              ZExts == RHS.ZExts && Shift == RHS.Shift;
9963     }
9964
9965     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9966
9967     bool operator<(const Cost &RHS) const {
9968       // Assume cross register banks copies are as expensive as loads.
9969       // FIXME: Do we want some more target hooks?
9970       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9971       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9972       // Unless we are optimizing for code size, consider the
9973       // expensive operation first.
9974       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9975         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9976       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9977              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9978     }
9979
9980     bool operator>(const Cost &RHS) const { return RHS < *this; }
9981
9982     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9983
9984     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9985   };
9986   // The last instruction that represent the slice. This should be a
9987   // truncate instruction.
9988   SDNode *Inst;
9989   // The original load instruction.
9990   LoadSDNode *Origin;
9991   // The right shift amount in bits from the original load.
9992   unsigned Shift;
9993   // The DAG from which Origin came from.
9994   // This is used to get some contextual information about legal types, etc.
9995   SelectionDAG *DAG;
9996
9997   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9998               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9999       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
10000
10001   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
10002   /// \return Result is \p BitWidth and has used bits set to 1 and
10003   ///         not used bits set to 0.
10004   APInt getUsedBits() const {
10005     // Reproduce the trunc(lshr) sequence:
10006     // - Start from the truncated value.
10007     // - Zero extend to the desired bit width.
10008     // - Shift left.
10009     assert(Origin && "No original load to compare against.");
10010     unsigned BitWidth = Origin->getValueSizeInBits(0);
10011     assert(Inst && "This slice is not bound to an instruction");
10012     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
10013            "Extracted slice is bigger than the whole type!");
10014     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
10015     UsedBits.setAllBits();
10016     UsedBits = UsedBits.zext(BitWidth);
10017     UsedBits <<= Shift;
10018     return UsedBits;
10019   }
10020
10021   /// \brief Get the size of the slice to be loaded in bytes.
10022   unsigned getLoadedSize() const {
10023     unsigned SliceSize = getUsedBits().countPopulation();
10024     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
10025     return SliceSize / 8;
10026   }
10027
10028   /// \brief Get the type that will be loaded for this slice.
10029   /// Note: This may not be the final type for the slice.
10030   EVT getLoadedType() const {
10031     assert(DAG && "Missing context");
10032     LLVMContext &Ctxt = *DAG->getContext();
10033     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
10034   }
10035
10036   /// \brief Get the alignment of the load used for this slice.
10037   unsigned getAlignment() const {
10038     unsigned Alignment = Origin->getAlignment();
10039     unsigned Offset = getOffsetFromBase();
10040     if (Offset != 0)
10041       Alignment = MinAlign(Alignment, Alignment + Offset);
10042     return Alignment;
10043   }
10044
10045   /// \brief Check if this slice can be rewritten with legal operations.
10046   bool isLegal() const {
10047     // An invalid slice is not legal.
10048     if (!Origin || !Inst || !DAG)
10049       return false;
10050
10051     // Offsets are for indexed load only, we do not handle that.
10052     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
10053       return false;
10054
10055     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10056
10057     // Check that the type is legal.
10058     EVT SliceType = getLoadedType();
10059     if (!TLI.isTypeLegal(SliceType))
10060       return false;
10061
10062     // Check that the load is legal for this type.
10063     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
10064       return false;
10065
10066     // Check that the offset can be computed.
10067     // 1. Check its type.
10068     EVT PtrType = Origin->getBasePtr().getValueType();
10069     if (PtrType == MVT::Untyped || PtrType.isExtended())
10070       return false;
10071
10072     // 2. Check that it fits in the immediate.
10073     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
10074       return false;
10075
10076     // 3. Check that the computation is legal.
10077     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
10078       return false;
10079
10080     // Check that the zext is legal if it needs one.
10081     EVT TruncateType = Inst->getValueType(0);
10082     if (TruncateType != SliceType &&
10083         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
10084       return false;
10085
10086     return true;
10087   }
10088
10089   /// \brief Get the offset in bytes of this slice in the original chunk of
10090   /// bits.
10091   /// \pre DAG != nullptr.
10092   uint64_t getOffsetFromBase() const {
10093     assert(DAG && "Missing context.");
10094     bool IsBigEndian = DAG->getDataLayout().isBigEndian();
10095     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
10096     uint64_t Offset = Shift / 8;
10097     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
10098     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
10099            "The size of the original loaded type is not a multiple of a"
10100            " byte.");
10101     // If Offset is bigger than TySizeInBytes, it means we are loading all
10102     // zeros. This should have been optimized before in the process.
10103     assert(TySizeInBytes > Offset &&
10104            "Invalid shift amount for given loaded size");
10105     if (IsBigEndian)
10106       Offset = TySizeInBytes - Offset - getLoadedSize();
10107     return Offset;
10108   }
10109
10110   /// \brief Generate the sequence of instructions to load the slice
10111   /// represented by this object and redirect the uses of this slice to
10112   /// this new sequence of instructions.
10113   /// \pre this->Inst && this->Origin are valid Instructions and this
10114   /// object passed the legal check: LoadedSlice::isLegal returned true.
10115   /// \return The last instruction of the sequence used to load the slice.
10116   SDValue loadSlice() const {
10117     assert(Inst && Origin && "Unable to replace a non-existing slice.");
10118     const SDValue &OldBaseAddr = Origin->getBasePtr();
10119     SDValue BaseAddr = OldBaseAddr;
10120     // Get the offset in that chunk of bytes w.r.t. the endianess.
10121     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
10122     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
10123     if (Offset) {
10124       // BaseAddr = BaseAddr + Offset.
10125       EVT ArithType = BaseAddr.getValueType();
10126       SDLoc DL(Origin);
10127       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
10128                               DAG->getConstant(Offset, DL, ArithType));
10129     }
10130
10131     // Create the type of the loaded slice according to its size.
10132     EVT SliceType = getLoadedType();
10133
10134     // Create the load for the slice.
10135     SDValue LastInst = DAG->getLoad(
10136         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
10137         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
10138         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
10139     // If the final type is not the same as the loaded type, this means that
10140     // we have to pad with zero. Create a zero extend for that.
10141     EVT FinalType = Inst->getValueType(0);
10142     if (SliceType != FinalType)
10143       LastInst =
10144           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
10145     return LastInst;
10146   }
10147
10148   /// \brief Check if this slice can be merged with an expensive cross register
10149   /// bank copy. E.g.,
10150   /// i = load i32
10151   /// f = bitcast i32 i to float
10152   bool canMergeExpensiveCrossRegisterBankCopy() const {
10153     if (!Inst || !Inst->hasOneUse())
10154       return false;
10155     SDNode *Use = *Inst->use_begin();
10156     if (Use->getOpcode() != ISD::BITCAST)
10157       return false;
10158     assert(DAG && "Missing context");
10159     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
10160     EVT ResVT = Use->getValueType(0);
10161     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
10162     const TargetRegisterClass *ArgRC =
10163         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
10164     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
10165       return false;
10166
10167     // At this point, we know that we perform a cross-register-bank copy.
10168     // Check if it is expensive.
10169     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
10170     // Assume bitcasts are cheap, unless both register classes do not
10171     // explicitly share a common sub class.
10172     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
10173       return false;
10174
10175     // Check if it will be merged with the load.
10176     // 1. Check the alignment constraint.
10177     unsigned RequiredAlignment = DAG->getDataLayout().getABITypeAlignment(
10178         ResVT.getTypeForEVT(*DAG->getContext()));
10179
10180     if (RequiredAlignment > getAlignment())
10181       return false;
10182
10183     // 2. Check that the load is a legal operation for that type.
10184     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
10185       return false;
10186
10187     // 3. Check that we do not have a zext in the way.
10188     if (Inst->getValueType(0) != getLoadedType())
10189       return false;
10190
10191     return true;
10192   }
10193 };
10194 }
10195
10196 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
10197 /// \p UsedBits looks like 0..0 1..1 0..0.
10198 static bool areUsedBitsDense(const APInt &UsedBits) {
10199   // If all the bits are one, this is dense!
10200   if (UsedBits.isAllOnesValue())
10201     return true;
10202
10203   // Get rid of the unused bits on the right.
10204   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
10205   // Get rid of the unused bits on the left.
10206   if (NarrowedUsedBits.countLeadingZeros())
10207     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
10208   // Check that the chunk of bits is completely used.
10209   return NarrowedUsedBits.isAllOnesValue();
10210 }
10211
10212 /// \brief Check whether or not \p First and \p Second are next to each other
10213 /// in memory. This means that there is no hole between the bits loaded
10214 /// by \p First and the bits loaded by \p Second.
10215 static bool areSlicesNextToEachOther(const LoadedSlice &First,
10216                                      const LoadedSlice &Second) {
10217   assert(First.Origin == Second.Origin && First.Origin &&
10218          "Unable to match different memory origins.");
10219   APInt UsedBits = First.getUsedBits();
10220   assert((UsedBits & Second.getUsedBits()) == 0 &&
10221          "Slices are not supposed to overlap.");
10222   UsedBits |= Second.getUsedBits();
10223   return areUsedBitsDense(UsedBits);
10224 }
10225
10226 /// \brief Adjust the \p GlobalLSCost according to the target
10227 /// paring capabilities and the layout of the slices.
10228 /// \pre \p GlobalLSCost should account for at least as many loads as
10229 /// there is in the slices in \p LoadedSlices.
10230 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10231                                  LoadedSlice::Cost &GlobalLSCost) {
10232   unsigned NumberOfSlices = LoadedSlices.size();
10233   // If there is less than 2 elements, no pairing is possible.
10234   if (NumberOfSlices < 2)
10235     return;
10236
10237   // Sort the slices so that elements that are likely to be next to each
10238   // other in memory are next to each other in the list.
10239   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
10240             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
10241     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
10242     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
10243   });
10244   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
10245   // First (resp. Second) is the first (resp. Second) potentially candidate
10246   // to be placed in a paired load.
10247   const LoadedSlice *First = nullptr;
10248   const LoadedSlice *Second = nullptr;
10249   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
10250                 // Set the beginning of the pair.
10251                                                            First = Second) {
10252
10253     Second = &LoadedSlices[CurrSlice];
10254
10255     // If First is NULL, it means we start a new pair.
10256     // Get to the next slice.
10257     if (!First)
10258       continue;
10259
10260     EVT LoadedType = First->getLoadedType();
10261
10262     // If the types of the slices are different, we cannot pair them.
10263     if (LoadedType != Second->getLoadedType())
10264       continue;
10265
10266     // Check if the target supplies paired loads for this type.
10267     unsigned RequiredAlignment = 0;
10268     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
10269       // move to the next pair, this type is hopeless.
10270       Second = nullptr;
10271       continue;
10272     }
10273     // Check if we meet the alignment requirement.
10274     if (RequiredAlignment > First->getAlignment())
10275       continue;
10276
10277     // Check that both loads are next to each other in memory.
10278     if (!areSlicesNextToEachOther(*First, *Second))
10279       continue;
10280
10281     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
10282     --GlobalLSCost.Loads;
10283     // Move to the next pair.
10284     Second = nullptr;
10285   }
10286 }
10287
10288 /// \brief Check the profitability of all involved LoadedSlice.
10289 /// Currently, it is considered profitable if there is exactly two
10290 /// involved slices (1) which are (2) next to each other in memory, and
10291 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
10292 ///
10293 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
10294 /// the elements themselves.
10295 ///
10296 /// FIXME: When the cost model will be mature enough, we can relax
10297 /// constraints (1) and (2).
10298 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10299                                 const APInt &UsedBits, bool ForCodeSize) {
10300   unsigned NumberOfSlices = LoadedSlices.size();
10301   if (StressLoadSlicing)
10302     return NumberOfSlices > 1;
10303
10304   // Check (1).
10305   if (NumberOfSlices != 2)
10306     return false;
10307
10308   // Check (2).
10309   if (!areUsedBitsDense(UsedBits))
10310     return false;
10311
10312   // Check (3).
10313   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10314   // The original code has one big load.
10315   OrigCost.Loads = 1;
10316   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10317     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10318     // Accumulate the cost of all the slices.
10319     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10320     GlobalSlicingCost += SliceCost;
10321
10322     // Account as cost in the original configuration the gain obtained
10323     // with the current slices.
10324     OrigCost.addSliceGain(LS);
10325   }
10326
10327   // If the target supports paired load, adjust the cost accordingly.
10328   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10329   return OrigCost > GlobalSlicingCost;
10330 }
10331
10332 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10333 /// operations, split it in the various pieces being extracted.
10334 ///
10335 /// This sort of thing is introduced by SROA.
10336 /// This slicing takes care not to insert overlapping loads.
10337 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10338 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10339   if (Level < AfterLegalizeDAG)
10340     return false;
10341
10342   LoadSDNode *LD = cast<LoadSDNode>(N);
10343   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10344       !LD->getValueType(0).isInteger())
10345     return false;
10346
10347   // Keep track of already used bits to detect overlapping values.
10348   // In that case, we will just abort the transformation.
10349   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10350
10351   SmallVector<LoadedSlice, 4> LoadedSlices;
10352
10353   // Check if this load is used as several smaller chunks of bits.
10354   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10355   // of computation for each trunc.
10356   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10357        UI != UIEnd; ++UI) {
10358     // Skip the uses of the chain.
10359     if (UI.getUse().getResNo() != 0)
10360       continue;
10361
10362     SDNode *User = *UI;
10363     unsigned Shift = 0;
10364
10365     // Check if this is a trunc(lshr).
10366     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10367         isa<ConstantSDNode>(User->getOperand(1))) {
10368       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10369       User = *User->use_begin();
10370     }
10371
10372     // At this point, User is a Truncate, iff we encountered, trunc or
10373     // trunc(lshr).
10374     if (User->getOpcode() != ISD::TRUNCATE)
10375       return false;
10376
10377     // The width of the type must be a power of 2 and greater than 8-bits.
10378     // Otherwise the load cannot be represented in LLVM IR.
10379     // Moreover, if we shifted with a non-8-bits multiple, the slice
10380     // will be across several bytes. We do not support that.
10381     unsigned Width = User->getValueSizeInBits(0);
10382     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10383       return 0;
10384
10385     // Build the slice for this chain of computations.
10386     LoadedSlice LS(User, LD, Shift, &DAG);
10387     APInt CurrentUsedBits = LS.getUsedBits();
10388
10389     // Check if this slice overlaps with another.
10390     if ((CurrentUsedBits & UsedBits) != 0)
10391       return false;
10392     // Update the bits used globally.
10393     UsedBits |= CurrentUsedBits;
10394
10395     // Check if the new slice would be legal.
10396     if (!LS.isLegal())
10397       return false;
10398
10399     // Record the slice.
10400     LoadedSlices.push_back(LS);
10401   }
10402
10403   // Abort slicing if it does not seem to be profitable.
10404   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10405     return false;
10406
10407   ++SlicedLoads;
10408
10409   // Rewrite each chain to use an independent load.
10410   // By construction, each chain can be represented by a unique load.
10411
10412   // Prepare the argument for the new token factor for all the slices.
10413   SmallVector<SDValue, 8> ArgChains;
10414   for (SmallVectorImpl<LoadedSlice>::const_iterator
10415            LSIt = LoadedSlices.begin(),
10416            LSItEnd = LoadedSlices.end();
10417        LSIt != LSItEnd; ++LSIt) {
10418     SDValue SliceInst = LSIt->loadSlice();
10419     CombineTo(LSIt->Inst, SliceInst, true);
10420     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10421       SliceInst = SliceInst.getOperand(0);
10422     assert(SliceInst->getOpcode() == ISD::LOAD &&
10423            "It takes more than a zext to get to the loaded slice!!");
10424     ArgChains.push_back(SliceInst.getValue(1));
10425   }
10426
10427   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10428                               ArgChains);
10429   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10430   return true;
10431 }
10432
10433 /// Check to see if V is (and load (ptr), imm), where the load is having
10434 /// specific bytes cleared out.  If so, return the byte size being masked out
10435 /// and the shift amount.
10436 static std::pair<unsigned, unsigned>
10437 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10438   std::pair<unsigned, unsigned> Result(0, 0);
10439
10440   // Check for the structure we're looking for.
10441   if (V->getOpcode() != ISD::AND ||
10442       !isa<ConstantSDNode>(V->getOperand(1)) ||
10443       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10444     return Result;
10445
10446   // Check the chain and pointer.
10447   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10448   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10449
10450   // The store should be chained directly to the load or be an operand of a
10451   // tokenfactor.
10452   if (LD == Chain.getNode())
10453     ; // ok.
10454   else if (Chain->getOpcode() != ISD::TokenFactor)
10455     return Result; // Fail.
10456   else {
10457     bool isOk = false;
10458     for (const SDValue &ChainOp : Chain->op_values())
10459       if (ChainOp.getNode() == LD) {
10460         isOk = true;
10461         break;
10462       }
10463     if (!isOk) return Result;
10464   }
10465
10466   // This only handles simple types.
10467   if (V.getValueType() != MVT::i16 &&
10468       V.getValueType() != MVT::i32 &&
10469       V.getValueType() != MVT::i64)
10470     return Result;
10471
10472   // Check the constant mask.  Invert it so that the bits being masked out are
10473   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10474   // follow the sign bit for uniformity.
10475   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10476   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10477   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10478   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10479   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10480   if (NotMaskLZ == 64) return Result;  // All zero mask.
10481
10482   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10483   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10484     return Result;
10485
10486   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10487   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10488     NotMaskLZ -= 64-V.getValueSizeInBits();
10489
10490   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10491   switch (MaskedBytes) {
10492   case 1:
10493   case 2:
10494   case 4: break;
10495   default: return Result; // All one mask, or 5-byte mask.
10496   }
10497
10498   // Verify that the first bit starts at a multiple of mask so that the access
10499   // is aligned the same as the access width.
10500   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10501
10502   Result.first = MaskedBytes;
10503   Result.second = NotMaskTZ/8;
10504   return Result;
10505 }
10506
10507
10508 /// Check to see if IVal is something that provides a value as specified by
10509 /// MaskInfo. If so, replace the specified store with a narrower store of
10510 /// truncated IVal.
10511 static SDNode *
10512 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10513                                 SDValue IVal, StoreSDNode *St,
10514                                 DAGCombiner *DC) {
10515   unsigned NumBytes = MaskInfo.first;
10516   unsigned ByteShift = MaskInfo.second;
10517   SelectionDAG &DAG = DC->getDAG();
10518
10519   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10520   // that uses this.  If not, this is not a replacement.
10521   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10522                                   ByteShift*8, (ByteShift+NumBytes)*8);
10523   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10524
10525   // Check that it is legal on the target to do this.  It is legal if the new
10526   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10527   // legalization.
10528   MVT VT = MVT::getIntegerVT(NumBytes*8);
10529   if (!DC->isTypeLegal(VT))
10530     return nullptr;
10531
10532   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10533   // shifted by ByteShift and truncated down to NumBytes.
10534   if (ByteShift) {
10535     SDLoc DL(IVal);
10536     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10537                        DAG.getConstant(ByteShift*8, DL,
10538                                     DC->getShiftAmountTy(IVal.getValueType())));
10539   }
10540
10541   // Figure out the offset for the store and the alignment of the access.
10542   unsigned StOffset;
10543   unsigned NewAlign = St->getAlignment();
10544
10545   if (DAG.getDataLayout().isLittleEndian())
10546     StOffset = ByteShift;
10547   else
10548     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10549
10550   SDValue Ptr = St->getBasePtr();
10551   if (StOffset) {
10552     SDLoc DL(IVal);
10553     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10554                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10555     NewAlign = MinAlign(NewAlign, StOffset);
10556   }
10557
10558   // Truncate down to the new size.
10559   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10560
10561   ++OpsNarrowed;
10562   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10563                       St->getPointerInfo().getWithOffset(StOffset),
10564                       false, false, NewAlign).getNode();
10565 }
10566
10567
10568 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10569 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10570 /// narrowing the load and store if it would end up being a win for performance
10571 /// or code size.
10572 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10573   StoreSDNode *ST  = cast<StoreSDNode>(N);
10574   if (ST->isVolatile())
10575     return SDValue();
10576
10577   SDValue Chain = ST->getChain();
10578   SDValue Value = ST->getValue();
10579   SDValue Ptr   = ST->getBasePtr();
10580   EVT VT = Value.getValueType();
10581
10582   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10583     return SDValue();
10584
10585   unsigned Opc = Value.getOpcode();
10586
10587   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10588   // is a byte mask indicating a consecutive number of bytes, check to see if
10589   // Y is known to provide just those bytes.  If so, we try to replace the
10590   // load + replace + store sequence with a single (narrower) store, which makes
10591   // the load dead.
10592   if (Opc == ISD::OR) {
10593     std::pair<unsigned, unsigned> MaskedLoad;
10594     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10595     if (MaskedLoad.first)
10596       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10597                                                   Value.getOperand(1), ST,this))
10598         return SDValue(NewST, 0);
10599
10600     // Or is commutative, so try swapping X and Y.
10601     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10602     if (MaskedLoad.first)
10603       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10604                                                   Value.getOperand(0), ST,this))
10605         return SDValue(NewST, 0);
10606   }
10607
10608   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10609       Value.getOperand(1).getOpcode() != ISD::Constant)
10610     return SDValue();
10611
10612   SDValue N0 = Value.getOperand(0);
10613   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10614       Chain == SDValue(N0.getNode(), 1)) {
10615     LoadSDNode *LD = cast<LoadSDNode>(N0);
10616     if (LD->getBasePtr() != Ptr ||
10617         LD->getPointerInfo().getAddrSpace() !=
10618         ST->getPointerInfo().getAddrSpace())
10619       return SDValue();
10620
10621     // Find the type to narrow it the load / op / store to.
10622     SDValue N1 = Value.getOperand(1);
10623     unsigned BitWidth = N1.getValueSizeInBits();
10624     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10625     if (Opc == ISD::AND)
10626       Imm ^= APInt::getAllOnesValue(BitWidth);
10627     if (Imm == 0 || Imm.isAllOnesValue())
10628       return SDValue();
10629     unsigned ShAmt = Imm.countTrailingZeros();
10630     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10631     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10632     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10633     // The narrowing should be profitable, the load/store operation should be
10634     // legal (or custom) and the store size should be equal to the NewVT width.
10635     while (NewBW < BitWidth &&
10636            (NewVT.getStoreSizeInBits() != NewBW ||
10637             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10638             !TLI.isNarrowingProfitable(VT, NewVT))) {
10639       NewBW = NextPowerOf2(NewBW);
10640       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10641     }
10642     if (NewBW >= BitWidth)
10643       return SDValue();
10644
10645     // If the lsb changed does not start at the type bitwidth boundary,
10646     // start at the previous one.
10647     if (ShAmt % NewBW)
10648       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10649     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10650                                    std::min(BitWidth, ShAmt + NewBW));
10651     if ((Imm & Mask) == Imm) {
10652       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10653       if (Opc == ISD::AND)
10654         NewImm ^= APInt::getAllOnesValue(NewBW);
10655       uint64_t PtrOff = ShAmt / 8;
10656       // For big endian targets, we need to adjust the offset to the pointer to
10657       // load the correct bytes.
10658       if (DAG.getDataLayout().isBigEndian())
10659         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10660
10661       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10662       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10663       if (NewAlign < DAG.getDataLayout().getABITypeAlignment(NewVTTy))
10664         return SDValue();
10665
10666       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10667                                    Ptr.getValueType(), Ptr,
10668                                    DAG.getConstant(PtrOff, SDLoc(LD),
10669                                                    Ptr.getValueType()));
10670       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10671                                   LD->getChain(), NewPtr,
10672                                   LD->getPointerInfo().getWithOffset(PtrOff),
10673                                   LD->isVolatile(), LD->isNonTemporal(),
10674                                   LD->isInvariant(), NewAlign,
10675                                   LD->getAAInfo());
10676       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10677                                    DAG.getConstant(NewImm, SDLoc(Value),
10678                                                    NewVT));
10679       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10680                                    NewVal, NewPtr,
10681                                    ST->getPointerInfo().getWithOffset(PtrOff),
10682                                    false, false, NewAlign);
10683
10684       AddToWorklist(NewPtr.getNode());
10685       AddToWorklist(NewLD.getNode());
10686       AddToWorklist(NewVal.getNode());
10687       WorklistRemover DeadNodes(*this);
10688       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10689       ++OpsNarrowed;
10690       return NewST;
10691     }
10692   }
10693
10694   return SDValue();
10695 }
10696
10697 /// For a given floating point load / store pair, if the load value isn't used
10698 /// by any other operations, then consider transforming the pair to integer
10699 /// load / store operations if the target deems the transformation profitable.
10700 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10701   StoreSDNode *ST  = cast<StoreSDNode>(N);
10702   SDValue Chain = ST->getChain();
10703   SDValue Value = ST->getValue();
10704   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10705       Value.hasOneUse() &&
10706       Chain == SDValue(Value.getNode(), 1)) {
10707     LoadSDNode *LD = cast<LoadSDNode>(Value);
10708     EVT VT = LD->getMemoryVT();
10709     if (!VT.isFloatingPoint() ||
10710         VT != ST->getMemoryVT() ||
10711         LD->isNonTemporal() ||
10712         ST->isNonTemporal() ||
10713         LD->getPointerInfo().getAddrSpace() != 0 ||
10714         ST->getPointerInfo().getAddrSpace() != 0)
10715       return SDValue();
10716
10717     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10718     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10719         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10720         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10721         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10722       return SDValue();
10723
10724     unsigned LDAlign = LD->getAlignment();
10725     unsigned STAlign = ST->getAlignment();
10726     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10727     unsigned ABIAlign = DAG.getDataLayout().getABITypeAlignment(IntVTTy);
10728     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10729       return SDValue();
10730
10731     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10732                                 LD->getChain(), LD->getBasePtr(),
10733                                 LD->getPointerInfo(),
10734                                 false, false, false, LDAlign);
10735
10736     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10737                                  NewLD, ST->getBasePtr(),
10738                                  ST->getPointerInfo(),
10739                                  false, false, STAlign);
10740
10741     AddToWorklist(NewLD.getNode());
10742     AddToWorklist(NewST.getNode());
10743     WorklistRemover DeadNodes(*this);
10744     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10745     ++LdStFP2Int;
10746     return NewST;
10747   }
10748
10749   return SDValue();
10750 }
10751
10752 namespace {
10753 /// Helper struct to parse and store a memory address as base + index + offset.
10754 /// We ignore sign extensions when it is safe to do so.
10755 /// The following two expressions are not equivalent. To differentiate we need
10756 /// to store whether there was a sign extension involved in the index
10757 /// computation.
10758 ///  (load (i64 add (i64 copyfromreg %c)
10759 ///                 (i64 signextend (add (i8 load %index)
10760 ///                                      (i8 1))))
10761 /// vs
10762 ///
10763 /// (load (i64 add (i64 copyfromreg %c)
10764 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10765 ///                                         (i32 1)))))
10766 struct BaseIndexOffset {
10767   SDValue Base;
10768   SDValue Index;
10769   int64_t Offset;
10770   bool IsIndexSignExt;
10771
10772   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10773
10774   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10775                   bool IsIndexSignExt) :
10776     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10777
10778   bool equalBaseIndex(const BaseIndexOffset &Other) {
10779     return Other.Base == Base && Other.Index == Index &&
10780       Other.IsIndexSignExt == IsIndexSignExt;
10781   }
10782
10783   /// Parses tree in Ptr for base, index, offset addresses.
10784   static BaseIndexOffset match(SDValue Ptr) {
10785     bool IsIndexSignExt = false;
10786
10787     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10788     // instruction, then it could be just the BASE or everything else we don't
10789     // know how to handle. Just use Ptr as BASE and give up.
10790     if (Ptr->getOpcode() != ISD::ADD)
10791       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10792
10793     // We know that we have at least an ADD instruction. Try to pattern match
10794     // the simple case of BASE + OFFSET.
10795     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10796       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10797       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10798                               IsIndexSignExt);
10799     }
10800
10801     // Inside a loop the current BASE pointer is calculated using an ADD and a
10802     // MUL instruction. In this case Ptr is the actual BASE pointer.
10803     // (i64 add (i64 %array_ptr)
10804     //          (i64 mul (i64 %induction_var)
10805     //                   (i64 %element_size)))
10806     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10807       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10808
10809     // Look at Base + Index + Offset cases.
10810     SDValue Base = Ptr->getOperand(0);
10811     SDValue IndexOffset = Ptr->getOperand(1);
10812
10813     // Skip signextends.
10814     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10815       IndexOffset = IndexOffset->getOperand(0);
10816       IsIndexSignExt = true;
10817     }
10818
10819     // Either the case of Base + Index (no offset) or something else.
10820     if (IndexOffset->getOpcode() != ISD::ADD)
10821       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10822
10823     // Now we have the case of Base + Index + offset.
10824     SDValue Index = IndexOffset->getOperand(0);
10825     SDValue Offset = IndexOffset->getOperand(1);
10826
10827     if (!isa<ConstantSDNode>(Offset))
10828       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10829
10830     // Ignore signextends.
10831     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10832       Index = Index->getOperand(0);
10833       IsIndexSignExt = true;
10834     } else IsIndexSignExt = false;
10835
10836     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10837     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10838   }
10839 };
10840 } // namespace
10841
10842 SDValue DAGCombiner::getMergedConstantVectorStore(SelectionDAG &DAG,
10843                                                   SDLoc SL,
10844                                                   ArrayRef<MemOpLink> Stores,
10845                                                   SmallVectorImpl<SDValue> &Chains,
10846                                                   EVT Ty) const {
10847   SmallVector<SDValue, 8> BuildVector;
10848
10849   for (unsigned I = 0, E = Ty.getVectorNumElements(); I != E; ++I) {
10850     StoreSDNode *St = cast<StoreSDNode>(Stores[I].MemNode);
10851     Chains.push_back(St->getChain());
10852     BuildVector.push_back(St->getValue());
10853   }
10854
10855   return DAG.getNode(ISD::BUILD_VECTOR, SL, Ty, BuildVector);
10856 }
10857
10858 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10859                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10860                   unsigned NumStores, bool IsConstantSrc, bool UseVector) {
10861   // Make sure we have something to merge.
10862   if (NumStores < 2)
10863     return false;
10864
10865   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10866   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10867   unsigned LatestNodeUsed = 0;
10868
10869   for (unsigned i=0; i < NumStores; ++i) {
10870     // Find a chain for the new wide-store operand. Notice that some
10871     // of the store nodes that we found may not be selected for inclusion
10872     // in the wide store. The chain we use needs to be the chain of the
10873     // latest store node which is *used* and replaced by the wide store.
10874     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10875       LatestNodeUsed = i;
10876   }
10877
10878   SmallVector<SDValue, 8> Chains;
10879
10880   // The latest Node in the DAG.
10881   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10882   SDLoc DL(StoreNodes[0].MemNode);
10883
10884   SDValue StoredVal;
10885   if (UseVector) {
10886     bool IsVec = MemVT.isVector();
10887     unsigned Elts = NumStores;
10888     if (IsVec) {
10889       // When merging vector stores, get the total number of elements.
10890       Elts *= MemVT.getVectorNumElements();
10891     }
10892     // Get the type for the merged vector store.
10893     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
10894     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10895
10896     if (IsConstantSrc) {
10897       StoredVal = getMergedConstantVectorStore(DAG, DL, StoreNodes, Chains, Ty);
10898     } else {
10899       SmallVector<SDValue, 8> Ops;
10900       for (unsigned i = 0; i < NumStores; ++i) {
10901         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10902         SDValue Val = St->getValue();
10903         // All operands of BUILD_VECTOR / CONCAT_VECTOR must have the same type.
10904         if (Val.getValueType() != MemVT)
10905           return false;
10906         Ops.push_back(Val);
10907         Chains.push_back(St->getChain());
10908       }
10909
10910       // Build the extracted vector elements back into a vector.
10911       StoredVal = DAG.getNode(IsVec ? ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
10912                               DL, Ty, Ops);    }
10913   } else {
10914     // We should always use a vector store when merging extracted vector
10915     // elements, so this path implies a store of constants.
10916     assert(IsConstantSrc && "Merged vector elements should use vector store");
10917
10918     unsigned SizeInBits = NumStores * ElementSizeBytes * 8;
10919     APInt StoreInt(SizeInBits, 0);
10920
10921     // Construct a single integer constant which is made of the smaller
10922     // constant inputs.
10923     bool IsLE = DAG.getDataLayout().isLittleEndian();
10924     for (unsigned i = 0; i < NumStores; ++i) {
10925       unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
10926       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10927       Chains.push_back(St->getChain());
10928
10929       SDValue Val = St->getValue();
10930       StoreInt <<= ElementSizeBytes * 8;
10931       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10932         StoreInt |= C->getAPIntValue().zext(SizeInBits);
10933       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10934         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(SizeInBits);
10935       } else {
10936         llvm_unreachable("Invalid constant element type");
10937       }
10938     }
10939
10940     // Create the new Load and Store operations.
10941     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
10942     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10943   }
10944
10945   assert(!Chains.empty());
10946
10947   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
10948   SDValue NewStore = DAG.getStore(NewChain, DL, StoredVal,
10949                                   FirstInChain->getBasePtr(),
10950                                   FirstInChain->getPointerInfo(),
10951                                   false, false,
10952                                   FirstInChain->getAlignment());
10953
10954   // Replace the last store with the new store
10955   CombineTo(LatestOp, NewStore);
10956   // Erase all other stores.
10957   for (unsigned i = 0; i < NumStores; ++i) {
10958     if (StoreNodes[i].MemNode == LatestOp)
10959       continue;
10960     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10961     // ReplaceAllUsesWith will replace all uses that existed when it was
10962     // called, but graph optimizations may cause new ones to appear. For
10963     // example, the case in pr14333 looks like
10964     //
10965     //  St's chain -> St -> another store -> X
10966     //
10967     // And the only difference from St to the other store is the chain.
10968     // When we change it's chain to be St's chain they become identical,
10969     // get CSEed and the net result is that X is now a use of St.
10970     // Since we know that St is redundant, just iterate.
10971     while (!St->use_empty())
10972       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10973     deleteAndRecombine(St);
10974   }
10975
10976   return true;
10977 }
10978
10979 void DAGCombiner::getStoreMergeAndAliasCandidates(
10980     StoreSDNode* St, SmallVectorImpl<MemOpLink> &StoreNodes,
10981     SmallVectorImpl<LSBaseSDNode*> &AliasLoadNodes) {
10982   // This holds the base pointer, index, and the offset in bytes from the base
10983   // pointer.
10984   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10985
10986   // We must have a base and an offset.
10987   if (!BasePtr.Base.getNode())
10988     return;
10989
10990   // Do not handle stores to undef base pointers.
10991   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10992     return;
10993
10994   // Walk up the chain and look for nodes with offsets from the same
10995   // base pointer. Stop when reaching an instruction with a different kind
10996   // or instruction which has a different base pointer.
10997   EVT MemVT = St->getMemoryVT();
10998   unsigned Seq = 0;
10999   StoreSDNode *Index = St;
11000
11001
11002   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11003                                                   : DAG.getSubtarget().useAA();
11004
11005   if (UseAA) {
11006     // Look at other users of the same chain. Stores on the same chain do not
11007     // alias. If combiner-aa is enabled, non-aliasing stores are canonicalized
11008     // to be on the same chain, so don't bother looking at adjacent chains.
11009
11010     SDValue Chain = St->getChain();
11011     for (auto I = Chain->use_begin(), E = Chain->use_end(); I != E; ++I) {
11012       if (StoreSDNode *OtherST = dyn_cast<StoreSDNode>(*I)) {
11013         if (I.getOperandNo() != 0)
11014           continue;
11015
11016         if (OtherST->isVolatile() || OtherST->isIndexed())
11017           continue;
11018
11019         if (OtherST->getMemoryVT() != MemVT)
11020           continue;
11021
11022         BaseIndexOffset Ptr = BaseIndexOffset::match(OtherST->getBasePtr());
11023
11024         if (Ptr.equalBaseIndex(BasePtr))
11025           StoreNodes.push_back(MemOpLink(OtherST, Ptr.Offset, Seq++));
11026       }
11027     }
11028
11029     return;
11030   }
11031
11032   while (Index) {
11033     // If the chain has more than one use, then we can't reorder the mem ops.
11034     if (Index != St && !SDValue(Index, 0)->hasOneUse())
11035       break;
11036
11037     // Find the base pointer and offset for this memory node.
11038     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
11039
11040     // Check that the base pointer is the same as the original one.
11041     if (!Ptr.equalBaseIndex(BasePtr))
11042       break;
11043
11044     // The memory operands must not be volatile.
11045     if (Index->isVolatile() || Index->isIndexed())
11046       break;
11047
11048     // No truncation.
11049     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
11050       if (St->isTruncatingStore())
11051         break;
11052
11053     // The stored memory type must be the same.
11054     if (Index->getMemoryVT() != MemVT)
11055       break;
11056
11057     // We found a potential memory operand to merge.
11058     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
11059
11060     // Find the next memory operand in the chain. If the next operand in the
11061     // chain is a store then move up and continue the scan with the next
11062     // memory operand. If the next operand is a load save it and use alias
11063     // information to check if it interferes with anything.
11064     SDNode *NextInChain = Index->getChain().getNode();
11065     while (1) {
11066       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
11067         // We found a store node. Use it for the next iteration.
11068         Index = STn;
11069         break;
11070       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
11071         if (Ldn->isVolatile()) {
11072           Index = nullptr;
11073           break;
11074         }
11075
11076         // Save the load node for later. Continue the scan.
11077         AliasLoadNodes.push_back(Ldn);
11078         NextInChain = Ldn->getChain().getNode();
11079         continue;
11080       } else {
11081         Index = nullptr;
11082         break;
11083       }
11084     }
11085   }
11086 }
11087
11088 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
11089   if (OptLevel == CodeGenOpt::None)
11090     return false;
11091
11092   EVT MemVT = St->getMemoryVT();
11093   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
11094   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
11095       Attribute::NoImplicitFloat);
11096
11097   // This function cannot currently deal with non-byte-sized memory sizes.
11098   if (ElementSizeBytes * 8 != MemVT.getSizeInBits())
11099     return false;
11100
11101   if (!MemVT.isSimple())
11102     return false;
11103
11104   // Perform an early exit check. Do not bother looking at stored values that
11105   // are not constants, loads, or extracted vector elements.
11106   SDValue StoredVal = St->getValue();
11107   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
11108   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
11109                        isa<ConstantFPSDNode>(StoredVal);
11110   bool IsExtractVecSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
11111                           StoredVal.getOpcode() == ISD::EXTRACT_SUBVECTOR);
11112
11113   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecSrc)
11114     return false;
11115
11116   // Don't merge vectors into wider vectors if the source data comes from loads.
11117   // TODO: This restriction can be lifted by using logic similar to the
11118   // ExtractVecSrc case.
11119   if (MemVT.isVector() && IsLoadSrc)
11120     return false;
11121
11122   // Only look at ends of store sequences.
11123   SDValue Chain = SDValue(St, 0);
11124   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
11125     return false;
11126
11127   // Save the LoadSDNodes that we find in the chain.
11128   // We need to make sure that these nodes do not interfere with
11129   // any of the store nodes.
11130   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
11131
11132   // Save the StoreSDNodes that we find in the chain.
11133   SmallVector<MemOpLink, 8> StoreNodes;
11134
11135   getStoreMergeAndAliasCandidates(St, StoreNodes, AliasLoadNodes);
11136
11137   // Check if there is anything to merge.
11138   if (StoreNodes.size() < 2)
11139     return false;
11140
11141   // Sort the memory operands according to their distance from the base pointer.
11142   std::sort(StoreNodes.begin(), StoreNodes.end(),
11143             [](MemOpLink LHS, MemOpLink RHS) {
11144     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
11145            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
11146             LHS.SequenceNum > RHS.SequenceNum);
11147   });
11148
11149   // Scan the memory operations on the chain and find the first non-consecutive
11150   // store memory address.
11151   unsigned LastConsecutiveStore = 0;
11152   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
11153   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
11154
11155     // Check that the addresses are consecutive starting from the second
11156     // element in the list of stores.
11157     if (i > 0) {
11158       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
11159       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11160         break;
11161     }
11162
11163     bool Alias = false;
11164     // Check if this store interferes with any of the loads that we found.
11165     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
11166       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
11167         Alias = true;
11168         break;
11169       }
11170     // We found a load that alias with this store. Stop the sequence.
11171     if (Alias)
11172       break;
11173
11174     // Mark this node as useful.
11175     LastConsecutiveStore = i;
11176   }
11177
11178   // The node with the lowest store address.
11179   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
11180   unsigned FirstStoreAS = FirstInChain->getAddressSpace();
11181   unsigned FirstStoreAlign = FirstInChain->getAlignment();
11182   LLVMContext &Context = *DAG.getContext();
11183   const DataLayout &DL = DAG.getDataLayout();
11184
11185   // Store the constants into memory as one consecutive store.
11186   if (IsConstantSrc) {
11187     unsigned LastLegalType = 0;
11188     unsigned LastLegalVectorType = 0;
11189     bool NonZero = false;
11190     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11191       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11192       SDValue StoredVal = St->getValue();
11193
11194       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
11195         NonZero |= !C->isNullValue();
11196       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
11197         NonZero |= !C->getConstantFPValue()->isNullValue();
11198       } else {
11199         // Non-constant.
11200         break;
11201       }
11202
11203       // Find a legal type for the constant store.
11204       unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11205       EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11206       bool IsFast;
11207       if (TLI.isTypeLegal(StoreTy) &&
11208           TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11209                                  FirstStoreAlign, &IsFast) && IsFast) {
11210         LastLegalType = i+1;
11211       // Or check whether a truncstore is legal.
11212       } else if (TLI.getTypeAction(Context, StoreTy) ==
11213                  TargetLowering::TypePromoteInteger) {
11214         EVT LegalizedStoredValueTy =
11215           TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
11216         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11217             TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11218                                    FirstStoreAS, FirstStoreAlign, &IsFast) &&
11219             IsFast) {
11220           LastLegalType = i + 1;
11221         }
11222       }
11223
11224       // We only use vectors if the constant is known to be zero or the target
11225       // allows it and the function is not marked with the noimplicitfloat
11226       // attribute.
11227       if ((!NonZero || TLI.storeOfVectorConstantIsCheap(MemVT, i+1,
11228                                                         FirstStoreAS)) &&
11229           !NoVectors) {
11230         // Find a legal type for the vector store.
11231         EVT Ty = EVT::getVectorVT(Context, MemVT, i+1);
11232         if (TLI.isTypeLegal(Ty) &&
11233             TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11234                                    FirstStoreAlign, &IsFast) && IsFast)
11235           LastLegalVectorType = i + 1;
11236       }
11237     }
11238
11239     // Check if we found a legal integer type to store.
11240     if (LastLegalType == 0 && LastLegalVectorType == 0)
11241       return false;
11242
11243     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
11244     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
11245
11246     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
11247                                            true, UseVector);
11248   }
11249
11250   // When extracting multiple vector elements, try to store them
11251   // in one vector store rather than a sequence of scalar stores.
11252   if (IsExtractVecSrc) {
11253     unsigned NumStoresToMerge = 0;
11254     bool IsVec = MemVT.isVector();
11255     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
11256       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11257       unsigned StoreValOpcode = St->getValue().getOpcode();
11258       // This restriction could be loosened.
11259       // Bail out if any stored values are not elements extracted from a vector.
11260       // It should be possible to handle mixed sources, but load sources need
11261       // more careful handling (see the block of code below that handles
11262       // consecutive loads).
11263       if (StoreValOpcode != ISD::EXTRACT_VECTOR_ELT &&
11264           StoreValOpcode != ISD::EXTRACT_SUBVECTOR)
11265         return false;
11266
11267       // Find a legal type for the vector store.
11268       unsigned Elts = i + 1;
11269       if (IsVec) {
11270         // When merging vector stores, get the total number of elements.
11271         Elts *= MemVT.getVectorNumElements();
11272       }
11273       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
11274       bool IsFast;
11275       if (TLI.isTypeLegal(Ty) &&
11276           TLI.allowsMemoryAccess(Context, DL, Ty, FirstStoreAS,
11277                                  FirstStoreAlign, &IsFast) && IsFast)
11278         NumStoresToMerge = i + 1;
11279     }
11280
11281     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumStoresToMerge,
11282                                            false, true);
11283   }
11284
11285   // Below we handle the case of multiple consecutive stores that
11286   // come from multiple consecutive loads. We merge them into a single
11287   // wide load and a single wide store.
11288
11289   // Look for load nodes which are used by the stored values.
11290   SmallVector<MemOpLink, 8> LoadNodes;
11291
11292   // Find acceptable loads. Loads need to have the same chain (token factor),
11293   // must not be zext, volatile, indexed, and they must be consecutive.
11294   BaseIndexOffset LdBasePtr;
11295   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
11296     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
11297     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
11298     if (!Ld) break;
11299
11300     // Loads must only have one use.
11301     if (!Ld->hasNUsesOfValue(1, 0))
11302       break;
11303
11304     // The memory operands must not be volatile.
11305     if (Ld->isVolatile() || Ld->isIndexed())
11306       break;
11307
11308     // We do not accept ext loads.
11309     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
11310       break;
11311
11312     // The stored memory type must be the same.
11313     if (Ld->getMemoryVT() != MemVT)
11314       break;
11315
11316     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
11317     // If this is not the first ptr that we check.
11318     if (LdBasePtr.Base.getNode()) {
11319       // The base ptr must be the same.
11320       if (!LdPtr.equalBaseIndex(LdBasePtr))
11321         break;
11322     } else {
11323       // Check that all other base pointers are the same as this one.
11324       LdBasePtr = LdPtr;
11325     }
11326
11327     // We found a potential memory operand to merge.
11328     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
11329   }
11330
11331   if (LoadNodes.size() < 2)
11332     return false;
11333
11334   // If we have load/store pair instructions and we only have two values,
11335   // don't bother.
11336   unsigned RequiredAlignment;
11337   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
11338       St->getAlignment() >= RequiredAlignment)
11339     return false;
11340
11341   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11342   unsigned FirstLoadAS = FirstLoad->getAddressSpace();
11343   unsigned FirstLoadAlign = FirstLoad->getAlignment();
11344
11345   // Scan the memory operations on the chain and find the first non-consecutive
11346   // load memory address. These variables hold the index in the store node
11347   // array.
11348   unsigned LastConsecutiveLoad = 0;
11349   // This variable refers to the size and not index in the array.
11350   unsigned LastLegalVectorType = 0;
11351   unsigned LastLegalIntegerType = 0;
11352   StartAddress = LoadNodes[0].OffsetFromBase;
11353   SDValue FirstChain = FirstLoad->getChain();
11354   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
11355     // All loads much share the same chain.
11356     if (LoadNodes[i].MemNode->getChain() != FirstChain)
11357       break;
11358
11359     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
11360     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
11361       break;
11362     LastConsecutiveLoad = i;
11363     // Find a legal type for the vector store.
11364     EVT StoreTy = EVT::getVectorVT(Context, MemVT, i+1);
11365     bool IsFastSt, IsFastLd;
11366     if (TLI.isTypeLegal(StoreTy) &&
11367         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11368                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11369         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11370                                FirstLoadAlign, &IsFastLd) && IsFastLd) {
11371       LastLegalVectorType = i + 1;
11372     }
11373
11374     // Find a legal type for the integer store.
11375     unsigned SizeInBits = (i+1) * ElementSizeBytes * 8;
11376     StoreTy = EVT::getIntegerVT(Context, SizeInBits);
11377     if (TLI.isTypeLegal(StoreTy) &&
11378         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstStoreAS,
11379                                FirstStoreAlign, &IsFastSt) && IsFastSt &&
11380         TLI.allowsMemoryAccess(Context, DL, StoreTy, FirstLoadAS,
11381                                FirstLoadAlign, &IsFastLd) && IsFastLd)
11382       LastLegalIntegerType = i + 1;
11383     // Or check whether a truncstore and extload is legal.
11384     else if (TLI.getTypeAction(Context, StoreTy) ==
11385              TargetLowering::TypePromoteInteger) {
11386       EVT LegalizedStoredValueTy =
11387         TLI.getTypeToTransformTo(Context, StoreTy);
11388       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
11389           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11390           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11391           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy) &&
11392           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11393                                  FirstStoreAS, FirstStoreAlign, &IsFastSt) &&
11394           IsFastSt &&
11395           TLI.allowsMemoryAccess(Context, DL, LegalizedStoredValueTy,
11396                                  FirstLoadAS, FirstLoadAlign, &IsFastLd) &&
11397           IsFastLd)
11398         LastLegalIntegerType = i+1;
11399     }
11400   }
11401
11402   // Only use vector types if the vector type is larger than the integer type.
11403   // If they are the same, use integers.
11404   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11405   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11406
11407   // We add +1 here because the LastXXX variables refer to location while
11408   // the NumElem refers to array/index size.
11409   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11410   NumElem = std::min(LastLegalType, NumElem);
11411
11412   if (NumElem < 2)
11413     return false;
11414
11415   // Collect the chains from all merged stores.
11416   SmallVector<SDValue, 8> MergeStoreChains;
11417   MergeStoreChains.push_back(StoreNodes[0].MemNode->getChain());
11418
11419   // The latest Node in the DAG.
11420   unsigned LatestNodeUsed = 0;
11421   for (unsigned i=1; i<NumElem; ++i) {
11422     // Find a chain for the new wide-store operand. Notice that some
11423     // of the store nodes that we found may not be selected for inclusion
11424     // in the wide store. The chain we use needs to be the chain of the
11425     // latest store node which is *used* and replaced by the wide store.
11426     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11427       LatestNodeUsed = i;
11428
11429     MergeStoreChains.push_back(StoreNodes[i].MemNode->getChain());
11430   }
11431
11432   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11433
11434   // Find if it is better to use vectors or integers to load and store
11435   // to memory.
11436   EVT JointMemOpVT;
11437   if (UseVectorTy) {
11438     JointMemOpVT = EVT::getVectorVT(Context, MemVT, NumElem);
11439   } else {
11440     unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
11441     JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
11442   }
11443
11444   SDLoc LoadDL(LoadNodes[0].MemNode);
11445   SDLoc StoreDL(StoreNodes[0].MemNode);
11446
11447   // The merged loads are required to have the same chain, so using the first's
11448   // chain is acceptable.
11449   SDValue NewLoad = DAG.getLoad(
11450       JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
11451       FirstLoad->getPointerInfo(), false, false, false, FirstLoadAlign);
11452
11453   SDValue NewStoreChain =
11454     DAG.getNode(ISD::TokenFactor, StoreDL, MVT::Other, MergeStoreChains);
11455
11456   SDValue NewStore = DAG.getStore(
11457     NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
11458       FirstInChain->getPointerInfo(), false, false, FirstStoreAlign);
11459
11460   // Replace one of the loads with the new load.
11461   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11462   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11463                                 SDValue(NewLoad.getNode(), 1));
11464
11465   // Remove the rest of the load chains.
11466   for (unsigned i = 1; i < NumElem ; ++i) {
11467     // Replace all chain users of the old load nodes with the chain of the new
11468     // load node.
11469     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11470     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11471   }
11472
11473   // Replace the last store with the new store.
11474   CombineTo(LatestOp, NewStore);
11475   // Erase all other stores.
11476   for (unsigned i = 0; i < NumElem ; ++i) {
11477     // Remove all Store nodes.
11478     if (StoreNodes[i].MemNode == LatestOp)
11479       continue;
11480     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11481     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11482     deleteAndRecombine(St);
11483   }
11484
11485   return true;
11486 }
11487
11488 SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
11489   SDLoc SL(ST);
11490   SDValue ReplStore;
11491
11492   // Replace the chain to avoid dependency.
11493   if (ST->isTruncatingStore()) {
11494     ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
11495                                   ST->getBasePtr(), ST->getMemoryVT(),
11496                                   ST->getMemOperand());
11497   } else {
11498     ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
11499                              ST->getMemOperand());
11500   }
11501
11502   // Create token to keep both nodes around.
11503   SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
11504                               MVT::Other, ST->getChain(), ReplStore);
11505
11506   // Make sure the new and old chains are cleaned up.
11507   AddToWorklist(Token.getNode());
11508
11509   // Don't add users to work list.
11510   return CombineTo(ST, Token, false);
11511 }
11512
11513 SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
11514   SDValue Value = ST->getValue();
11515   if (Value.getOpcode() == ISD::TargetConstantFP)
11516     return SDValue();
11517
11518   SDLoc DL(ST);
11519
11520   SDValue Chain = ST->getChain();
11521   SDValue Ptr = ST->getBasePtr();
11522
11523   const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
11524
11525   // NOTE: If the original store is volatile, this transform must not increase
11526   // the number of stores.  For example, on x86-32 an f64 can be stored in one
11527   // processor operation but an i64 (which is not legal) requires two.  So the
11528   // transform should not be done in this case.
11529
11530   SDValue Tmp;
11531   switch (CFP->getSimpleValueType(0).SimpleTy) {
11532   default:
11533     llvm_unreachable("Unknown FP type");
11534   case MVT::f16:    // We don't do this for these yet.
11535   case MVT::f80:
11536   case MVT::f128:
11537   case MVT::ppcf128:
11538     return SDValue();
11539   case MVT::f32:
11540     if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11541         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11542       ;
11543       Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11544                             bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11545                             MVT::i32);
11546       return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
11547     }
11548
11549     return SDValue();
11550   case MVT::f64:
11551     if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11552          !ST->isVolatile()) ||
11553         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11554       ;
11555       Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11556                             getZExtValue(), SDLoc(CFP), MVT::i64);
11557       return DAG.getStore(Chain, DL, Tmp,
11558                           Ptr, ST->getMemOperand());
11559     }
11560
11561     if (!ST->isVolatile() &&
11562         TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11563       // Many FP stores are not made apparent until after legalize, e.g. for
11564       // argument passing.  Since this is so common, custom legalize the
11565       // 64-bit integer store into two 32-bit stores.
11566       uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11567       SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11568       SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11569       if (DAG.getDataLayout().isBigEndian())
11570         std::swap(Lo, Hi);
11571
11572       unsigned Alignment = ST->getAlignment();
11573       bool isVolatile = ST->isVolatile();
11574       bool isNonTemporal = ST->isNonTemporal();
11575       AAMDNodes AAInfo = ST->getAAInfo();
11576
11577       SDValue St0 = DAG.getStore(Chain, DL, Lo,
11578                                  Ptr, ST->getPointerInfo(),
11579                                  isVolatile, isNonTemporal,
11580                                  ST->getAlignment(), AAInfo);
11581       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11582                         DAG.getConstant(4, DL, Ptr.getValueType()));
11583       Alignment = MinAlign(Alignment, 4U);
11584       SDValue St1 = DAG.getStore(Chain, DL, Hi,
11585                                  Ptr, ST->getPointerInfo().getWithOffset(4),
11586                                  isVolatile, isNonTemporal,
11587                                  Alignment, AAInfo);
11588       return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11589                          St0, St1);
11590     }
11591
11592     return SDValue();
11593   }
11594 }
11595
11596 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11597   StoreSDNode *ST  = cast<StoreSDNode>(N);
11598   SDValue Chain = ST->getChain();
11599   SDValue Value = ST->getValue();
11600   SDValue Ptr   = ST->getBasePtr();
11601
11602   // If this is a store of a bit convert, store the input value if the
11603   // resultant store does not need a higher alignment than the original.
11604   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11605       ST->isUnindexed()) {
11606     unsigned OrigAlign = ST->getAlignment();
11607     EVT SVT = Value.getOperand(0).getValueType();
11608     unsigned Align = DAG.getDataLayout().getABITypeAlignment(
11609         SVT.getTypeForEVT(*DAG.getContext()));
11610     if (Align <= OrigAlign &&
11611         ((!LegalOperations && !ST->isVolatile()) ||
11612          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11613       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11614                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11615                           ST->isNonTemporal(), OrigAlign,
11616                           ST->getAAInfo());
11617   }
11618
11619   // Turn 'store undef, Ptr' -> nothing.
11620   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11621     return Chain;
11622
11623   // Try to infer better alignment information than the store already has.
11624   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11625     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11626       if (Align > ST->getAlignment()) {
11627         SDValue NewStore =
11628                DAG.getTruncStore(Chain, SDLoc(N), Value,
11629                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11630                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11631                                  ST->getAAInfo());
11632         if (NewStore.getNode() != N)
11633           return CombineTo(ST, NewStore, true);
11634       }
11635     }
11636   }
11637
11638   // Try transforming a pair floating point load / store ops to integer
11639   // load / store ops.
11640   if (SDValue NewST = TransformFPLoadStorePair(N))
11641     return NewST;
11642
11643   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11644                                                   : DAG.getSubtarget().useAA();
11645 #ifndef NDEBUG
11646   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11647       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11648     UseAA = false;
11649 #endif
11650   if (UseAA && ST->isUnindexed()) {
11651     // FIXME: We should do this even without AA enabled. AA will just allow
11652     // FindBetterChain to work in more situations. The problem with this is that
11653     // any combine that expects memory operations to be on consecutive chains
11654     // first needs to be updated to look for users of the same chain.
11655
11656     // Walk up chain skipping non-aliasing memory nodes, on this store and any
11657     // adjacent stores.
11658     if (findBetterNeighborChains(ST)) {
11659       // replaceStoreChain uses CombineTo, which handled all of the worklist
11660       // manipulation. Return the original node to not do anything else.
11661       return SDValue(ST, 0);
11662     }
11663   }
11664
11665   // Try transforming N to an indexed store.
11666   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11667     return SDValue(N, 0);
11668
11669   // FIXME: is there such a thing as a truncating indexed store?
11670   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11671       Value.getValueType().isInteger()) {
11672     // See if we can simplify the input to this truncstore with knowledge that
11673     // only the low bits are being used.  For example:
11674     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11675     SDValue Shorter =
11676       GetDemandedBits(Value,
11677                       APInt::getLowBitsSet(
11678                         Value.getValueType().getScalarType().getSizeInBits(),
11679                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11680     AddToWorklist(Value.getNode());
11681     if (Shorter.getNode())
11682       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11683                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11684
11685     // Otherwise, see if we can simplify the operation with
11686     // SimplifyDemandedBits, which only works if the value has a single use.
11687     if (SimplifyDemandedBits(Value,
11688                         APInt::getLowBitsSet(
11689                           Value.getValueType().getScalarType().getSizeInBits(),
11690                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11691       return SDValue(N, 0);
11692   }
11693
11694   // If this is a load followed by a store to the same location, then the store
11695   // is dead/noop.
11696   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11697     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11698         ST->isUnindexed() && !ST->isVolatile() &&
11699         // There can't be any side effects between the load and store, such as
11700         // a call or store.
11701         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11702       // The store is dead, remove it.
11703       return Chain;
11704     }
11705   }
11706
11707   // If this is a store followed by a store with the same value to the same
11708   // location, then the store is dead/noop.
11709   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11710     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11711         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11712         ST1->isUnindexed() && !ST1->isVolatile()) {
11713       // The store is dead, remove it.
11714       return Chain;
11715     }
11716   }
11717
11718   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11719   // truncating store.  We can do this even if this is already a truncstore.
11720   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11721       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11722       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11723                             ST->getMemoryVT())) {
11724     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11725                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11726   }
11727
11728   // Only perform this optimization before the types are legal, because we
11729   // don't want to perform this optimization on every DAGCombine invocation.
11730   if (!LegalTypes) {
11731     bool EverChanged = false;
11732
11733     do {
11734       // There can be multiple store sequences on the same chain.
11735       // Keep trying to merge store sequences until we are unable to do so
11736       // or until we merge the last store on the chain.
11737       bool Changed = MergeConsecutiveStores(ST);
11738       EverChanged |= Changed;
11739       if (!Changed) break;
11740     } while (ST->getOpcode() != ISD::DELETED_NODE);
11741
11742     if (EverChanged)
11743       return SDValue(N, 0);
11744   }
11745
11746   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11747   //
11748   // Make sure to do this only after attempting to merge stores in order to
11749   //  avoid changing the types of some subset of stores due to visit order,
11750   //  preventing their merging.
11751   if (isa<ConstantFPSDNode>(Value)) {
11752     if (SDValue NewSt = replaceStoreOfFPConstant(ST))
11753       return NewSt;
11754   }
11755
11756   return ReduceLoadOpStoreWidth(N);
11757 }
11758
11759 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11760   SDValue InVec = N->getOperand(0);
11761   SDValue InVal = N->getOperand(1);
11762   SDValue EltNo = N->getOperand(2);
11763   SDLoc dl(N);
11764
11765   // If the inserted element is an UNDEF, just use the input vector.
11766   if (InVal.getOpcode() == ISD::UNDEF)
11767     return InVec;
11768
11769   EVT VT = InVec.getValueType();
11770
11771   // If we can't generate a legal BUILD_VECTOR, exit
11772   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11773     return SDValue();
11774
11775   // Check that we know which element is being inserted
11776   if (!isa<ConstantSDNode>(EltNo))
11777     return SDValue();
11778   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11779
11780   // Canonicalize insert_vector_elt dag nodes.
11781   // Example:
11782   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11783   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11784   //
11785   // Do this only if the child insert_vector node has one use; also
11786   // do this only if indices are both constants and Idx1 < Idx0.
11787   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11788       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11789     unsigned OtherElt =
11790       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11791     if (Elt < OtherElt) {
11792       // Swap nodes.
11793       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11794                                   InVec.getOperand(0), InVal, EltNo);
11795       AddToWorklist(NewOp.getNode());
11796       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11797                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11798     }
11799   }
11800
11801   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11802   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11803   // vector elements.
11804   SmallVector<SDValue, 8> Ops;
11805   // Do not combine these two vectors if the output vector will not replace
11806   // the input vector.
11807   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11808     Ops.append(InVec.getNode()->op_begin(),
11809                InVec.getNode()->op_end());
11810   } else if (InVec.getOpcode() == ISD::UNDEF) {
11811     unsigned NElts = VT.getVectorNumElements();
11812     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11813   } else {
11814     return SDValue();
11815   }
11816
11817   // Insert the element
11818   if (Elt < Ops.size()) {
11819     // All the operands of BUILD_VECTOR must have the same type;
11820     // we enforce that here.
11821     EVT OpVT = Ops[0].getValueType();
11822     if (InVal.getValueType() != OpVT)
11823       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11824                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11825                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11826     Ops[Elt] = InVal;
11827   }
11828
11829   // Return the new vector
11830   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11831 }
11832
11833 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11834     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11835   EVT ResultVT = EVE->getValueType(0);
11836   EVT VecEltVT = InVecVT.getVectorElementType();
11837   unsigned Align = OriginalLoad->getAlignment();
11838   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
11839       VecEltVT.getTypeForEVT(*DAG.getContext()));
11840
11841   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11842     return SDValue();
11843
11844   Align = NewAlign;
11845
11846   SDValue NewPtr = OriginalLoad->getBasePtr();
11847   SDValue Offset;
11848   EVT PtrType = NewPtr.getValueType();
11849   MachinePointerInfo MPI;
11850   SDLoc DL(EVE);
11851   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11852     int Elt = ConstEltNo->getZExtValue();
11853     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11854     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11855     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11856   } else {
11857     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11858     Offset = DAG.getNode(
11859         ISD::MUL, DL, PtrType, Offset,
11860         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11861     MPI = OriginalLoad->getPointerInfo();
11862   }
11863   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11864
11865   // The replacement we need to do here is a little tricky: we need to
11866   // replace an extractelement of a load with a load.
11867   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11868   // Note that this replacement assumes that the extractvalue is the only
11869   // use of the load; that's okay because we don't want to perform this
11870   // transformation in other cases anyway.
11871   SDValue Load;
11872   SDValue Chain;
11873   if (ResultVT.bitsGT(VecEltVT)) {
11874     // If the result type of vextract is wider than the load, then issue an
11875     // extending load instead.
11876     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11877                                                   VecEltVT)
11878                                    ? ISD::ZEXTLOAD
11879                                    : ISD::EXTLOAD;
11880     Load = DAG.getExtLoad(
11881         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11882         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11883         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11884     Chain = Load.getValue(1);
11885   } else {
11886     Load = DAG.getLoad(
11887         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11888         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11889         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11890     Chain = Load.getValue(1);
11891     if (ResultVT.bitsLT(VecEltVT))
11892       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11893     else
11894       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11895   }
11896   WorklistRemover DeadNodes(*this);
11897   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11898   SDValue To[] = { Load, Chain };
11899   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11900   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11901   // worklist explicitly as well.
11902   AddToWorklist(Load.getNode());
11903   AddUsersToWorklist(Load.getNode()); // Add users too
11904   // Make sure to revisit this node to clean it up; it will usually be dead.
11905   AddToWorklist(EVE);
11906   ++OpsNarrowed;
11907   return SDValue(EVE, 0);
11908 }
11909
11910 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11911   // (vextract (scalar_to_vector val, 0) -> val
11912   SDValue InVec = N->getOperand(0);
11913   EVT VT = InVec.getValueType();
11914   EVT NVT = N->getValueType(0);
11915
11916   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11917     // Check if the result type doesn't match the inserted element type. A
11918     // SCALAR_TO_VECTOR may truncate the inserted element and the
11919     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11920     SDValue InOp = InVec.getOperand(0);
11921     if (InOp.getValueType() != NVT) {
11922       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11923       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11924     }
11925     return InOp;
11926   }
11927
11928   SDValue EltNo = N->getOperand(1);
11929   ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
11930
11931   // extract_vector_elt (build_vector x, y), 1 -> y
11932   if (ConstEltNo &&
11933       InVec.getOpcode() == ISD::BUILD_VECTOR &&
11934       TLI.isTypeLegal(VT) &&
11935       (InVec.hasOneUse() ||
11936        TLI.aggressivelyPreferBuildVectorSources(VT))) {
11937     SDValue Elt = InVec.getOperand(ConstEltNo->getZExtValue());
11938     EVT InEltVT = Elt.getValueType();
11939
11940     // Sometimes build_vector's scalar input types do not match result type.
11941     if (NVT == InEltVT)
11942       return Elt;
11943
11944     // TODO: It may be useful to truncate if free if the build_vector implicitly
11945     // converts.
11946   }
11947
11948   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11949   // We only perform this optimization before the op legalization phase because
11950   // we may introduce new vector instructions which are not backed by TD
11951   // patterns. For example on AVX, extracting elements from a wide vector
11952   // without using extract_subvector. However, if we can find an underlying
11953   // scalar value, then we can always use that.
11954   if (ConstEltNo && InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
11955     int NumElem = VT.getVectorNumElements();
11956     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11957     // Find the new index to extract from.
11958     int OrigElt = SVOp->getMaskElt(ConstEltNo->getZExtValue());
11959
11960     // Extracting an undef index is undef.
11961     if (OrigElt == -1)
11962       return DAG.getUNDEF(NVT);
11963
11964     // Select the right vector half to extract from.
11965     SDValue SVInVec;
11966     if (OrigElt < NumElem) {
11967       SVInVec = InVec->getOperand(0);
11968     } else {
11969       SVInVec = InVec->getOperand(1);
11970       OrigElt -= NumElem;
11971     }
11972
11973     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11974       SDValue InOp = SVInVec.getOperand(OrigElt);
11975       if (InOp.getValueType() != NVT) {
11976         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11977         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11978       }
11979
11980       return InOp;
11981     }
11982
11983     // FIXME: We should handle recursing on other vector shuffles and
11984     // scalar_to_vector here as well.
11985
11986     if (!LegalOperations) {
11987       EVT IndexTy = TLI.getVectorIdxTy(DAG.getDataLayout());
11988       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11989                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11990     }
11991   }
11992
11993   bool BCNumEltsChanged = false;
11994   EVT ExtVT = VT.getVectorElementType();
11995   EVT LVT = ExtVT;
11996
11997   // If the result of load has to be truncated, then it's not necessarily
11998   // profitable.
11999   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
12000     return SDValue();
12001
12002   if (InVec.getOpcode() == ISD::BITCAST) {
12003     // Don't duplicate a load with other uses.
12004     if (!InVec.hasOneUse())
12005       return SDValue();
12006
12007     EVT BCVT = InVec.getOperand(0).getValueType();
12008     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
12009       return SDValue();
12010     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
12011       BCNumEltsChanged = true;
12012     InVec = InVec.getOperand(0);
12013     ExtVT = BCVT.getVectorElementType();
12014   }
12015
12016   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
12017   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
12018       ISD::isNormalLoad(InVec.getNode()) &&
12019       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
12020     SDValue Index = N->getOperand(1);
12021     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
12022       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
12023                                                            OrigLoad);
12024   }
12025
12026   // Perform only after legalization to ensure build_vector / vector_shuffle
12027   // optimizations have already been done.
12028   if (!LegalOperations) return SDValue();
12029
12030   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
12031   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
12032   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
12033
12034   if (ConstEltNo) {
12035     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
12036
12037     LoadSDNode *LN0 = nullptr;
12038     const ShuffleVectorSDNode *SVN = nullptr;
12039     if (ISD::isNormalLoad(InVec.getNode())) {
12040       LN0 = cast<LoadSDNode>(InVec);
12041     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
12042                InVec.getOperand(0).getValueType() == ExtVT &&
12043                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
12044       // Don't duplicate a load with other uses.
12045       if (!InVec.hasOneUse())
12046         return SDValue();
12047
12048       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
12049     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
12050       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
12051       // =>
12052       // (load $addr+1*size)
12053
12054       // Don't duplicate a load with other uses.
12055       if (!InVec.hasOneUse())
12056         return SDValue();
12057
12058       // If the bit convert changed the number of elements, it is unsafe
12059       // to examine the mask.
12060       if (BCNumEltsChanged)
12061         return SDValue();
12062
12063       // Select the input vector, guarding against out of range extract vector.
12064       unsigned NumElems = VT.getVectorNumElements();
12065       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
12066       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
12067
12068       if (InVec.getOpcode() == ISD::BITCAST) {
12069         // Don't duplicate a load with other uses.
12070         if (!InVec.hasOneUse())
12071           return SDValue();
12072
12073         InVec = InVec.getOperand(0);
12074       }
12075       if (ISD::isNormalLoad(InVec.getNode())) {
12076         LN0 = cast<LoadSDNode>(InVec);
12077         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
12078         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
12079       }
12080     }
12081
12082     // Make sure we found a non-volatile load and the extractelement is
12083     // the only use.
12084     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
12085       return SDValue();
12086
12087     // If Idx was -1 above, Elt is going to be -1, so just return undef.
12088     if (Elt == -1)
12089       return DAG.getUNDEF(LVT);
12090
12091     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
12092   }
12093
12094   return SDValue();
12095 }
12096
12097 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
12098 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
12099   // We perform this optimization post type-legalization because
12100   // the type-legalizer often scalarizes integer-promoted vectors.
12101   // Performing this optimization before may create bit-casts which
12102   // will be type-legalized to complex code sequences.
12103   // We perform this optimization only before the operation legalizer because we
12104   // may introduce illegal operations.
12105   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
12106     return SDValue();
12107
12108   unsigned NumInScalars = N->getNumOperands();
12109   SDLoc dl(N);
12110   EVT VT = N->getValueType(0);
12111
12112   // Check to see if this is a BUILD_VECTOR of a bunch of values
12113   // which come from any_extend or zero_extend nodes. If so, we can create
12114   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
12115   // optimizations. We do not handle sign-extend because we can't fill the sign
12116   // using shuffles.
12117   EVT SourceType = MVT::Other;
12118   bool AllAnyExt = true;
12119
12120   for (unsigned i = 0; i != NumInScalars; ++i) {
12121     SDValue In = N->getOperand(i);
12122     // Ignore undef inputs.
12123     if (In.getOpcode() == ISD::UNDEF) continue;
12124
12125     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
12126     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
12127
12128     // Abort if the element is not an extension.
12129     if (!ZeroExt && !AnyExt) {
12130       SourceType = MVT::Other;
12131       break;
12132     }
12133
12134     // The input is a ZeroExt or AnyExt. Check the original type.
12135     EVT InTy = In.getOperand(0).getValueType();
12136
12137     // Check that all of the widened source types are the same.
12138     if (SourceType == MVT::Other)
12139       // First time.
12140       SourceType = InTy;
12141     else if (InTy != SourceType) {
12142       // Multiple income types. Abort.
12143       SourceType = MVT::Other;
12144       break;
12145     }
12146
12147     // Check if all of the extends are ANY_EXTENDs.
12148     AllAnyExt &= AnyExt;
12149   }
12150
12151   // In order to have valid types, all of the inputs must be extended from the
12152   // same source type and all of the inputs must be any or zero extend.
12153   // Scalar sizes must be a power of two.
12154   EVT OutScalarTy = VT.getScalarType();
12155   bool ValidTypes = SourceType != MVT::Other &&
12156                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
12157                  isPowerOf2_32(SourceType.getSizeInBits());
12158
12159   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
12160   // turn into a single shuffle instruction.
12161   if (!ValidTypes)
12162     return SDValue();
12163
12164   bool isLE = DAG.getDataLayout().isLittleEndian();
12165   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
12166   assert(ElemRatio > 1 && "Invalid element size ratio");
12167   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
12168                                DAG.getConstant(0, SDLoc(N), SourceType);
12169
12170   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
12171   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
12172
12173   // Populate the new build_vector
12174   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12175     SDValue Cast = N->getOperand(i);
12176     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
12177             Cast.getOpcode() == ISD::ZERO_EXTEND ||
12178             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
12179     SDValue In;
12180     if (Cast.getOpcode() == ISD::UNDEF)
12181       In = DAG.getUNDEF(SourceType);
12182     else
12183       In = Cast->getOperand(0);
12184     unsigned Index = isLE ? (i * ElemRatio) :
12185                             (i * ElemRatio + (ElemRatio - 1));
12186
12187     assert(Index < Ops.size() && "Invalid index");
12188     Ops[Index] = In;
12189   }
12190
12191   // The type of the new BUILD_VECTOR node.
12192   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
12193   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
12194          "Invalid vector size");
12195   // Check if the new vector type is legal.
12196   if (!isTypeLegal(VecVT)) return SDValue();
12197
12198   // Make the new BUILD_VECTOR.
12199   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
12200
12201   // The new BUILD_VECTOR node has the potential to be further optimized.
12202   AddToWorklist(BV.getNode());
12203   // Bitcast to the desired type.
12204   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
12205 }
12206
12207 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
12208   EVT VT = N->getValueType(0);
12209
12210   unsigned NumInScalars = N->getNumOperands();
12211   SDLoc dl(N);
12212
12213   EVT SrcVT = MVT::Other;
12214   unsigned Opcode = ISD::DELETED_NODE;
12215   unsigned NumDefs = 0;
12216
12217   for (unsigned i = 0; i != NumInScalars; ++i) {
12218     SDValue In = N->getOperand(i);
12219     unsigned Opc = In.getOpcode();
12220
12221     if (Opc == ISD::UNDEF)
12222       continue;
12223
12224     // If all scalar values are floats and converted from integers.
12225     if (Opcode == ISD::DELETED_NODE &&
12226         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
12227       Opcode = Opc;
12228     }
12229
12230     if (Opc != Opcode)
12231       return SDValue();
12232
12233     EVT InVT = In.getOperand(0).getValueType();
12234
12235     // If all scalar values are typed differently, bail out. It's chosen to
12236     // simplify BUILD_VECTOR of integer types.
12237     if (SrcVT == MVT::Other)
12238       SrcVT = InVT;
12239     if (SrcVT != InVT)
12240       return SDValue();
12241     NumDefs++;
12242   }
12243
12244   // If the vector has just one element defined, it's not worth to fold it into
12245   // a vectorized one.
12246   if (NumDefs < 2)
12247     return SDValue();
12248
12249   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
12250          && "Should only handle conversion from integer to float.");
12251   assert(SrcVT != MVT::Other && "Cannot determine source type!");
12252
12253   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
12254
12255   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
12256     return SDValue();
12257
12258   // Just because the floating-point vector type is legal does not necessarily
12259   // mean that the corresponding integer vector type is.
12260   if (!isTypeLegal(NVT))
12261     return SDValue();
12262
12263   SmallVector<SDValue, 8> Opnds;
12264   for (unsigned i = 0; i != NumInScalars; ++i) {
12265     SDValue In = N->getOperand(i);
12266
12267     if (In.getOpcode() == ISD::UNDEF)
12268       Opnds.push_back(DAG.getUNDEF(SrcVT));
12269     else
12270       Opnds.push_back(In.getOperand(0));
12271   }
12272   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
12273   AddToWorklist(BV.getNode());
12274
12275   return DAG.getNode(Opcode, dl, VT, BV);
12276 }
12277
12278 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
12279   unsigned NumInScalars = N->getNumOperands();
12280   SDLoc dl(N);
12281   EVT VT = N->getValueType(0);
12282
12283   // A vector built entirely of undefs is undef.
12284   if (ISD::allOperandsUndef(N))
12285     return DAG.getUNDEF(VT);
12286
12287   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
12288     return V;
12289
12290   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
12291     return V;
12292
12293   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
12294   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
12295   // at most two distinct vectors, turn this into a shuffle node.
12296
12297   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
12298   if (!isTypeLegal(VT))
12299     return SDValue();
12300
12301   // May only combine to shuffle after legalize if shuffle is legal.
12302   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
12303     return SDValue();
12304
12305   SDValue VecIn1, VecIn2;
12306   bool UsesZeroVector = false;
12307   for (unsigned i = 0; i != NumInScalars; ++i) {
12308     SDValue Op = N->getOperand(i);
12309     // Ignore undef inputs.
12310     if (Op.getOpcode() == ISD::UNDEF) continue;
12311
12312     // See if we can combine this build_vector into a blend with a zero vector.
12313     if (!VecIn2.getNode() && (isNullConstant(Op) || isNullFPConstant(Op))) {
12314       UsesZeroVector = true;
12315       continue;
12316     }
12317
12318     // If this input is something other than a EXTRACT_VECTOR_ELT with a
12319     // constant index, bail out.
12320     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
12321         !isa<ConstantSDNode>(Op.getOperand(1))) {
12322       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12323       break;
12324     }
12325
12326     // We allow up to two distinct input vectors.
12327     SDValue ExtractedFromVec = Op.getOperand(0);
12328     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
12329       continue;
12330
12331     if (!VecIn1.getNode()) {
12332       VecIn1 = ExtractedFromVec;
12333     } else if (!VecIn2.getNode() && !UsesZeroVector) {
12334       VecIn2 = ExtractedFromVec;
12335     } else {
12336       // Too many inputs.
12337       VecIn1 = VecIn2 = SDValue(nullptr, 0);
12338       break;
12339     }
12340   }
12341
12342   // If everything is good, we can make a shuffle operation.
12343   if (VecIn1.getNode()) {
12344     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
12345     SmallVector<int, 8> Mask;
12346     for (unsigned i = 0; i != NumInScalars; ++i) {
12347       unsigned Opcode = N->getOperand(i).getOpcode();
12348       if (Opcode == ISD::UNDEF) {
12349         Mask.push_back(-1);
12350         continue;
12351       }
12352
12353       // Operands can also be zero.
12354       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
12355         assert(UsesZeroVector &&
12356                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
12357                "Unexpected node found!");
12358         Mask.push_back(NumInScalars+i);
12359         continue;
12360       }
12361
12362       // If extracting from the first vector, just use the index directly.
12363       SDValue Extract = N->getOperand(i);
12364       SDValue ExtVal = Extract.getOperand(1);
12365       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
12366       if (Extract.getOperand(0) == VecIn1) {
12367         Mask.push_back(ExtIndex);
12368         continue;
12369       }
12370
12371       // Otherwise, use InIdx + InputVecSize
12372       Mask.push_back(InNumElements + ExtIndex);
12373     }
12374
12375     // Avoid introducing illegal shuffles with zero.
12376     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
12377       return SDValue();
12378
12379     // We can't generate a shuffle node with mismatched input and output types.
12380     // Attempt to transform a single input vector to the correct type.
12381     if ((VT != VecIn1.getValueType())) {
12382       // If the input vector type has a different base type to the output
12383       // vector type, bail out.
12384       EVT VTElemType = VT.getVectorElementType();
12385       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
12386           (VecIn2.getNode() &&
12387            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
12388         return SDValue();
12389
12390       // If the input vector is too small, widen it.
12391       // We only support widening of vectors which are half the size of the
12392       // output registers. For example XMM->YMM widening on X86 with AVX.
12393       EVT VecInT = VecIn1.getValueType();
12394       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
12395         // If we only have one small input, widen it by adding undef values.
12396         if (!VecIn2.getNode())
12397           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
12398                                DAG.getUNDEF(VecIn1.getValueType()));
12399         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
12400           // If we have two small inputs of the same type, try to concat them.
12401           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
12402           VecIn2 = SDValue(nullptr, 0);
12403         } else
12404           return SDValue();
12405       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
12406         // If the input vector is too large, try to split it.
12407         // We don't support having two input vectors that are too large.
12408         // If the zero vector was used, we can not split the vector,
12409         // since we'd need 3 inputs.
12410         if (UsesZeroVector || VecIn2.getNode())
12411           return SDValue();
12412
12413         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
12414           return SDValue();
12415
12416         // Try to replace VecIn1 with two extract_subvectors
12417         // No need to update the masks, they should still be correct.
12418         VecIn2 = DAG.getNode(
12419             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12420             DAG.getConstant(VT.getVectorNumElements(), dl,
12421                             TLI.getVectorIdxTy(DAG.getDataLayout())));
12422         VecIn1 = DAG.getNode(
12423             ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
12424             DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
12425       } else
12426         return SDValue();
12427     }
12428
12429     if (UsesZeroVector)
12430       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
12431                                 DAG.getConstantFP(0.0, dl, VT);
12432     else
12433       // If VecIn2 is unused then change it to undef.
12434       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
12435
12436     // Check that we were able to transform all incoming values to the same
12437     // type.
12438     if (VecIn2.getValueType() != VecIn1.getValueType() ||
12439         VecIn1.getValueType() != VT)
12440           return SDValue();
12441
12442     // Return the new VECTOR_SHUFFLE node.
12443     SDValue Ops[2];
12444     Ops[0] = VecIn1;
12445     Ops[1] = VecIn2;
12446     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
12447   }
12448
12449   return SDValue();
12450 }
12451
12452 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12453   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12454   EVT OpVT = N->getOperand(0).getValueType();
12455
12456   // If the operands are legal vectors, leave them alone.
12457   if (TLI.isTypeLegal(OpVT))
12458     return SDValue();
12459
12460   SDLoc DL(N);
12461   EVT VT = N->getValueType(0);
12462   SmallVector<SDValue, 8> Ops;
12463
12464   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12465   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12466
12467   // Keep track of what we encounter.
12468   bool AnyInteger = false;
12469   bool AnyFP = false;
12470   for (const SDValue &Op : N->ops()) {
12471     if (ISD::BITCAST == Op.getOpcode() &&
12472         !Op.getOperand(0).getValueType().isVector())
12473       Ops.push_back(Op.getOperand(0));
12474     else if (ISD::UNDEF == Op.getOpcode())
12475       Ops.push_back(ScalarUndef);
12476     else
12477       return SDValue();
12478
12479     // Note whether we encounter an integer or floating point scalar.
12480     // If it's neither, bail out, it could be something weird like x86mmx.
12481     EVT LastOpVT = Ops.back().getValueType();
12482     if (LastOpVT.isFloatingPoint())
12483       AnyFP = true;
12484     else if (LastOpVT.isInteger())
12485       AnyInteger = true;
12486     else
12487       return SDValue();
12488   }
12489
12490   // If any of the operands is a floating point scalar bitcast to a vector,
12491   // use floating point types throughout, and bitcast everything.
12492   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12493   if (AnyFP) {
12494     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12495     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12496     if (AnyInteger) {
12497       for (SDValue &Op : Ops) {
12498         if (Op.getValueType() == SVT)
12499           continue;
12500         if (Op.getOpcode() == ISD::UNDEF)
12501           Op = ScalarUndef;
12502         else
12503           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12504       }
12505     }
12506   }
12507
12508   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12509                                VT.getSizeInBits() / SVT.getSizeInBits());
12510   return DAG.getNode(ISD::BITCAST, DL, VT,
12511                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12512 }
12513
12514 // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
12515 // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
12516 // most two distinct vectors the same size as the result, attempt to turn this
12517 // into a legal shuffle.
12518 static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
12519   EVT VT = N->getValueType(0);
12520   EVT OpVT = N->getOperand(0).getValueType();
12521   int NumElts = VT.getVectorNumElements();
12522   int NumOpElts = OpVT.getVectorNumElements();
12523
12524   SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
12525   SmallVector<int, 8> Mask;
12526
12527   for (SDValue Op : N->ops()) {
12528     // Peek through any bitcast.
12529     while (Op.getOpcode() == ISD::BITCAST)
12530       Op = Op.getOperand(0);
12531
12532     // UNDEF nodes convert to UNDEF shuffle mask values.
12533     if (Op.getOpcode() == ISD::UNDEF) {
12534       Mask.append((unsigned)NumOpElts, -1);
12535       continue;
12536     }
12537
12538     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12539       return SDValue();
12540
12541     // What vector are we extracting the subvector from and at what index?
12542     SDValue ExtVec = Op.getOperand(0);
12543
12544     // We want the EVT of the original extraction to correctly scale the
12545     // extraction index.
12546     EVT ExtVT = ExtVec.getValueType();
12547
12548     // Peek through any bitcast.
12549     while (ExtVec.getOpcode() == ISD::BITCAST)
12550       ExtVec = ExtVec.getOperand(0);
12551
12552     // UNDEF nodes convert to UNDEF shuffle mask values.
12553     if (ExtVec.getOpcode() == ISD::UNDEF) {
12554       Mask.append((unsigned)NumOpElts, -1);
12555       continue;
12556     }
12557
12558     if (!isa<ConstantSDNode>(Op.getOperand(1)))
12559       return SDValue();
12560     int ExtIdx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12561
12562     // Ensure that we are extracting a subvector from a vector the same
12563     // size as the result.
12564     if (ExtVT.getSizeInBits() != VT.getSizeInBits())
12565       return SDValue();
12566
12567     // Scale the subvector index to account for any bitcast.
12568     int NumExtElts = ExtVT.getVectorNumElements();
12569     if (0 == (NumExtElts % NumElts))
12570       ExtIdx /= (NumExtElts / NumElts);
12571     else if (0 == (NumElts % NumExtElts))
12572       ExtIdx *= (NumElts / NumExtElts);
12573     else
12574       return SDValue();
12575
12576     // At most we can reference 2 inputs in the final shuffle.
12577     if (SV0.getOpcode() == ISD::UNDEF || SV0 == ExtVec) {
12578       SV0 = ExtVec;
12579       for (int i = 0; i != NumOpElts; ++i)
12580         Mask.push_back(i + ExtIdx);
12581     } else if (SV1.getOpcode() == ISD::UNDEF || SV1 == ExtVec) {
12582       SV1 = ExtVec;
12583       for (int i = 0; i != NumOpElts; ++i)
12584         Mask.push_back(i + ExtIdx + NumElts);
12585     } else {
12586       return SDValue();
12587     }
12588   }
12589
12590   if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(Mask, VT))
12591     return SDValue();
12592
12593   return DAG.getVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
12594                               DAG.getBitcast(VT, SV1), Mask);
12595 }
12596
12597 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12598   // If we only have one input vector, we don't need to do any concatenation.
12599   if (N->getNumOperands() == 1)
12600     return N->getOperand(0);
12601
12602   // Check if all of the operands are undefs.
12603   EVT VT = N->getValueType(0);
12604   if (ISD::allOperandsUndef(N))
12605     return DAG.getUNDEF(VT);
12606
12607   // Optimize concat_vectors where all but the first of the vectors are undef.
12608   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12609         return Op.getOpcode() == ISD::UNDEF;
12610       })) {
12611     SDValue In = N->getOperand(0);
12612     assert(In.getValueType().isVector() && "Must concat vectors");
12613
12614     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12615     if (In->getOpcode() == ISD::BITCAST &&
12616         !In->getOperand(0)->getValueType(0).isVector()) {
12617       SDValue Scalar = In->getOperand(0);
12618
12619       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12620       // look through the trunc so we can still do the transform:
12621       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12622       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12623           !TLI.isTypeLegal(Scalar.getValueType()) &&
12624           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12625         Scalar = Scalar->getOperand(0);
12626
12627       EVT SclTy = Scalar->getValueType(0);
12628
12629       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12630         return SDValue();
12631
12632       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12633                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12634       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12635         return SDValue();
12636
12637       SDLoc dl = SDLoc(N);
12638       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12639       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12640     }
12641   }
12642
12643   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12644   // We have already tested above for an UNDEF only concatenation.
12645   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12646   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12647   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12648     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12649   };
12650   bool AllBuildVectorsOrUndefs =
12651       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12652   if (AllBuildVectorsOrUndefs) {
12653     SmallVector<SDValue, 8> Opnds;
12654     EVT SVT = VT.getScalarType();
12655
12656     EVT MinVT = SVT;
12657     if (!SVT.isFloatingPoint()) {
12658       // If BUILD_VECTOR are from built from integer, they may have different
12659       // operand types. Get the smallest type and truncate all operands to it.
12660       bool FoundMinVT = false;
12661       for (const SDValue &Op : N->ops())
12662         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12663           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12664           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12665           FoundMinVT = true;
12666         }
12667       assert(FoundMinVT && "Concat vector type mismatch");
12668     }
12669
12670     for (const SDValue &Op : N->ops()) {
12671       EVT OpVT = Op.getValueType();
12672       unsigned NumElts = OpVT.getVectorNumElements();
12673
12674       if (ISD::UNDEF == Op.getOpcode())
12675         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12676
12677       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12678         if (SVT.isFloatingPoint()) {
12679           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12680           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12681         } else {
12682           for (unsigned i = 0; i != NumElts; ++i)
12683             Opnds.push_back(
12684                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12685         }
12686       }
12687     }
12688
12689     assert(VT.getVectorNumElements() == Opnds.size() &&
12690            "Concat vector type mismatch");
12691     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12692   }
12693
12694   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12695   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12696     return V;
12697
12698   // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
12699   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT))
12700     if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
12701       return V;
12702
12703   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12704   // nodes often generate nop CONCAT_VECTOR nodes.
12705   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12706   // place the incoming vectors at the exact same location.
12707   SDValue SingleSource = SDValue();
12708   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12709
12710   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12711     SDValue Op = N->getOperand(i);
12712
12713     if (Op.getOpcode() == ISD::UNDEF)
12714       continue;
12715
12716     // Check if this is the identity extract:
12717     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12718       return SDValue();
12719
12720     // Find the single incoming vector for the extract_subvector.
12721     if (SingleSource.getNode()) {
12722       if (Op.getOperand(0) != SingleSource)
12723         return SDValue();
12724     } else {
12725       SingleSource = Op.getOperand(0);
12726
12727       // Check the source type is the same as the type of the result.
12728       // If not, this concat may extend the vector, so we can not
12729       // optimize it away.
12730       if (SingleSource.getValueType() != N->getValueType(0))
12731         return SDValue();
12732     }
12733
12734     unsigned IdentityIndex = i * PartNumElem;
12735     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12736     // The extract index must be constant.
12737     if (!CS)
12738       return SDValue();
12739
12740     // Check that we are reading from the identity index.
12741     if (CS->getZExtValue() != IdentityIndex)
12742       return SDValue();
12743   }
12744
12745   if (SingleSource.getNode())
12746     return SingleSource;
12747
12748   return SDValue();
12749 }
12750
12751 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12752   EVT NVT = N->getValueType(0);
12753   SDValue V = N->getOperand(0);
12754
12755   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12756     // Combine:
12757     //    (extract_subvec (concat V1, V2, ...), i)
12758     // Into:
12759     //    Vi if possible
12760     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12761     // type.
12762     if (V->getOperand(0).getValueType() != NVT)
12763       return SDValue();
12764     unsigned Idx = N->getConstantOperandVal(1);
12765     unsigned NumElems = NVT.getVectorNumElements();
12766     assert((Idx % NumElems) == 0 &&
12767            "IDX in concat is not a multiple of the result vector length.");
12768     return V->getOperand(Idx / NumElems);
12769   }
12770
12771   // Skip bitcasting
12772   if (V->getOpcode() == ISD::BITCAST)
12773     V = V.getOperand(0);
12774
12775   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12776     SDLoc dl(N);
12777     // Handle only simple case where vector being inserted and vector
12778     // being extracted are of same type, and are half size of larger vectors.
12779     EVT BigVT = V->getOperand(0).getValueType();
12780     EVT SmallVT = V->getOperand(1).getValueType();
12781     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12782       return SDValue();
12783
12784     // Only handle cases where both indexes are constants with the same type.
12785     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12786     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12787
12788     if (InsIdx && ExtIdx &&
12789         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12790         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12791       // Combine:
12792       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12793       // Into:
12794       //    indices are equal or bit offsets are equal => V1
12795       //    otherwise => (extract_subvec V1, ExtIdx)
12796       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12797           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12798         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12799       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12800                          DAG.getNode(ISD::BITCAST, dl,
12801                                      N->getOperand(0).getValueType(),
12802                                      V->getOperand(0)), N->getOperand(1));
12803     }
12804   }
12805
12806   return SDValue();
12807 }
12808
12809 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12810                                                  SDValue V, SelectionDAG &DAG) {
12811   SDLoc DL(V);
12812   EVT VT = V.getValueType();
12813
12814   switch (V.getOpcode()) {
12815   default:
12816     return V;
12817
12818   case ISD::CONCAT_VECTORS: {
12819     EVT OpVT = V->getOperand(0).getValueType();
12820     int OpSize = OpVT.getVectorNumElements();
12821     SmallBitVector OpUsedElements(OpSize, false);
12822     bool FoundSimplification = false;
12823     SmallVector<SDValue, 4> NewOps;
12824     NewOps.reserve(V->getNumOperands());
12825     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12826       SDValue Op = V->getOperand(i);
12827       bool OpUsed = false;
12828       for (int j = 0; j < OpSize; ++j)
12829         if (UsedElements[i * OpSize + j]) {
12830           OpUsedElements[j] = true;
12831           OpUsed = true;
12832         }
12833       NewOps.push_back(
12834           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12835                  : DAG.getUNDEF(OpVT));
12836       FoundSimplification |= Op == NewOps.back();
12837       OpUsedElements.reset();
12838     }
12839     if (FoundSimplification)
12840       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12841     return V;
12842   }
12843
12844   case ISD::INSERT_SUBVECTOR: {
12845     SDValue BaseV = V->getOperand(0);
12846     SDValue SubV = V->getOperand(1);
12847     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12848     if (!IdxN)
12849       return V;
12850
12851     int SubSize = SubV.getValueType().getVectorNumElements();
12852     int Idx = IdxN->getZExtValue();
12853     bool SubVectorUsed = false;
12854     SmallBitVector SubUsedElements(SubSize, false);
12855     for (int i = 0; i < SubSize; ++i)
12856       if (UsedElements[i + Idx]) {
12857         SubVectorUsed = true;
12858         SubUsedElements[i] = true;
12859         UsedElements[i + Idx] = false;
12860       }
12861
12862     // Now recurse on both the base and sub vectors.
12863     SDValue SimplifiedSubV =
12864         SubVectorUsed
12865             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12866             : DAG.getUNDEF(SubV.getValueType());
12867     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12868     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12869       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12870                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12871     return V;
12872   }
12873   }
12874 }
12875
12876 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12877                                        SDValue N1, SelectionDAG &DAG) {
12878   EVT VT = SVN->getValueType(0);
12879   int NumElts = VT.getVectorNumElements();
12880   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12881   for (int M : SVN->getMask())
12882     if (M >= 0 && M < NumElts)
12883       N0UsedElements[M] = true;
12884     else if (M >= NumElts)
12885       N1UsedElements[M - NumElts] = true;
12886
12887   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12888   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12889   if (S0 == N0 && S1 == N1)
12890     return SDValue();
12891
12892   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12893 }
12894
12895 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12896 // or turn a shuffle of a single concat into simpler shuffle then concat.
12897 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12898   EVT VT = N->getValueType(0);
12899   unsigned NumElts = VT.getVectorNumElements();
12900
12901   SDValue N0 = N->getOperand(0);
12902   SDValue N1 = N->getOperand(1);
12903   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12904
12905   SmallVector<SDValue, 4> Ops;
12906   EVT ConcatVT = N0.getOperand(0).getValueType();
12907   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12908   unsigned NumConcats = NumElts / NumElemsPerConcat;
12909
12910   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12911   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12912   // half vector elements.
12913   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12914       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12915                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12916     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12917                               makeArrayRef(SVN->getMask().begin(), NumElemsPerConcat));
12918     N1 = DAG.getUNDEF(ConcatVT);
12919     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12920   }
12921
12922   // Look at every vector that's inserted. We're looking for exact
12923   // subvector-sized copies from a concatenated vector
12924   for (unsigned I = 0; I != NumConcats; ++I) {
12925     // Make sure we're dealing with a copy.
12926     unsigned Begin = I * NumElemsPerConcat;
12927     bool AllUndef = true, NoUndef = true;
12928     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12929       if (SVN->getMaskElt(J) >= 0)
12930         AllUndef = false;
12931       else
12932         NoUndef = false;
12933     }
12934
12935     if (NoUndef) {
12936       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12937         return SDValue();
12938
12939       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12940         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12941           return SDValue();
12942
12943       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12944       if (FirstElt < N0.getNumOperands())
12945         Ops.push_back(N0.getOperand(FirstElt));
12946       else
12947         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12948
12949     } else if (AllUndef) {
12950       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12951     } else { // Mixed with general masks and undefs, can't do optimization.
12952       return SDValue();
12953     }
12954   }
12955
12956   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12957 }
12958
12959 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12960   EVT VT = N->getValueType(0);
12961   unsigned NumElts = VT.getVectorNumElements();
12962
12963   SDValue N0 = N->getOperand(0);
12964   SDValue N1 = N->getOperand(1);
12965
12966   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12967
12968   // Canonicalize shuffle undef, undef -> undef
12969   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12970     return DAG.getUNDEF(VT);
12971
12972   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12973
12974   // Canonicalize shuffle v, v -> v, undef
12975   if (N0 == N1) {
12976     SmallVector<int, 8> NewMask;
12977     for (unsigned i = 0; i != NumElts; ++i) {
12978       int Idx = SVN->getMaskElt(i);
12979       if (Idx >= (int)NumElts) Idx -= NumElts;
12980       NewMask.push_back(Idx);
12981     }
12982     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12983                                 &NewMask[0]);
12984   }
12985
12986   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12987   if (N0.getOpcode() == ISD::UNDEF) {
12988     SmallVector<int, 8> NewMask;
12989     for (unsigned i = 0; i != NumElts; ++i) {
12990       int Idx = SVN->getMaskElt(i);
12991       if (Idx >= 0) {
12992         if (Idx >= (int)NumElts)
12993           Idx -= NumElts;
12994         else
12995           Idx = -1; // remove reference to lhs
12996       }
12997       NewMask.push_back(Idx);
12998     }
12999     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
13000                                 &NewMask[0]);
13001   }
13002
13003   // Remove references to rhs if it is undef
13004   if (N1.getOpcode() == ISD::UNDEF) {
13005     bool Changed = false;
13006     SmallVector<int, 8> NewMask;
13007     for (unsigned i = 0; i != NumElts; ++i) {
13008       int Idx = SVN->getMaskElt(i);
13009       if (Idx >= (int)NumElts) {
13010         Idx = -1;
13011         Changed = true;
13012       }
13013       NewMask.push_back(Idx);
13014     }
13015     if (Changed)
13016       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
13017   }
13018
13019   // If it is a splat, check if the argument vector is another splat or a
13020   // build_vector.
13021   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
13022     SDNode *V = N0.getNode();
13023
13024     // If this is a bit convert that changes the element type of the vector but
13025     // not the number of vector elements, look through it.  Be careful not to
13026     // look though conversions that change things like v4f32 to v2f64.
13027     if (V->getOpcode() == ISD::BITCAST) {
13028       SDValue ConvInput = V->getOperand(0);
13029       if (ConvInput.getValueType().isVector() &&
13030           ConvInput.getValueType().getVectorNumElements() == NumElts)
13031         V = ConvInput.getNode();
13032     }
13033
13034     if (V->getOpcode() == ISD::BUILD_VECTOR) {
13035       assert(V->getNumOperands() == NumElts &&
13036              "BUILD_VECTOR has wrong number of operands");
13037       SDValue Base;
13038       bool AllSame = true;
13039       for (unsigned i = 0; i != NumElts; ++i) {
13040         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
13041           Base = V->getOperand(i);
13042           break;
13043         }
13044       }
13045       // Splat of <u, u, u, u>, return <u, u, u, u>
13046       if (!Base.getNode())
13047         return N0;
13048       for (unsigned i = 0; i != NumElts; ++i) {
13049         if (V->getOperand(i) != Base) {
13050           AllSame = false;
13051           break;
13052         }
13053       }
13054       // Splat of <x, x, x, x>, return <x, x, x, x>
13055       if (AllSame)
13056         return N0;
13057
13058       // Canonicalize any other splat as a build_vector.
13059       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
13060       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
13061       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
13062                                   V->getValueType(0), Ops);
13063
13064       // We may have jumped through bitcasts, so the type of the
13065       // BUILD_VECTOR may not match the type of the shuffle.
13066       if (V->getValueType(0) != VT)
13067         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
13068       return NewBV;
13069     }
13070   }
13071
13072   // There are various patterns used to build up a vector from smaller vectors,
13073   // subvectors, or elements. Scan chains of these and replace unused insertions
13074   // or components with undef.
13075   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
13076     return S;
13077
13078   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13079       Level < AfterLegalizeVectorOps &&
13080       (N1.getOpcode() == ISD::UNDEF ||
13081       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
13082        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
13083     SDValue V = partitionShuffleOfConcats(N, DAG);
13084
13085     if (V.getNode())
13086       return V;
13087   }
13088
13089   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
13090   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
13091   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
13092     SmallVector<SDValue, 8> Ops;
13093     for (int M : SVN->getMask()) {
13094       SDValue Op = DAG.getUNDEF(VT.getScalarType());
13095       if (M >= 0) {
13096         int Idx = M % NumElts;
13097         SDValue &S = (M < (int)NumElts ? N0 : N1);
13098         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
13099           Op = S.getOperand(Idx);
13100         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
13101           if (Idx == 0)
13102             Op = S.getOperand(0);
13103         } else {
13104           // Operand can't be combined - bail out.
13105           break;
13106         }
13107       }
13108       Ops.push_back(Op);
13109     }
13110     if (Ops.size() == VT.getVectorNumElements()) {
13111       // BUILD_VECTOR requires all inputs to be of the same type, find the
13112       // maximum type and extend them all.
13113       EVT SVT = VT.getScalarType();
13114       if (SVT.isInteger())
13115         for (SDValue &Op : Ops)
13116           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
13117       if (SVT != VT.getScalarType())
13118         for (SDValue &Op : Ops)
13119           Op = TLI.isZExtFree(Op.getValueType(), SVT)
13120                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
13121                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
13122       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
13123     }
13124   }
13125
13126   // If this shuffle only has a single input that is a bitcasted shuffle,
13127   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
13128   // back to their original types.
13129   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
13130       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
13131       TLI.isTypeLegal(VT)) {
13132
13133     // Peek through the bitcast only if there is one user.
13134     SDValue BC0 = N0;
13135     while (BC0.getOpcode() == ISD::BITCAST) {
13136       if (!BC0.hasOneUse())
13137         break;
13138       BC0 = BC0.getOperand(0);
13139     }
13140
13141     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
13142       if (Scale == 1)
13143         return SmallVector<int, 8>(Mask.begin(), Mask.end());
13144
13145       SmallVector<int, 8> NewMask;
13146       for (int M : Mask)
13147         for (int s = 0; s != Scale; ++s)
13148           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
13149       return NewMask;
13150     };
13151
13152     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
13153       EVT SVT = VT.getScalarType();
13154       EVT InnerVT = BC0->getValueType(0);
13155       EVT InnerSVT = InnerVT.getScalarType();
13156
13157       // Determine which shuffle works with the smaller scalar type.
13158       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
13159       EVT ScaleSVT = ScaleVT.getScalarType();
13160
13161       if (TLI.isTypeLegal(ScaleVT) &&
13162           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
13163           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
13164
13165         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13166         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
13167
13168         // Scale the shuffle masks to the smaller scalar type.
13169         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
13170         SmallVector<int, 8> InnerMask =
13171             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
13172         SmallVector<int, 8> OuterMask =
13173             ScaleShuffleMask(SVN->getMask(), OuterScale);
13174
13175         // Merge the shuffle masks.
13176         SmallVector<int, 8> NewMask;
13177         for (int M : OuterMask)
13178           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
13179
13180         // Test for shuffle mask legality over both commutations.
13181         SDValue SV0 = BC0->getOperand(0);
13182         SDValue SV1 = BC0->getOperand(1);
13183         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13184         if (!LegalMask) {
13185           std::swap(SV0, SV1);
13186           ShuffleVectorSDNode::commuteMask(NewMask);
13187           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
13188         }
13189
13190         if (LegalMask) {
13191           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
13192           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
13193           return DAG.getNode(
13194               ISD::BITCAST, SDLoc(N), VT,
13195               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
13196         }
13197       }
13198     }
13199   }
13200
13201   // Canonicalize shuffles according to rules:
13202   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
13203   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
13204   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
13205   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
13206       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
13207       TLI.isTypeLegal(VT)) {
13208     // The incoming shuffle must be of the same type as the result of the
13209     // current shuffle.
13210     assert(N1->getOperand(0).getValueType() == VT &&
13211            "Shuffle types don't match");
13212
13213     SDValue SV0 = N1->getOperand(0);
13214     SDValue SV1 = N1->getOperand(1);
13215     bool HasSameOp0 = N0 == SV0;
13216     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
13217     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
13218       // Commute the operands of this shuffle so that next rule
13219       // will trigger.
13220       return DAG.getCommutedVectorShuffle(*SVN);
13221   }
13222
13223   // Try to fold according to rules:
13224   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13225   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13226   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13227   // Don't try to fold shuffles with illegal type.
13228   // Only fold if this shuffle is the only user of the other shuffle.
13229   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
13230       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
13231     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
13232
13233     // The incoming shuffle must be of the same type as the result of the
13234     // current shuffle.
13235     assert(OtherSV->getOperand(0).getValueType() == VT &&
13236            "Shuffle types don't match");
13237
13238     SDValue SV0, SV1;
13239     SmallVector<int, 4> Mask;
13240     // Compute the combined shuffle mask for a shuffle with SV0 as the first
13241     // operand, and SV1 as the second operand.
13242     for (unsigned i = 0; i != NumElts; ++i) {
13243       int Idx = SVN->getMaskElt(i);
13244       if (Idx < 0) {
13245         // Propagate Undef.
13246         Mask.push_back(Idx);
13247         continue;
13248       }
13249
13250       SDValue CurrentVec;
13251       if (Idx < (int)NumElts) {
13252         // This shuffle index refers to the inner shuffle N0. Lookup the inner
13253         // shuffle mask to identify which vector is actually referenced.
13254         Idx = OtherSV->getMaskElt(Idx);
13255         if (Idx < 0) {
13256           // Propagate Undef.
13257           Mask.push_back(Idx);
13258           continue;
13259         }
13260
13261         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
13262                                            : OtherSV->getOperand(1);
13263       } else {
13264         // This shuffle index references an element within N1.
13265         CurrentVec = N1;
13266       }
13267
13268       // Simple case where 'CurrentVec' is UNDEF.
13269       if (CurrentVec.getOpcode() == ISD::UNDEF) {
13270         Mask.push_back(-1);
13271         continue;
13272       }
13273
13274       // Canonicalize the shuffle index. We don't know yet if CurrentVec
13275       // will be the first or second operand of the combined shuffle.
13276       Idx = Idx % NumElts;
13277       if (!SV0.getNode() || SV0 == CurrentVec) {
13278         // Ok. CurrentVec is the left hand side.
13279         // Update the mask accordingly.
13280         SV0 = CurrentVec;
13281         Mask.push_back(Idx);
13282         continue;
13283       }
13284
13285       // Bail out if we cannot convert the shuffle pair into a single shuffle.
13286       if (SV1.getNode() && SV1 != CurrentVec)
13287         return SDValue();
13288
13289       // Ok. CurrentVec is the right hand side.
13290       // Update the mask accordingly.
13291       SV1 = CurrentVec;
13292       Mask.push_back(Idx + NumElts);
13293     }
13294
13295     // Check if all indices in Mask are Undef. In case, propagate Undef.
13296     bool isUndefMask = true;
13297     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
13298       isUndefMask &= Mask[i] < 0;
13299
13300     if (isUndefMask)
13301       return DAG.getUNDEF(VT);
13302
13303     if (!SV0.getNode())
13304       SV0 = DAG.getUNDEF(VT);
13305     if (!SV1.getNode())
13306       SV1 = DAG.getUNDEF(VT);
13307
13308     // Avoid introducing shuffles with illegal mask.
13309     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
13310       ShuffleVectorSDNode::commuteMask(Mask);
13311
13312       if (!TLI.isShuffleMaskLegal(Mask, VT))
13313         return SDValue();
13314
13315       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
13316       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
13317       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
13318       std::swap(SV0, SV1);
13319     }
13320
13321     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
13322     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
13323     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
13324     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
13325   }
13326
13327   return SDValue();
13328 }
13329
13330 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
13331   SDValue InVal = N->getOperand(0);
13332   EVT VT = N->getValueType(0);
13333
13334   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
13335   // with a VECTOR_SHUFFLE.
13336   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
13337     SDValue InVec = InVal->getOperand(0);
13338     SDValue EltNo = InVal->getOperand(1);
13339
13340     // FIXME: We could support implicit truncation if the shuffle can be
13341     // scaled to a smaller vector scalar type.
13342     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
13343     if (C0 && VT == InVec.getValueType() &&
13344         VT.getScalarType() == InVal.getValueType()) {
13345       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
13346       int Elt = C0->getZExtValue();
13347       NewMask[0] = Elt;
13348
13349       if (TLI.isShuffleMaskLegal(NewMask, VT))
13350         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
13351                                     NewMask);
13352     }
13353   }
13354
13355   return SDValue();
13356 }
13357
13358 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
13359   SDValue N0 = N->getOperand(0);
13360   SDValue N2 = N->getOperand(2);
13361
13362   // If the input vector is a concatenation, and the insert replaces
13363   // one of the halves, we can optimize into a single concat_vectors.
13364   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
13365       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
13366     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
13367     EVT VT = N->getValueType(0);
13368
13369     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13370     // (concat_vectors Z, Y)
13371     if (InsIdx == 0)
13372       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13373                          N->getOperand(1), N0.getOperand(1));
13374
13375     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
13376     // (concat_vectors X, Z)
13377     if (InsIdx == VT.getVectorNumElements()/2)
13378       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
13379                          N0.getOperand(0), N->getOperand(1));
13380   }
13381
13382   return SDValue();
13383 }
13384
13385 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
13386   SDValue N0 = N->getOperand(0);
13387
13388   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
13389   if (N0->getOpcode() == ISD::FP16_TO_FP)
13390     return N0->getOperand(0);
13391
13392   return SDValue();
13393 }
13394
13395 SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
13396   SDValue N0 = N->getOperand(0);
13397
13398   // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
13399   if (N0->getOpcode() == ISD::AND) {
13400     ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
13401     if (AndConst && AndConst->getAPIntValue() == 0xffff) {
13402       return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
13403                          N0.getOperand(0));
13404     }
13405   }
13406
13407   return SDValue();
13408 }
13409
13410 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
13411 /// with the destination vector and a zero vector.
13412 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
13413 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
13414 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
13415   EVT VT = N->getValueType(0);
13416   SDValue LHS = N->getOperand(0);
13417   SDValue RHS = N->getOperand(1);
13418   SDLoc dl(N);
13419
13420   // Make sure we're not running after operation legalization where it
13421   // may have custom lowered the vector shuffles.
13422   if (LegalOperations)
13423     return SDValue();
13424
13425   if (N->getOpcode() != ISD::AND)
13426     return SDValue();
13427
13428   if (RHS.getOpcode() == ISD::BITCAST)
13429     RHS = RHS.getOperand(0);
13430
13431   if (RHS.getOpcode() != ISD::BUILD_VECTOR)
13432     return SDValue();
13433
13434   EVT RVT = RHS.getValueType();
13435   unsigned NumElts = RHS.getNumOperands();
13436
13437   // Attempt to create a valid clear mask, splitting the mask into
13438   // sub elements and checking to see if each is
13439   // all zeros or all ones - suitable for shuffle masking.
13440   auto BuildClearMask = [&](int Split) {
13441     int NumSubElts = NumElts * Split;
13442     int NumSubBits = RVT.getScalarSizeInBits() / Split;
13443
13444     SmallVector<int, 8> Indices;
13445     for (int i = 0; i != NumSubElts; ++i) {
13446       int EltIdx = i / Split;
13447       int SubIdx = i % Split;
13448       SDValue Elt = RHS.getOperand(EltIdx);
13449       if (Elt.getOpcode() == ISD::UNDEF) {
13450         Indices.push_back(-1);
13451         continue;
13452       }
13453
13454       APInt Bits;
13455       if (isa<ConstantSDNode>(Elt))
13456         Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
13457       else if (isa<ConstantFPSDNode>(Elt))
13458         Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
13459       else
13460         return SDValue();
13461
13462       // Extract the sub element from the constant bit mask.
13463       if (DAG.getDataLayout().isBigEndian()) {
13464         Bits = Bits.lshr((Split - SubIdx - 1) * NumSubBits);
13465       } else {
13466         Bits = Bits.lshr(SubIdx * NumSubBits);
13467       }
13468
13469       if (Split > 1)
13470         Bits = Bits.trunc(NumSubBits);
13471
13472       if (Bits.isAllOnesValue())
13473         Indices.push_back(i);
13474       else if (Bits == 0)
13475         Indices.push_back(i + NumSubElts);
13476       else
13477         return SDValue();
13478     }
13479
13480     // Let's see if the target supports this vector_shuffle.
13481     EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
13482     EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
13483     if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
13484       return SDValue();
13485
13486     SDValue Zero = DAG.getConstant(0, dl, ClearVT);
13487     return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, dl,
13488                                                    DAG.getBitcast(ClearVT, LHS),
13489                                                    Zero, &Indices[0]));
13490   };
13491
13492   // Determine maximum split level (byte level masking).
13493   int MaxSplit = 1;
13494   if (RVT.getScalarSizeInBits() % 8 == 0)
13495     MaxSplit = RVT.getScalarSizeInBits() / 8;
13496
13497   for (int Split = 1; Split <= MaxSplit; ++Split)
13498     if (RVT.getScalarSizeInBits() % Split == 0)
13499       if (SDValue S = BuildClearMask(Split))
13500         return S;
13501
13502   return SDValue();
13503 }
13504
13505 /// Visit a binary vector operation, like ADD.
13506 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
13507   assert(N->getValueType(0).isVector() &&
13508          "SimplifyVBinOp only works on vectors!");
13509
13510   SDValue LHS = N->getOperand(0);
13511   SDValue RHS = N->getOperand(1);
13512   SDValue Ops[] = {LHS, RHS};
13513
13514   // See if we can constant fold the vector operation.
13515   if (SDValue Fold = DAG.FoldConstantVectorArithmetic(
13516           N->getOpcode(), SDLoc(LHS), LHS.getValueType(), Ops, N->getFlags()))
13517     return Fold;
13518
13519   // Try to convert a constant mask AND into a shuffle clear mask.
13520   if (SDValue Shuffle = XformToShuffleWithZero(N))
13521     return Shuffle;
13522
13523   // Type legalization might introduce new shuffles in the DAG.
13524   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
13525   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
13526   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
13527       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
13528       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
13529       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
13530     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
13531     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
13532
13533     if (SVN0->getMask().equals(SVN1->getMask())) {
13534       EVT VT = N->getValueType(0);
13535       SDValue UndefVector = LHS.getOperand(1);
13536       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
13537                                      LHS.getOperand(0), RHS.getOperand(0),
13538                                      N->getFlags());
13539       AddUsersToWorklist(N);
13540       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
13541                                   &SVN0->getMask()[0]);
13542     }
13543   }
13544
13545   return SDValue();
13546 }
13547
13548 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13549                                     SDValue N1, SDValue N2){
13550   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13551
13552   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13553                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13554
13555   // If we got a simplified select_cc node back from SimplifySelectCC, then
13556   // break it down into a new SETCC node, and a new SELECT node, and then return
13557   // the SELECT node, since we were called with a SELECT node.
13558   if (SCC.getNode()) {
13559     // Check to see if we got a select_cc back (to turn into setcc/select).
13560     // Otherwise, just return whatever node we got back, like fabs.
13561     if (SCC.getOpcode() == ISD::SELECT_CC) {
13562       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13563                                   N0.getValueType(),
13564                                   SCC.getOperand(0), SCC.getOperand(1),
13565                                   SCC.getOperand(4));
13566       AddToWorklist(SETCC.getNode());
13567       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13568                            SCC.getOperand(2), SCC.getOperand(3));
13569     }
13570
13571     return SCC;
13572   }
13573   return SDValue();
13574 }
13575
13576 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13577 /// being selected between, see if we can simplify the select.  Callers of this
13578 /// should assume that TheSelect is deleted if this returns true.  As such, they
13579 /// should return the appropriate thing (e.g. the node) back to the top-level of
13580 /// the DAG combiner loop to avoid it being looked at.
13581 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13582                                     SDValue RHS) {
13583
13584   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13585   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13586   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13587     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13588       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13589       SDValue Sqrt = RHS;
13590       ISD::CondCode CC;
13591       SDValue CmpLHS;
13592       const ConstantFPSDNode *NegZero = nullptr;
13593
13594       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13595         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13596         CmpLHS = TheSelect->getOperand(0);
13597         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13598       } else {
13599         // SELECT or VSELECT
13600         SDValue Cmp = TheSelect->getOperand(0);
13601         if (Cmp.getOpcode() == ISD::SETCC) {
13602           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13603           CmpLHS = Cmp.getOperand(0);
13604           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13605         }
13606       }
13607       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13608           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13609           CC == ISD::SETULT || CC == ISD::SETLT)) {
13610         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13611         CombineTo(TheSelect, Sqrt);
13612         return true;
13613       }
13614     }
13615   }
13616   // Cannot simplify select with vector condition
13617   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13618
13619   // If this is a select from two identical things, try to pull the operation
13620   // through the select.
13621   if (LHS.getOpcode() != RHS.getOpcode() ||
13622       !LHS.hasOneUse() || !RHS.hasOneUse())
13623     return false;
13624
13625   // If this is a load and the token chain is identical, replace the select
13626   // of two loads with a load through a select of the address to load from.
13627   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13628   // constants have been dropped into the constant pool.
13629   if (LHS.getOpcode() == ISD::LOAD) {
13630     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13631     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13632
13633     // Token chains must be identical.
13634     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13635         // Do not let this transformation reduce the number of volatile loads.
13636         LLD->isVolatile() || RLD->isVolatile() ||
13637         // FIXME: If either is a pre/post inc/dec load,
13638         // we'd need to split out the address adjustment.
13639         LLD->isIndexed() || RLD->isIndexed() ||
13640         // If this is an EXTLOAD, the VT's must match.
13641         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13642         // If this is an EXTLOAD, the kind of extension must match.
13643         (LLD->getExtensionType() != RLD->getExtensionType() &&
13644          // The only exception is if one of the extensions is anyext.
13645          LLD->getExtensionType() != ISD::EXTLOAD &&
13646          RLD->getExtensionType() != ISD::EXTLOAD) ||
13647         // FIXME: this discards src value information.  This is
13648         // over-conservative. It would be beneficial to be able to remember
13649         // both potential memory locations.  Since we are discarding
13650         // src value info, don't do the transformation if the memory
13651         // locations are not in the default address space.
13652         LLD->getPointerInfo().getAddrSpace() != 0 ||
13653         RLD->getPointerInfo().getAddrSpace() != 0 ||
13654         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13655                                       LLD->getBasePtr().getValueType()))
13656       return false;
13657
13658     // Check that the select condition doesn't reach either load.  If so,
13659     // folding this will induce a cycle into the DAG.  If not, this is safe to
13660     // xform, so create a select of the addresses.
13661     SDValue Addr;
13662     if (TheSelect->getOpcode() == ISD::SELECT) {
13663       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13664       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13665           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13666         return false;
13667       // The loads must not depend on one another.
13668       if (LLD->isPredecessorOf(RLD) ||
13669           RLD->isPredecessorOf(LLD))
13670         return false;
13671       Addr = DAG.getSelect(SDLoc(TheSelect),
13672                            LLD->getBasePtr().getValueType(),
13673                            TheSelect->getOperand(0), LLD->getBasePtr(),
13674                            RLD->getBasePtr());
13675     } else {  // Otherwise SELECT_CC
13676       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13677       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13678
13679       if ((LLD->hasAnyUseOfValue(1) &&
13680            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13681           (RLD->hasAnyUseOfValue(1) &&
13682            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13683         return false;
13684
13685       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13686                          LLD->getBasePtr().getValueType(),
13687                          TheSelect->getOperand(0),
13688                          TheSelect->getOperand(1),
13689                          LLD->getBasePtr(), RLD->getBasePtr(),
13690                          TheSelect->getOperand(4));
13691     }
13692
13693     SDValue Load;
13694     // It is safe to replace the two loads if they have different alignments,
13695     // but the new load must be the minimum (most restrictive) alignment of the
13696     // inputs.
13697     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13698     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13699     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13700       Load = DAG.getLoad(TheSelect->getValueType(0),
13701                          SDLoc(TheSelect),
13702                          // FIXME: Discards pointer and AA info.
13703                          LLD->getChain(), Addr, MachinePointerInfo(),
13704                          LLD->isVolatile(), LLD->isNonTemporal(),
13705                          isInvariant, Alignment);
13706     } else {
13707       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13708                             RLD->getExtensionType() : LLD->getExtensionType(),
13709                             SDLoc(TheSelect),
13710                             TheSelect->getValueType(0),
13711                             // FIXME: Discards pointer and AA info.
13712                             LLD->getChain(), Addr, MachinePointerInfo(),
13713                             LLD->getMemoryVT(), LLD->isVolatile(),
13714                             LLD->isNonTemporal(), isInvariant, Alignment);
13715     }
13716
13717     // Users of the select now use the result of the load.
13718     CombineTo(TheSelect, Load);
13719
13720     // Users of the old loads now use the new load's chain.  We know the
13721     // old-load value is dead now.
13722     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13723     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13724     return true;
13725   }
13726
13727   return false;
13728 }
13729
13730 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13731 /// where 'cond' is the comparison specified by CC.
13732 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13733                                       SDValue N2, SDValue N3,
13734                                       ISD::CondCode CC, bool NotExtCompare) {
13735   // (x ? y : y) -> y.
13736   if (N2 == N3) return N2;
13737
13738   EVT VT = N2.getValueType();
13739   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13740   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13741
13742   // Determine if the condition we're dealing with is constant
13743   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13744                               N0, N1, CC, DL, false);
13745   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13746
13747   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
13748     // fold select_cc true, x, y -> x
13749     // fold select_cc false, x, y -> y
13750     return !SCCC->isNullValue() ? N2 : N3;
13751   }
13752
13753   // Check to see if we can simplify the select into an fabs node
13754   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13755     // Allow either -0.0 or 0.0
13756     if (CFP->isZero()) {
13757       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13758       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13759           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13760           N2 == N3.getOperand(0))
13761         return DAG.getNode(ISD::FABS, DL, VT, N0);
13762
13763       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13764       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13765           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13766           N2.getOperand(0) == N3)
13767         return DAG.getNode(ISD::FABS, DL, VT, N3);
13768     }
13769   }
13770
13771   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13772   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13773   // in it.  This is a win when the constant is not otherwise available because
13774   // it replaces two constant pool loads with one.  We only do this if the FP
13775   // type is known to be legal, because if it isn't, then we are before legalize
13776   // types an we want the other legalization to happen first (e.g. to avoid
13777   // messing with soft float) and if the ConstantFP is not legal, because if
13778   // it is legal, we may not need to store the FP constant in a constant pool.
13779   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13780     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13781       if (TLI.isTypeLegal(N2.getValueType()) &&
13782           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13783                TargetLowering::Legal &&
13784            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13785            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13786           // If both constants have multiple uses, then we won't need to do an
13787           // extra load, they are likely around in registers for other users.
13788           (TV->hasOneUse() || FV->hasOneUse())) {
13789         Constant *Elts[] = {
13790           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13791           const_cast<ConstantFP*>(TV->getConstantFPValue())
13792         };
13793         Type *FPTy = Elts[0]->getType();
13794         const DataLayout &TD = DAG.getDataLayout();
13795
13796         // Create a ConstantArray of the two constants.
13797         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13798         SDValue CPIdx =
13799             DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
13800                                 TD.getPrefTypeAlignment(FPTy));
13801         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13802
13803         // Get the offsets to the 0 and 1 element of the array so that we can
13804         // select between them.
13805         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13806         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13807         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13808
13809         SDValue Cond = DAG.getSetCC(DL,
13810                                     getSetCCResultType(N0.getValueType()),
13811                                     N0, N1, CC);
13812         AddToWorklist(Cond.getNode());
13813         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13814                                           Cond, One, Zero);
13815         AddToWorklist(CstOffset.getNode());
13816         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13817                             CstOffset);
13818         AddToWorklist(CPIdx.getNode());
13819         return DAG.getLoad(
13820             TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13821             MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
13822             false, false, false, Alignment);
13823       }
13824     }
13825
13826   // Check to see if we can perform the "gzip trick", transforming
13827   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13828   if (isNullConstant(N3) && CC == ISD::SETLT &&
13829       (isNullConstant(N1) ||                 // (a < 0) ? b : 0
13830        (isOneConstant(N1) && N0 == N2))) {   // (a < 1) ? a : 0
13831     EVT XType = N0.getValueType();
13832     EVT AType = N2.getValueType();
13833     if (XType.bitsGE(AType)) {
13834       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13835       // single-bit constant.
13836       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13837         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13838         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13839         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13840                                        getShiftAmountTy(N0.getValueType()));
13841         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13842                                     XType, N0, ShCt);
13843         AddToWorklist(Shift.getNode());
13844
13845         if (XType.bitsGT(AType)) {
13846           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13847           AddToWorklist(Shift.getNode());
13848         }
13849
13850         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13851       }
13852
13853       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13854                                   XType, N0,
13855                                   DAG.getConstant(XType.getSizeInBits() - 1,
13856                                                   SDLoc(N0),
13857                                          getShiftAmountTy(N0.getValueType())));
13858       AddToWorklist(Shift.getNode());
13859
13860       if (XType.bitsGT(AType)) {
13861         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13862         AddToWorklist(Shift.getNode());
13863       }
13864
13865       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13866     }
13867   }
13868
13869   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13870   // where y is has a single bit set.
13871   // A plaintext description would be, we can turn the SELECT_CC into an AND
13872   // when the condition can be materialized as an all-ones register.  Any
13873   // single bit-test can be materialized as an all-ones register with
13874   // shift-left and shift-right-arith.
13875   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13876       N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
13877     SDValue AndLHS = N0->getOperand(0);
13878     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13879     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13880       // Shift the tested bit over the sign bit.
13881       APInt AndMask = ConstAndRHS->getAPIntValue();
13882       SDValue ShlAmt =
13883         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13884                         getShiftAmountTy(AndLHS.getValueType()));
13885       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13886
13887       // Now arithmetic right shift it all the way over, so the result is either
13888       // all-ones, or zero.
13889       SDValue ShrAmt =
13890         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13891                         getShiftAmountTy(Shl.getValueType()));
13892       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13893
13894       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13895     }
13896   }
13897
13898   // fold select C, 16, 0 -> shl C, 4
13899   if (N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2() &&
13900       TLI.getBooleanContents(N0.getValueType()) ==
13901           TargetLowering::ZeroOrOneBooleanContent) {
13902
13903     // If the caller doesn't want us to simplify this into a zext of a compare,
13904     // don't do it.
13905     if (NotExtCompare && N2C->isOne())
13906       return SDValue();
13907
13908     // Get a SetCC of the condition
13909     // NOTE: Don't create a SETCC if it's not legal on this target.
13910     if (!LegalOperations ||
13911         TLI.isOperationLegal(ISD::SETCC, N0.getValueType())) {
13912       SDValue Temp, SCC;
13913       // cast from setcc result type to select result type
13914       if (LegalTypes) {
13915         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13916                             N0, N1, CC);
13917         if (N2.getValueType().bitsLT(SCC.getValueType()))
13918           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13919                                         N2.getValueType());
13920         else
13921           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13922                              N2.getValueType(), SCC);
13923       } else {
13924         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13925         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13926                            N2.getValueType(), SCC);
13927       }
13928
13929       AddToWorklist(SCC.getNode());
13930       AddToWorklist(Temp.getNode());
13931
13932       if (N2C->isOne())
13933         return Temp;
13934
13935       // shl setcc result by log2 n2c
13936       return DAG.getNode(
13937           ISD::SHL, DL, N2.getValueType(), Temp,
13938           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13939                           getShiftAmountTy(Temp.getValueType())));
13940     }
13941   }
13942
13943   // Check to see if this is an integer abs.
13944   // select_cc setg[te] X,  0,  X, -X ->
13945   // select_cc setgt    X, -1,  X, -X ->
13946   // select_cc setl[te] X,  0, -X,  X ->
13947   // select_cc setlt    X,  1, -X,  X ->
13948   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13949   if (N1C) {
13950     ConstantSDNode *SubC = nullptr;
13951     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13952          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13953         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13954       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13955     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13956               (N1C->isOne() && CC == ISD::SETLT)) &&
13957              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13958       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13959
13960     EVT XType = N0.getValueType();
13961     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13962       SDLoc DL(N0);
13963       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13964                                   N0,
13965                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13966                                          getShiftAmountTy(N0.getValueType())));
13967       SDValue Add = DAG.getNode(ISD::ADD, DL,
13968                                 XType, N0, Shift);
13969       AddToWorklist(Shift.getNode());
13970       AddToWorklist(Add.getNode());
13971       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13972     }
13973   }
13974
13975   return SDValue();
13976 }
13977
13978 /// This is a stub for TargetLowering::SimplifySetCC.
13979 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13980                                    SDValue N1, ISD::CondCode Cond,
13981                                    SDLoc DL, bool foldBooleans) {
13982   TargetLowering::DAGCombinerInfo
13983     DagCombineInfo(DAG, Level, false, this);
13984   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13985 }
13986
13987 /// Given an ISD::SDIV node expressing a divide by constant, return
13988 /// a DAG expression to select that will generate the same value by multiplying
13989 /// by a magic number.
13990 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13991 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13992   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13993   if (!C)
13994     return SDValue();
13995
13996   // Avoid division by zero.
13997   if (C->isNullValue())
13998     return SDValue();
13999
14000   std::vector<SDNode*> Built;
14001   SDValue S =
14002       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14003
14004   for (SDNode *N : Built)
14005     AddToWorklist(N);
14006   return S;
14007 }
14008
14009 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
14010 /// DAG expression that will generate the same value by right shifting.
14011 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
14012   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14013   if (!C)
14014     return SDValue();
14015
14016   // Avoid division by zero.
14017   if (C->isNullValue())
14018     return SDValue();
14019
14020   std::vector<SDNode *> Built;
14021   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
14022
14023   for (SDNode *N : Built)
14024     AddToWorklist(N);
14025   return S;
14026 }
14027
14028 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
14029 /// expression that will generate the same value by multiplying by a magic
14030 /// number.
14031 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
14032 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
14033   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
14034   if (!C)
14035     return SDValue();
14036
14037   // Avoid division by zero.
14038   if (C->isNullValue())
14039     return SDValue();
14040
14041   std::vector<SDNode*> Built;
14042   SDValue S =
14043       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
14044
14045   for (SDNode *N : Built)
14046     AddToWorklist(N);
14047   return S;
14048 }
14049
14050 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op, SDNodeFlags *Flags) {
14051   if (Level >= AfterLegalizeDAG)
14052     return SDValue();
14053
14054   // Expose the DAG combiner to the target combiner implementations.
14055   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14056
14057   unsigned Iterations = 0;
14058   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
14059     if (Iterations) {
14060       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14061       // For the reciprocal, we need to find the zero of the function:
14062       //   F(X) = A X - 1 [which has a zero at X = 1/A]
14063       //     =>
14064       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
14065       //     does not require additional intermediate precision]
14066       EVT VT = Op.getValueType();
14067       SDLoc DL(Op);
14068       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
14069
14070       AddToWorklist(Est.getNode());
14071
14072       // Newton iterations: Est = Est + Est (1 - Arg * Est)
14073       for (unsigned i = 0; i < Iterations; ++i) {
14074         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est, Flags);
14075         AddToWorklist(NewEst.getNode());
14076
14077         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst, Flags);
14078         AddToWorklist(NewEst.getNode());
14079
14080         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14081         AddToWorklist(NewEst.getNode());
14082
14083         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst, Flags);
14084         AddToWorklist(Est.getNode());
14085       }
14086     }
14087     return Est;
14088   }
14089
14090   return SDValue();
14091 }
14092
14093 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14094 /// For the reciprocal sqrt, we need to find the zero of the function:
14095 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14096 ///     =>
14097 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
14098 /// As a result, we precompute A/2 prior to the iteration loop.
14099 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
14100                                           unsigned Iterations,
14101                                           SDNodeFlags *Flags) {
14102   EVT VT = Arg.getValueType();
14103   SDLoc DL(Arg);
14104   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
14105
14106   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
14107   // this entire sequence requires only one FP constant.
14108   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
14109   AddToWorklist(HalfArg.getNode());
14110
14111   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
14112   AddToWorklist(HalfArg.getNode());
14113
14114   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
14115   for (unsigned i = 0; i < Iterations; ++i) {
14116     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14117     AddToWorklist(NewEst.getNode());
14118
14119     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
14120     AddToWorklist(NewEst.getNode());
14121
14122     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
14123     AddToWorklist(NewEst.getNode());
14124
14125     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
14126     AddToWorklist(Est.getNode());
14127   }
14128   return Est;
14129 }
14130
14131 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
14132 /// For the reciprocal sqrt, we need to find the zero of the function:
14133 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
14134 ///     =>
14135 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
14136 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
14137                                           unsigned Iterations,
14138                                           SDNodeFlags *Flags) {
14139   EVT VT = Arg.getValueType();
14140   SDLoc DL(Arg);
14141   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
14142   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
14143
14144   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
14145   for (unsigned i = 0; i < Iterations; ++i) {
14146     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
14147     AddToWorklist(HalfEst.getNode());
14148
14149     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
14150     AddToWorklist(Est.getNode());
14151
14152     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
14153     AddToWorklist(Est.getNode());
14154
14155     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree, Flags);
14156     AddToWorklist(Est.getNode());
14157
14158     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst, Flags);
14159     AddToWorklist(Est.getNode());
14160   }
14161   return Est;
14162 }
14163
14164 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op, SDNodeFlags *Flags) {
14165   if (Level >= AfterLegalizeDAG)
14166     return SDValue();
14167
14168   // Expose the DAG combiner to the target combiner implementations.
14169   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
14170   unsigned Iterations = 0;
14171   bool UseOneConstNR = false;
14172   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
14173     AddToWorklist(Est.getNode());
14174     if (Iterations) {
14175       Est = UseOneConstNR ?
14176         BuildRsqrtNROneConst(Op, Est, Iterations, Flags) :
14177         BuildRsqrtNRTwoConst(Op, Est, Iterations, Flags);
14178     }
14179     return Est;
14180   }
14181
14182   return SDValue();
14183 }
14184
14185 /// Return true if base is a frame index, which is known not to alias with
14186 /// anything but itself.  Provides base object and offset as results.
14187 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
14188                            const GlobalValue *&GV, const void *&CV) {
14189   // Assume it is a primitive operation.
14190   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
14191
14192   // If it's an adding a simple constant then integrate the offset.
14193   if (Base.getOpcode() == ISD::ADD) {
14194     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
14195       Base = Base.getOperand(0);
14196       Offset += C->getZExtValue();
14197     }
14198   }
14199
14200   // Return the underlying GlobalValue, and update the Offset.  Return false
14201   // for GlobalAddressSDNode since the same GlobalAddress may be represented
14202   // by multiple nodes with different offsets.
14203   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
14204     GV = G->getGlobal();
14205     Offset += G->getOffset();
14206     return false;
14207   }
14208
14209   // Return the underlying Constant value, and update the Offset.  Return false
14210   // for ConstantSDNodes since the same constant pool entry may be represented
14211   // by multiple nodes with different offsets.
14212   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
14213     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
14214                                          : (const void *)C->getConstVal();
14215     Offset += C->getOffset();
14216     return false;
14217   }
14218   // If it's any of the following then it can't alias with anything but itself.
14219   return isa<FrameIndexSDNode>(Base);
14220 }
14221
14222 /// Return true if there is any possibility that the two addresses overlap.
14223 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
14224   // If they are the same then they must be aliases.
14225   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
14226
14227   // If they are both volatile then they cannot be reordered.
14228   if (Op0->isVolatile() && Op1->isVolatile()) return true;
14229
14230   // If one operation reads from invariant memory, and the other may store, they
14231   // cannot alias. These should really be checking the equivalent of mayWrite,
14232   // but it only matters for memory nodes other than load /store.
14233   if (Op0->isInvariant() && Op1->writeMem())
14234     return false;
14235
14236   if (Op1->isInvariant() && Op0->writeMem())
14237     return false;
14238
14239   // Gather base node and offset information.
14240   SDValue Base1, Base2;
14241   int64_t Offset1, Offset2;
14242   const GlobalValue *GV1, *GV2;
14243   const void *CV1, *CV2;
14244   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
14245                                       Base1, Offset1, GV1, CV1);
14246   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
14247                                       Base2, Offset2, GV2, CV2);
14248
14249   // If they have a same base address then check to see if they overlap.
14250   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
14251     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14252              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14253
14254   // It is possible for different frame indices to alias each other, mostly
14255   // when tail call optimization reuses return address slots for arguments.
14256   // To catch this case, look up the actual index of frame indices to compute
14257   // the real alias relationship.
14258   if (isFrameIndex1 && isFrameIndex2) {
14259     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14260     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
14261     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
14262     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
14263              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
14264   }
14265
14266   // Otherwise, if we know what the bases are, and they aren't identical, then
14267   // we know they cannot alias.
14268   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
14269     return false;
14270
14271   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
14272   // compared to the size and offset of the access, we may be able to prove they
14273   // do not alias.  This check is conservative for now to catch cases created by
14274   // splitting vector types.
14275   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
14276       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
14277       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
14278        Op1->getMemoryVT().getSizeInBits() >> 3) &&
14279       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
14280     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
14281     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
14282
14283     // There is no overlap between these relatively aligned accesses of similar
14284     // size, return no alias.
14285     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
14286         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
14287       return false;
14288   }
14289
14290   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
14291                    ? CombinerGlobalAA
14292                    : DAG.getSubtarget().useAA();
14293 #ifndef NDEBUG
14294   if (CombinerAAOnlyFunc.getNumOccurrences() &&
14295       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
14296     UseAA = false;
14297 #endif
14298   if (UseAA &&
14299       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
14300     // Use alias analysis information.
14301     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
14302                                  Op1->getSrcValueOffset());
14303     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
14304         Op0->getSrcValueOffset() - MinOffset;
14305     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
14306         Op1->getSrcValueOffset() - MinOffset;
14307     AliasResult AAResult =
14308         AA.alias(MemoryLocation(Op0->getMemOperand()->getValue(), Overlap1,
14309                                 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
14310                  MemoryLocation(Op1->getMemOperand()->getValue(), Overlap2,
14311                                 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
14312     if (AAResult == NoAlias)
14313       return false;
14314   }
14315
14316   // Otherwise we have to assume they alias.
14317   return true;
14318 }
14319
14320 /// Walk up chain skipping non-aliasing memory nodes,
14321 /// looking for aliasing nodes and adding them to the Aliases vector.
14322 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
14323                                    SmallVectorImpl<SDValue> &Aliases) {
14324   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
14325   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
14326
14327   // Get alias information for node.
14328   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
14329
14330   // Starting off.
14331   Chains.push_back(OriginalChain);
14332   unsigned Depth = 0;
14333
14334   // Look at each chain and determine if it is an alias.  If so, add it to the
14335   // aliases list.  If not, then continue up the chain looking for the next
14336   // candidate.
14337   while (!Chains.empty()) {
14338     SDValue Chain = Chains.pop_back_val();
14339
14340     // For TokenFactor nodes, look at each operand and only continue up the
14341     // chain until we reach the depth limit.
14342     //
14343     // FIXME: The depth check could be made to return the last non-aliasing
14344     // chain we found before we hit a tokenfactor rather than the original
14345     // chain.
14346     if (Depth > 6) {
14347       Aliases.clear();
14348       Aliases.push_back(OriginalChain);
14349       return;
14350     }
14351
14352     // Don't bother if we've been before.
14353     if (!Visited.insert(Chain.getNode()).second)
14354       continue;
14355
14356     switch (Chain.getOpcode()) {
14357     case ISD::EntryToken:
14358       // Entry token is ideal chain operand, but handled in FindBetterChain.
14359       break;
14360
14361     case ISD::LOAD:
14362     case ISD::STORE: {
14363       // Get alias information for Chain.
14364       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
14365           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
14366
14367       // If chain is alias then stop here.
14368       if (!(IsLoad && IsOpLoad) &&
14369           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
14370         Aliases.push_back(Chain);
14371       } else {
14372         // Look further up the chain.
14373         Chains.push_back(Chain.getOperand(0));
14374         ++Depth;
14375       }
14376       break;
14377     }
14378
14379     case ISD::TokenFactor:
14380       // We have to check each of the operands of the token factor for "small"
14381       // token factors, so we queue them up.  Adding the operands to the queue
14382       // (stack) in reverse order maintains the original order and increases the
14383       // likelihood that getNode will find a matching token factor (CSE.)
14384       if (Chain.getNumOperands() > 16) {
14385         Aliases.push_back(Chain);
14386         break;
14387       }
14388       for (unsigned n = Chain.getNumOperands(); n;)
14389         Chains.push_back(Chain.getOperand(--n));
14390       ++Depth;
14391       break;
14392
14393     default:
14394       // For all other instructions we will just have to take what we can get.
14395       Aliases.push_back(Chain);
14396       break;
14397     }
14398   }
14399
14400   // We need to be careful here to also search for aliases through the
14401   // value operand of a store, etc. Consider the following situation:
14402   //   Token1 = ...
14403   //   L1 = load Token1, %52
14404   //   S1 = store Token1, L1, %51
14405   //   L2 = load Token1, %52+8
14406   //   S2 = store Token1, L2, %51+8
14407   //   Token2 = Token(S1, S2)
14408   //   L3 = load Token2, %53
14409   //   S3 = store Token2, L3, %52
14410   //   L4 = load Token2, %53+8
14411   //   S4 = store Token2, L4, %52+8
14412   // If we search for aliases of S3 (which loads address %52), and we look
14413   // only through the chain, then we'll miss the trivial dependence on L1
14414   // (which also loads from %52). We then might change all loads and
14415   // stores to use Token1 as their chain operand, which could result in
14416   // copying %53 into %52 before copying %52 into %51 (which should
14417   // happen first).
14418   //
14419   // The problem is, however, that searching for such data dependencies
14420   // can become expensive, and the cost is not directly related to the
14421   // chain depth. Instead, we'll rule out such configurations here by
14422   // insisting that we've visited all chain users (except for users
14423   // of the original chain, which is not necessary). When doing this,
14424   // we need to look through nodes we don't care about (otherwise, things
14425   // like register copies will interfere with trivial cases).
14426
14427   SmallVector<const SDNode *, 16> Worklist;
14428   for (const SDNode *N : Visited)
14429     if (N != OriginalChain.getNode())
14430       Worklist.push_back(N);
14431
14432   while (!Worklist.empty()) {
14433     const SDNode *M = Worklist.pop_back_val();
14434
14435     // We have already visited M, and want to make sure we've visited any uses
14436     // of M that we care about. For uses that we've not visisted, and don't
14437     // care about, queue them to the worklist.
14438
14439     for (SDNode::use_iterator UI = M->use_begin(),
14440          UIE = M->use_end(); UI != UIE; ++UI)
14441       if (UI.getUse().getValueType() == MVT::Other &&
14442           Visited.insert(*UI).second) {
14443         if (isa<MemSDNode>(*UI)) {
14444           // We've not visited this use, and we care about it (it could have an
14445           // ordering dependency with the original node).
14446           Aliases.clear();
14447           Aliases.push_back(OriginalChain);
14448           return;
14449         }
14450
14451         // We've not visited this use, but we don't care about it. Mark it as
14452         // visited and enqueue it to the worklist.
14453         Worklist.push_back(*UI);
14454       }
14455   }
14456 }
14457
14458 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
14459 /// (aliasing node.)
14460 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
14461   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
14462
14463   // Accumulate all the aliases to this node.
14464   GatherAllAliases(N, OldChain, Aliases);
14465
14466   // If no operands then chain to entry token.
14467   if (Aliases.size() == 0)
14468     return DAG.getEntryNode();
14469
14470   // If a single operand then chain to it.  We don't need to revisit it.
14471   if (Aliases.size() == 1)
14472     return Aliases[0];
14473
14474   // Construct a custom tailored token factor.
14475   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
14476 }
14477
14478 bool DAGCombiner::findBetterNeighborChains(StoreSDNode* St) {
14479   // This holds the base pointer, index, and the offset in bytes from the base
14480   // pointer.
14481   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
14482
14483   // We must have a base and an offset.
14484   if (!BasePtr.Base.getNode())
14485     return false;
14486
14487   // Do not handle stores to undef base pointers.
14488   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
14489     return false;
14490
14491   SmallVector<StoreSDNode *, 8> ChainedStores;
14492   ChainedStores.push_back(St);
14493
14494   // Walk up the chain and look for nodes with offsets from the same
14495   // base pointer. Stop when reaching an instruction with a different kind
14496   // or instruction which has a different base pointer.
14497   StoreSDNode *Index = St;
14498   while (Index) {
14499     // If the chain has more than one use, then we can't reorder the mem ops.
14500     if (Index != St && !SDValue(Index, 0)->hasOneUse())
14501       break;
14502
14503     if (Index->isVolatile() || Index->isIndexed())
14504       break;
14505
14506     // Find the base pointer and offset for this memory node.
14507     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
14508
14509     // Check that the base pointer is the same as the original one.
14510     if (!Ptr.equalBaseIndex(BasePtr))
14511       break;
14512
14513     // Find the next memory operand in the chain. If the next operand in the
14514     // chain is a store then move up and continue the scan with the next
14515     // memory operand. If the next operand is a load save it and use alias
14516     // information to check if it interferes with anything.
14517     SDNode *NextInChain = Index->getChain().getNode();
14518     while (true) {
14519       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
14520         // We found a store node. Use it for the next iteration.
14521         ChainedStores.push_back(STn);
14522         Index = STn;
14523         break;
14524       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
14525         NextInChain = Ldn->getChain().getNode();
14526         continue;
14527       } else {
14528         Index = nullptr;
14529         break;
14530       }
14531     }
14532   }
14533
14534   bool MadeChange = false;
14535   SmallVector<std::pair<StoreSDNode *, SDValue>, 8> BetterChains;
14536
14537   for (StoreSDNode *ChainedStore : ChainedStores) {
14538     SDValue Chain = ChainedStore->getChain();
14539     SDValue BetterChain = FindBetterChain(ChainedStore, Chain);
14540
14541     if (Chain != BetterChain) {
14542       MadeChange = true;
14543       BetterChains.push_back(std::make_pair(ChainedStore, BetterChain));
14544     }
14545   }
14546
14547   // Do all replacements after finding the replacements to make to avoid making
14548   // the chains more complicated by introducing new TokenFactors.
14549   for (auto Replacement : BetterChains)
14550     replaceStoreChain(Replacement.first, Replacement.second);
14551
14552   return MadeChange;
14553 }
14554
14555 /// This is the entry point for the file.
14556 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
14557                            CodeGenOpt::Level OptLevel) {
14558   /// This is the main entry point to this class.
14559   DAGCombiner(*this, AA, OptLevel).Run(Level);
14560 }